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 (Retired) Things That Count Exceptions

Why doesn't the following code work for float ?

user_string = input("What is your string? ") user_num = input("What is your number? ") my_num = int(user_num) print(user_string[my_num]) When the user inputs a float value, it should convert it into an integer as it does with... say int(5.5). Thanks in advance!

2 Answers

Convert it to a float and then an int. You're attempting to convert a string that doesn't look like an integer into an integer, so you need to cast it into a float first, which can be converted into an int.

int(float(user_num))

Hey Manobhav!

Cory's answer is correct, but to spell it out a little more clearly, and answer your question of Why? The reason your code doesn't work is because input() returns a string, even if what the user types in is an integer or a float. In other words, when they type in -- for example -- 5.5, Python turns that float into the string '5.5'. Then, when you attempt to turn that string into an int, Python throws an error that basically says "This is a decimal number; you can't make it into an int." So, as Cory said, the answer is to first convert it into a float, and then convert that float into an int. Kind of irritating, but logical. : )

I hope this helps! Please select this as the Best Answer if it proved most helpful to you.

Thanks! and Be Well, Graham