如何在Python中使用执行循环3次?

AJP AJP

我正在尝试学习Python3。以下是基本程序。在这里,我想将重试次数限制为3次。如何在Python中实现。提前致谢。

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

print("Select Operation from below:")
print("1.Addition")
print("2.Subtraction")
print("3.Multiplication")
print("4.Division")

while True:
    choice= int(input("Enter your Choice(1,2,3,4)  from above:"))
    if choice in (1,2,3,4):
        num1 = float(input("Enter first number :"))
        num2 = float(input("Enter second number :"))
        if choice == 1:
            print("Addition of 2 numbers {} and  {} is {} ".format(num1,num2,add(num1,num2)))
        elif choice == 2:
            print("Subtraction of 2 numbers {} and  {} is {} ".format(num1,num2,sub(num1,num2)))
        elif choice == 3:
            print("Multiplication of 2 numbers {} and  {} is {} ".format(num1,num2,mul(num1,num2)))
        elif choice == 4:
            print("Division of 2 numbers {} and  {} is {} ".format(num1,num2,div(num1,num2)))
        break
    else:
        invalidCount =0
        if invalidCount <=3:
            invalidCount += 1 
            print("Invalid Input with retry no {}".format(invalidCount))
        else:
            print("Exceeded maximum number of Invalid re-try")  

             
中学

超过以下重试次数时,您需要打破循环:

....
else:
   print("Exceeded maximum number of Invalid re-try")  
   break##This will ensure you break from the immediate loop like while in your case.  

您的代码中的问题是,每当invalidCount用户输入无效的输入时,您都将其重置为0。您应该在循环之外初始化该变量。

另一种查看方式是将while条件本身修复为:

invalidCount = 0
while invalidCount <= 3:

然后在该else部分中,您只需增加,invalidCount这会使您的代码更简洁明了。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Python-如何在for循环中使用return语句?

如何在python中使用循环创建元组

如何在python中使用循环创建多个类对象?

如何在Python中使用C样式的循环?

如何在python中使用for循环在列表中添加值?

如何在python中使用for循环附加多维数组

如何在PHP中使用foreach循环执行多维数组?

如何在python中使用子列表执行计算

python:如何在findall中使用for循环

如何在python中使用turtle模块循环颜色?

如何在python中使用交叉验证执行GridSearchCV

如何在python的Axes3D中使用循环绘制图例?

如何在Python中使用循环从JSON提取元素?

Python:如何使用for循环执行我的代码5次?

如何在Python 3中使用列表推导对矩阵执行数学运算?

如何在循环python外的for循环中使用变量

如何在Python中使用for循环创建嵌套字典?

如何在python中使用Selenium执行右键单击?

如何在python中使用double while循环?

如何在python中使用for循环逐行读取

如何在Python中使用单个for循环遍历3个不同的数组

如何在PostgreSQL中使用循环序列执行排序

如何在python中的循环(n次迭代)中使用异常处理,以便结果存储在文件中但循环不会终止?

如何在 CrateDB 中使用 python 执行批量插入?

如何在我的 Python 代码中使用 while 循环

如何在 Python 3 中使用 exit()

如何在python中使用函数和循环调用变量

如何在python中使用条件执行矩阵乘法?

我们如何在 kv 文件中使用循环创建多行?(Python3,kivy)