Why do some floats convert to integers and others don't in this Python code?
I've tested the following code with various floats as input (e.g. 11.1, 11.5, 44.5, 22.5, etc.) and sometimes the code returns, for example, "x is 11" and sometimes it returns "x is not an integer." Why?
def main():
x = get_int("What's x? ")
print (f'x is {x}')
def get_int(prompt):
while True:
try:
return int(input(prompt))
except ValueError:
print("x is not an integer.")
try:
return int(float(input(prompt)))
except ValueError:
print("x is not an integer.")
else:
return x
main()
CodePudding user response:
This is what you were thinking of. If it works as an integer return it. Otherwise, try that SAME STRING as a float.
def main():
x = get_int("What's x? ")
print (f'x is {x}')
def get_int(prompt):
while True:
i = input(prompt)
try:
return int(i)
except ValueError:
print("x is not an integer.")
try:
return int(float(i))
except ValueError:
print("x is not a float.")
else:
return x
main()
CodePudding user response:
On line number 8 the input()
will only accept text of type int
. Therefore if you input a float
it will throw a ValueError
. But on line number 12 the input is being converted to a float
then it is being converted to an int
. Which does not throw a ValueError
.