Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Basics Types and Branching Numeric

i didnt quite understand what the float and int command does can you please elaborate on it a bit more

i didnt quite understand what the float and int command does can you please elaborate on it a bit more

1 Answer

Hi Jamshaid!

The int() and float() functions perform variable conversions - also called "casting".

This allows you to change the datatype of a variable in cases where you may need to change the datatype because, say, a certain function only accepts or a certain operation only works properly with specific data types.

Consider this code:

num_int = 1 # datatype = integer
num_string = '1' # datatype = string

new_num_int = int(num_str) # datatype = integer (because it was cast/converted from a string to an integer)

For example:

print("There are " + 7 + " days in one week.")

will produce this error:

TypeError: must be str, not int

however, this:

print("There are " + str(7) + " days in one week.")

will not.

More info:

https://www.w3schools.com/python/python_casting.asp

I hope that helps.

Stay safe and happy coding!