我仍在学习Python的基础知识,但是我被困在试图完成的自定义计算器程序中。
while True:
print('Welcome. Below, type the number associated to begin calculating:')
print('1: Addition')
print('2: Subtraction')
print('3: Multiplication')
print('4: Division')
pick = int(input('Enter the number associated with your calculation: '))
if pick != (1, 5):
print('Please enter an option given.')
else:
continue
def addNumber():
if pick == 1:
print('-------------------------')
print('You have chosen #1 - Addition.')
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
print('Your sum is equal to:', num1 + num2)
print('-------------------------')
addNumber()
第一个功能是加法,其余功能对于每个选择都是其自己的。下一部分是底部,允许用户在选择后重新启动。
again = str(input('Would you like to calculate again?\n'))
if again == 'Yes':
continue
else:
break
如果用户尝试将值放在1-4的范围之外(提示再次尝试),则没有问题,但是如果有人选择了显示的选项(如应该的那样),{{1} }出现。
'Please enter an option given.'
我应该如何重写if / else参数?
答案 0 :(得分:0)
好吧,您的if块可能看起来像这样:
if pick not in range(1, 5):
print('Please enter an option given.')
continue
else:
functions[pick]()
您可以在顶部定义functions
字典,如下所示:
functions = {1: addNumber, 2: subNumber, 3: multiplyNumber, 4: divideNumber}
并像使用addNumber()
一样使用其余功能。
答案 1 :(得分:0)
我想您在if pick in range(1, 5):
这一行中有问题
这是我的建议:
def addNumber():
if pick == 1:
print('-------------------------')
print('You have chosen #1 - Addition.')
num1 = int(input('Enter your first number: '))
num2 = int(input('Enter your second number: '))
print('Your sum is equal to:', num1 + num2)
print('-------------------------')
while True:
print('Welcome. Below, type the number associated to begin calculating:')
print('1: Addition')
print('2: Subtraction')
print('3: Multiplication')
print('4: Division')
pick = int(input('Enter the number associated with your calculation: '))
if pick in range(1, 5):
if pick==1:
addNumber()
elif pick==2:
subsNumber() # just as an example, but you can replace it
elif pick==3:
MultipNumber() # same
else:
divideNumber() # same
else:
print('Please enter an option given.')