Python计算器使用3 numb有问题

2022-05-21 07:50:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚开始学习python,我创建了一个计算器。
我在用乘法和除法做三位数运算时遇到了困难。
我将变量Number3设置为零,这样如果没有第三个数字,它就不会影响操作,因此它将是1+1+0= 2,但如果不是+-,它将最终影响答案。
所以我所做的就是创建一个值为1的变量Number4,然后把它加到乘法和除法的elif语句中 不过,我觉得它马虎,有一个更好的方法来获得效果。最好的办法是什么?你知道吗

print ("Python calculator")
print ("""
Select an operation below
1: Add
2: Sub
3: Mult
4: Div

""")

def add(x, y, z):
   return x + y + z
def sub(x, y, z):
   return x - y - z
def mult(x, y, z):
   return x * y * z
def div(x, y, z):
   return x / y / z

Operation = input ("Enter Operation Number")

Number1 = int(input ("Enter Your First Number"))
Number2 = int(input ("Enter your Second Number"))
Number3 = (0)

More = input ("Do you have more numbers? (Yes or No)")
if More == "yes" or More == "Yes":
    Number3 =int(input ("What is your other number?"))
    print ("calculating")
else:
    print ("calculating")

if Operation == '1':
   print(add(Number1,Number2,Number3))

elif Operation == '2':
   print(sub(Number1,Number2,Number3))

elif Operation == '3'and More != "Yes":
  Number4 = 1
  print(mult(Number1,Number2,Number4 ))

elif Operation == '3':
   print(mult(Number1,Number2,Number3 ))

elif Operation == '4'and More != "Yes":
  Number4 = 1
  print(div(Number1,Number2,Number4 ))

elif Operation == '4':
   print(div(Number1,Number2,Number3 ))
else:
   print("Invalid inputs")

Tags: divinputreturndefmoreoperationyesprintenterelifmultnumber1number2number3number4
1条回答
网友
1楼 ·

我会设置

Number3 = None 

然后将逻辑内部化为具有默认参数的函数

def add(x, y, z=None):
   return x + y + (0 if z is None else z) 
def sub(x, y, z=None):
   return x - y -  (0 if z is None else z) 
def mult(x, y, z=None):
   return x * y * (1 if z is None else z) 
def div(x, y, z=None):
   return x / y /  (1 if z is None else z)

那么所有这些都应该像预期的那样工作

print(mult(Number1,Number2))
print(mult(Number1,Number2,1))
print(mult(Number1,Number2,0))
print(mult(Number1,Number2,None))