我的while验证循环不接受有效答案并中断,自动移动到else语句


# this is a simple calculator
import sys

def calculation():
print('what is the first number?')
x = int(input())
print('what is the second number?')
y = int(input())
# these two lines ask for the two numbers
print('would you like to do multiplication, division, addition, or subtraction?')
# the following loop makes the user choose which operator they wish to use
while True:
input_a = input()
if input_a == 'multiplication' or input_a == 'division' or input_a == 'addition' or input_a == 'subtraction':
break
else:
print('please choose a valid option')
if input_a == 'multiplication':  # the multiplication calculation
print(str(x) + ' multiplied by ' + str(y) + ' is equal to:')
def multiply():
return x*y
print(multiply())
elif input_a == 'division':
print(str(x) + ' divided by ' + str(y) + ' is equal to:')
def divide():
try:
return x/y
except ZeroDivisionError:
print('you cannot divide by zero')
print(divide())

print(calculation())
while True:  #this loop repeats the program
calculation()
print('would you like to repeat? y/n')
input_b = input()
if input_b == 'n':
sys.exit()

我不太确定为什么,但在我的while验证循环中,即使给出了一个有效的答案,它仍然不会打破

请允许我事先道歉,但是我现在只写了大约3天的python代码,所以如果我的代码可以通过使用不同的方法更好地优化,那就是我没有这样做的原因

由于某种原因,当我没有将整个程序定义为一个函数时,它开始正常工作,但是我这样做是为了更容易地提供用户选择重新启动程序的选项

编辑:所以我发现了这个问题,这是因为我正在尝试输入,我实际上还没有编码,谢谢你提醒我检查我这边的错误

好了,不管你在做什么都很复杂下面是简单的版本:

def add(x,y):   
return(x+y)
def sub(x,y):   
return(x-y)
def mult(x,y):  
return(x*y)
def div(x,y):
return(x/y)
while True:
x=int(input('First No.: '))
y=int(input('First No.: '))
method=input('Operator: ')#will call a specific function from the dictionary
functs={'add':add(x,y),'subtract':sub(x,y),'multiply':mult(x,y),'divide':div(x,y)}
print(functs[method.lower()])#print the required result
choice=input('Continue? Y/N: ')
if choice=='N':
break
print('Loop Break')

相关内容

  • 没有找到相关文章

最新更新