If your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?
Answer from CambridgeCro on Stack OverflowIf your inputs are "sometimes" ints and "sometimes" floats then just wrap each input in a float(). You could make something more complex, but why would you?
You could check for the presence of a decimal point in your string to decide if you want to coerce it into a float or an int.
number = input()
if '.' in number:
number = float(number)
else:
number = int(float(number))
My current code accepts integers that are greater than 0, which is what I want, but I also want to accept floats/decimals as well. How would I do this? Here is my current code:
while True:
try:
time = int(input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continue
if time > 0:
givenTime[2] = time
breakIndentation is off here for some reason, but believe me when I say that the indentation in the actual code is correct..
Can I just do time = int or float(input("How much time has elapsed since your last stop (in hours)?")) or would this be wrong? Any help would be appreciated.
edit: nope,
time = int or float(input("How much time has elapsed since your last stop (in hours)?"))
doesn't work.
I don't understand why you don't just use floats?
while True:
try:
time = float(raw_input("How much time has elapsed since your last stop (in hours)?"))
except ValueError:
print("Enter a valid number of hours!")
continue
By typing an integer value, it'll just turn it into a float anyway.
here's something I wrote a few months ago for a similar question. Figure out how to modify it to do what you want:
def input_type(msg, type_converter):
while True:
s = input(msg)
try :
return type_converter(s)
except ValueError as e:
print(e)
def input_lessthan(msg, maximum, type_converter=int):
while True:
n = input_type(msg, type_converter)
if n <= maximum:
return n
print("Please enter a number less than {}".format(maximum))
print(input_lessthan("hours worked> ", 168, float))
How to make python accept both int and float input???
How would I make a program only accept floats and integers?
Beginners Question Float
What are blank float inputs defined as? Clearly not zero
So I have a program that has an input variable like ‘money = float(input(“How much money do you have?”)) ‘ I want to know in case I make a typo and add a string like inputting “5t6” I want the program to ask the question “please input a float” instead of just crashing. What would I do for that?