python - 我们究竟如何在 Python 中使用“继续”?
问题描述
i=0
while (i==0):
n1=float(input("Enter the first number: \n"))
n2=float(input("Enter the second number: \n"))
a=str(input("Choose the operation: \n 1.) + \n 2.) - \n 3.) * \n 4.) / \n 5.) % \n"))
if(a==1):
print("The addition of the inputted numbers is ", sum(n1,n2),"\n")
elif(a==2):
print("The difference between the inputted numbers is ", diff(n1,n2),"\n")
elif(a==3):
print("The multiplication of the inputted numbers is ", product(n1,n2),"\n")
elif(a==4):
print("The division of the inputted numbers is ", div(n1,n2),"\n")
elif(a==5):
print("The modulus of the inputted numbers is ", modulus(n1,n2),"\n")
else:
print("Do you want to quit the calculator?")
b=int(input("Press 00 for 'Yes' and 11 for 'No'\n"))
if(b==00):
break
else:
print("Enter a valid option for the operation number.\nThe calculator is re-starting.")
continue
这是我的python代码。我已经定义了这里使用的所有函数。
我得到的输出是:
当我在图像中圈出的位置输入正确的操作编号 3 时,为什么输出没有给我最终计算出的答案?为什么它一次又一次地重复相同的循环?
请帮助我。
解决方案
Hacker 已经为您提供了所有需要完成的更改。您需要查看整数与字符串的比较、while 循环的使用情况以及 Try-Except 选项。
为了帮助您有一个参考点,这里有修改后的代码供您比较:
while True:
while True:
try:
n1=float(input("Enter the first number: \n"))
break
except:
print ('Enter a number. It can be integer or float')
while True:
try:
n2=float(input("Enter the second number: \n"))
break
except:
print ('Enter a number. It can be integer or float')
while True:
try:
a=int(input("Choose the operation: \n 1.) + \n 2.) - \n 3.) * \n 4.) / \n 5.) % \n"))
if 1 <= a <= 5:
break
else:
print ('Enter a number within range 1 and 5')
except:
print ('Not a number. Please enter an integer')
if (a==1):
print("The addition of the inputted numbers is ", (n1+n2),"\n")
elif (a==2):
print("The difference between the inputted numbers is ", (n1-n2),"\n")
elif (a==3):
print("The multiplication of the inputted numbers is ", (n1*n2),"\n")
elif (a==4):
print("The division of the inputted numbers is ", n1/n2,"\n")
elif (a==5):
print("The modulus of the inputted numbers is ", int(n1%n2),"\n")
print("Do you want to quit the calculator?")
while True:
try:
b=int(input("Press 00 for 'Yes' and 11 for 'No'\n"))
if b==0: break
elif b!= 11: print ('Enter a valid option: 00 or 11')
except:
print ('Not a number. Please enter an integer')
推荐阅读
- firebase - Firebase Firestore https 可调用云函数中出现未经验证的错误
- jenkins - 詹金斯不以全尺寸打开浏览器窗口
- javascript - 将对象中的内容添加到 JQUERY-CONFIRM
- html - Bootstrap 4 - col 中的固定底部消息框(类似松弛的界面)
- javascript - 选择 createElement JS 创建的标签
- python - 落在网格网格之外的数据点被插值,而网格网格肯定覆盖了这些点
- python - 定义一个 Python 函数以重命名将名称和路径作为参数传递的文件
- javascript - 如何在验证器启动之前降低大小写信息
- javascript - 检查两个属性及其各自的值是否在对象数组中重复
- python - 如何将创建新选项卡与编辑配对