In python, when I try to cast a float input by the user into an integer, I get an error. This is the code
x=int(input("Choose a number: "))
The I input a float (3.0 is what I put), and I get this error:
ValueError: invalid literal for int() with base 10: ‘3.0’
But when I try to cast an integer input by the user into a float, it works perfectly fine. This is the code for that
x=float(input(Choose a number: "))
Then I put in an integer (3 in my case), and it casts it and stores the value without a problem
When I initially got the error from trying to cast the float into an integer, I tried the opposite, like I said above, casting an integer into a float. I thought this would also result in an error, but it didn’t, and casted the integer like I initially expected it would have done to the float. I am left wondering why it works one way but not the other
Capocho is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
3
From what I understand, the Input() function by default returns the data in the form of a string, and int() function expects a number or a string with no dots (.).
Try this:
x = int(float(input(“Choose a number: “)))
here is another question that has the same issue as well:
int() not working for floats?
Omar Ali is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.