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 (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