python - 我的 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 验证循环中,即使给出了一个有效的答案,它仍然不会中断
请允许我事先道歉,但我现在只编写 python 大约 3 天,所以如果我的代码可以通过使用不同的方法得到更好的优化,这就是我没有这样做的原因
但是由于某种原因,当我没有将整个程序定义为函数时,它开始正常工作,但是我这样做是为了更容易让用户选择重新启动程序
编辑:所以我发现了问题,这是因为我正在尝试输入我实际上还没有编码,谢谢你提醒我检查我身边的错误
解决方案
给你,无论你在做什么都很复杂,所以这里是它的简单版本:
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')
推荐阅读
- sql - 如何在 VB.Net 代码中处理带分号和单引号的 MS SQL 密码?
- html - Web Scraping:从 HTML 表格中重新格式化信息
- c# - C# 禁用 WncProc 上的调整大小自定义控件
- solr - Solr 在 Alfresco 6.2 中无法正常工作
- postgresql - Postgresql 不使用创建的功能索引
- amazon-web-services - 从 CLI 创建表时如何创建多个 GSI - DynamoDB
- apache-kafka - 无法注册 avro 架构
- javascript - 如何通过单击元素删除类
- android - 如何使用 dagger 2 和 kotlin 在活动中注入可为空的类型
- flutter - 颤振处理TextFormField的输入键,忽略焦点变化