I want my function to keep asking the user for an input until it satisfies all criteria. My function is as follows:
def PromptNumber(Text, Positive, Integer):
while True: #Keep asking for value until input is valid
Input = input(Text)
try: #Check if input is float
Input = float(Input)
except:
print('You must enter a valid number.')
continue
if Positive:
if Input < 0: #Check if input is negative
print('You must enter a valid number (positive).')
continue
else:
print("Positive else")
if Integer:
try: #Check if input is integer
Input = int(Input)
except ValueError:
print('You must enter a valid number (integer).')
continue
break
else:
print("Integer else")
break
return Input
Where the parameters are:
- Text: a string for the question I will ask
- Positive: a boolean to define whether the input must be positive
- Integer: a boolean to define whether the input must be an integer
This works okay for most questions however when calling the function with 2 True booleans (positive integer) like so PromptNumber("hi", True, True), it will keep asking for an input if the value is negative - as intended. But it will still accept non-integer values as long as they are positive.