I'm new to coding and Python is the first language I am learning. I'm trying to develop a basic calculator. The numbers can't be equal to zero and the user must use numbers 1-4 to choose between addition, subtraction, multiplication and division.
My challenge is: when I input a number equal to zero or a number that is not 1-4, the functions should prompt me to enter the right value, then update the variable to continue accordingly with the calculation. The code generates the error message and asks for a new input for the number but it is not saving the new input so it doesn't produce the right outputs.
For example, if I enter a number == 0, it prompts me to enter a new one, but then it keeps zero as the first number. Then if I do the same for the second number, the program stalls and it doesn't calculate anything.
If anyone could help me, I would appreciate tremendously... I apologize if this is not the most elegant code ever, but please keep in mind this is my first try...:-))
I posted this code on dpaste in case seeing it here doesn't work: strong texthttps://dpaste.de/hyKa
def number (n):
while n == 0:
print ("ERROR - number must be different than zero")
n = float(input("Enter a different number. \n"))
number (n)
return n
x = int(input("Enter your first number. \n"))
number (x)
def operator_control (user_choice):
while user_choice > 4 or 1 > user_choice:
print ("ERROR - you must choose either 1, 2, 3, or 4 depending on the operation you want")
user_choice = int(input("Let's try again - enter another number for the operator \n"))
return user_choice
return user_choice
user_choice = int(input("Now you will choose the operation! Ready? Choose 1 for addition, 2 for subtraction, 3 for multiplication and 4 for division \n"))
operator_control (user_choice)
z = int(input("Please choose your second number as the operand for the calculation. \n"))
number (z)
operator = user_choice
if operator == 1:
result = x + z
print ("Ok - you chose to add your first number," , x , "to" , z , "and the result of this calculation is" , result)
if operator == 2:
result = x - z
print ("Awesome - you chose to subtract your second number," , z , "from" , x , "and the result of this calculation is" , result)
if operator == 3:
result = x * z
print ("Fantastic! You chose to multiply your first number," , x , "by the second one" , z , "and the result is" , result)
if operator == 4:
result = x / z
print ("Fabulous! You chose to divide your first number," , x , "by the second one" , z , "and the result is" , result)