Why don't I need to define my variable as a float or integer?

How come you don’t add “_int” or “_float” to define whether it’s a float or an integer?

6 Likes

Python is not type cast, but type assigned. A variable gets its type from the value assigned to it. We do not have to declare the type.

pi = 3.1416

It will be a float by assignment.

int_pi = int(pi)

will parse the integer out of the value.

str_pi = str(pi)

will cast the value to a string.

Nothing prevents us from changing the values in any of the above to another type. We can change from one type to another and simply re-use variables, but we cannot perform operations on unmatched types.

1 + "1"

will throw an error.

We can even help garbage collection by releasing objects when they are no longer needed.

my_huge_array = None

The array will vanish, assuming there are no other references still in play.

19 Likes

I am trying to get back into coding and having worked with Java before, I will admit that this was making me bang my head against the wall! Thank you for the explanation, one thing I did notice though. According to the example below, you can still cast the type depending on how you want your expressed.
myfloat = 7.0
print(myfloat)
myfloat = float(7)
print(myfloat)
I got that from here

hello there,

for the statement: str_pi = int(pi), will it round pi or just see the first number before the decimal?

Don’t bother trying to learn small individual facts about what various things do, you’ll never get a complete picture of things that way. Get into the habit of looking it up instead.
https://docs.python.org/3/library/functions.html

which is the integer part of that number, as you will find in your reading.

I don’t understand the significance of the variables “int” and “float”. the exercise does not require that you use either. You just write release_year = 2019, not int= 2019 or release_year_int = 2019 or anything like that. why does it matter whether the release year is an integer or a float?