I’m trying to write a program in Python where the user is asked to input a number of hours after which a countdown starts in seconds, however I want to also make sure that no floats/strings are inputted and if they are, the user needs to be prompted with the same question and input a correct value. If an integer is inputted then I want the program to jump to the next statement (hence ‘pass’ on line 4). However, whatever I type in, the program always jumps to the next statement, regardless of whether it’s a string or a float.
JavaScript
x
10
10
1
TimeHours = input("Countdown time in hours:")
2
3
while isinstance(TimeHours, int) is True:
4
pass
5
if float(TimeHours) / 1 != int(float(TimeHours)):
6
input('Please input a whole number, decimals are not accepted.')
7
elif isinstance(TimeHours, str):
8
input('Alphabetical letters or unknown characters are not allowed, e.g. A, B, C, (, *')
9
continue
10
I tried using if statements and defining functions, but I can’t seem to make it work.
Advertisement
Answer
like this
JavaScript
1
9
1
while True:
2
TimeHours = input("Countdown time in hours:")
3
try:
4
TimeHours = int(TimeHours)
5
break
6
except ValueError as e:
7
print('Alphabetical letters or unknown characters are not allowed, e.g. A, B, C, (, *')
8
continue
9