如果输入负数,则停止while循环



我刚开始学习Python,现在我被WHILE循环卡住了,所以如果你能给我一些建议,我将不胜感激。

所以,这是我的代码,如果我输入负数并打印("输入错误"(,我需要的是停止整个代码,但我的代码在输入负数时仍然会通过并打印我("平均价格:"(。当我输入例如(2,3,6,-12(时,我不想打印("平均价格是:"(-只想打印("错误输入"(。我现在我的最后一张照片在WHILE循环中,但我正在努力寻找解决方案:(也许有更简单的解决方案,但正如我所说,我是新手,仍在学习提前谢谢。

price= int(input("Enter the price: "))
price_list=[]
while price!= 0:
price_list.append(price)
if price< 0:
print("Wrong entry")
break
price=int(input())
price_sum= sum(price_list)
print(f"Avg price is: {price_sum / len(price_list)}")

使用while/else循环可以产生所需的行为。

  • 如果遇到while循环中的中断,则else中的代码不会运行

代码

price= int(input("Enter the price: "))
price_list=[]
while price!= 0:
price_list.append(price)
if price< 0:
print("Wrong entry")
break
price=int(input())
price_sum= sum(price_list)
else:
print(f"Avg price is: {price_sum / len(price_list)}")

如果你不想在得到负数时运行其余的代码,你可以这样做:

price= int(input("Enter the price: "))
ok = True
price_list=[]
while price!= 0:
price_list.append(price)
if price< 0:
print("Wrong entry")
ok = False
break
price=int(input())
if ok:
price_sum= sum(price_list)
print(f"Avg price is: {price_sum / len(price_list)}")

因为它在循环之外,所以它将始终运行。

所以试试这个:

price= int(input("Enter the price: "))
price_list=[]
while price != 0:
if price< 0:
print("Wrong entry")
break
price_list.append(price)
price=int(input())            
price_sum= sum(price_list)
if price > 0:
print(f"Avg price is: {price_sum / len(price_list)}")

这里有两个选项。您可以在while保护中包含检查,如while price > 0您可以使用关键字break并在循环中添加if保护,如

if price < 0:
break

由于第一次输入价格时它在循环之外,所以最好的方法是将guard添加到while循环中,以便在第一次输入为负数的情况下跳过它。

您在这里进行过程编程。print在循环外声明它。此外,没有控制语句检查该语句。因此,不管输入是什么,print语句都会被执行。

由于任何非空列表都是真值,因此可以检查该列表是否为空或是否包含一些元素

price= int(input("Enter the price: "))
price_list=[]
while price!= 0:

if price< 0:
print("Wrong entry")
break
price_list.append(price)
price=int(input())
if price_list:
price_sum= sum(price_list)
print(f"Avg price is: {price_sum / len(price_list)}")

最新更新