我是编码新手,Python是我学习的第一门语言。我正在尝试开发一个基本的计算器。数字不能等于零,用户必须使用数字1-4来选择加法,减法,乘法和除法。
我的挑战是:当我输入一个等于零的数字或一个不是1-4的数字时,这些函数应该提示我输入正确的值,然后更新变量以相应地继续计算。代码生成错误消息并要求输入该数字的新输入,但它不保存新输入,因此它不会产生正确的输出。
例如,如果我输入一个数字== 0,它会提示我输入一个新数字,但它会保持零作为第一个数字。然后,如果我对第二个数字执行相同操作,程序会停止并且它不会计算任何内容。
如果有人可以帮助我,我会非常感激......如果这不是最优雅的代码我会道歉,但请记住这是我的第一次尝试...: - ))
我在dpaste上发布此代码,以防在此处看到它无效:强文 https://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)