When the user inputs anything but a number for the first input, the program should quit. But instead it just keeps going.
I tried to put many if ... break statements in the main function after the "a" to break it, but nothing helped.
def is_number(str):
try:
float(str)
return True
except ValueError:
return False
def is_valid_operator(operator):
operators = (' ', '-', '*', '/')
return operator in operators
def ask_for_a_number(force_valid_input):
while force_valid_input is True:
a = input('Please provide a number: ')
if is_number(a):
return float(a)
else:
if not force_valid_input:
return None
print("This doesn't look like a number, try again!")
def ask_for_an_operator(force_valid_input):
while force_valid_input is True:
operator = input('Please provide an operator: ')
if is_valid_operator(operator):
return operator
else:
if not force_valid_input:
return None
print('Unknown Operator')
def calc(operator, a, b):
if not is_number(a) or not is_valid_operator(operator) or not is_number(b):
return None
result = 0
if operator == ' ':
result = a b
elif operator == '-':
result = a - b
elif operator == '*':
result = a * b
elif operator == '/':
if b != 0:
result = a / b
else:
print('Error: Divide by zero is not allowed')
return None
return result
def main():
while True:
a = ask_for_a_number(force_valid_input = True)
operator = ask_for_an_operator(force_valid_input = True)
b = ask_for_a_number(force_valid_input = True)
result = calc(operator, a, b)
if result is not None:
print(f'The result is {result}')
if __name__ == '__main__':
main()
CodePudding user response:
Your main problem is that you are using a while loop with True but never order it to stop. You'd need a break
somewhere in there.
On another note, you don't need to check if a boolean is True
, you can just do if bool
or while bool
as it returns True or False anyway.
CodePudding user response:
You can just add a condition like below in main function
a = ask_for_a_number(force_valid_input = True)
if a == 'break':
break
And in the function ask_for_a_number return the 'break' string like below
print("This doesn't look like a number, try again!");
return 'break'
CodePudding user response:
You check whether a
is a number or not, but then don't do anything if it isn't one. So check the value of a
a = ask_for_a_number(force_valid_input = True)
if not a:
return