I'm new to python and am working on a simple calculator program for practice. I have created a loop for input validation but want to find a way to make my working function cleaner. Below is the original function that works.
def calculator():
first_num= input("First number: ")
second_num= input("Second number: ")
operation= ((input("Operation: (M, A, D, S) "))).upper()
while True:
if operation not in {"M", "A", "D", "S"}:
print("Invalid input: ")
operation = (input("Operation: (M, A, D, S) ")).upper()
else:
break
if operation == "M":
multiply(first_num,second_num)
elif operation == "D":
divide(first_num,second_num)
elif operation == "A":
add(first_num,second_num)
elif operation == "S":
sub(first_num,second_num)
Below is what I've tried to do to make a separate function
def calculator():
first_num= input("First number: ")
second_num= input("Second number: ")
operation= ((input("Operation: (M, A, D, S) "))).upper()
catch_operation(operation)
if operation == "M":
multiply(first_num,second_num)
elif operation == "D":
divide(first_num,second_num)
elif operation == "A":
add(first_num,second_num)
elif operation == "S":
sub(first_num,second_num)
def catch_operation(x):
while True:
if x not in {"M","A","D","S"}:
print("Invalid input: ")
x = (input("Operation: (M, A, D, S) ")).upper()
else:
return x
CodePudding user response:
Hmm. why do you still want to keep the while true in your function? why not just change it to:
def catch_operation(x):
while x not in {"M","A","D","S"}:
print("Invalid input: ")
x = (input("Operation: (M, A, D, S) ")).upper()
return x
CodePudding user response:
Moving the loop into a separate function as you've done is fine, but note that you need to assign the output of catch_operation(operation) to the variable operation before you parse it:
operation = ((input("Operation: (M, A, D, S) "))).upper()
operation = catch_operation(operation)