Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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!