2
age = input("how old are you? \n")
int(age)
print(type(age))
# <class 'str'>

age = input("how old are you? \n")
age_as_int = int(age)
print(type(age_as_int))
# <class 'int'>
SuperStormer
  • 4,997
  • 5
  • 25
  • 35
  • 4
    `int(age)` doesn't convert `age` in place, it returns a new `int` value that is based on the value of `age`. You could do `age = int(age)`, or just `age = int(input("how old are you?"))` to skip the intermediate step. – Samwise Aug 12 '22 at 23:11
  • his next question is going to be, okay but why. my best reasoning says that 1 reason is that different datatypes are stored using different amounts of memory, so changing a variables datatype requires a new place in memory to store it – Christian Trujillo Aug 12 '22 at 23:13
  • Does this answer your question? [Turn a variable from string to integer in python](https://stackoverflow.com/questions/50518635/turn-a-variable-from-string-to-integer-in-python) – SuperStormer Aug 12 '22 at 23:13
  • Gotcha, that makes perfect sense thank you! – Arthur Romo Aug 12 '22 at 23:57
  • 1
    Also, you want to at some point look into immutable types. https://stackoverflow.com/questions/8056130/immutable-vs-mutable-types Basically, a string can't be *modified*. For example, `foo.strip()` (removes surrounding spaces) doesn't modify `foo`, instead it returns a new string, which you can then assign to another variable `bar = foo.strip()`. On the other hand, a list variable can be modified. `li = [1,2,3] ; v = li.pop(); print(f"{v=}, {li=}");` – JL Peyret Aug 13 '22 at 00:38

1 Answers1

1

When you convert a data type to another using str(), int(), float() you need to assign the value to a variable, as you can see they are functions, they return something and if you don't put that something into a variable it gets lost.

for your first code to work it should be:

age = input("how old are you? \n")
age = int(age)
print(type(age))

or maybe

age = int(input("how old are you? \n"))
print(type(age))
Jean Carlo
  • 28
  • 5