【发布时间】:2019-12-27 21:29:24
【问题描述】:
我是 python 新手,正在编写以下代码(查找平均值的程序)
sum=0
for i in range(1,9999):
n=int(input("Enter your number: "))
i+=1
sum=n+sum
a=input("Do you want to add more (Y/N): ")
if a=="Y" or a=="y":
continue
elif a=="N" or a=="n":
break
else:
print("Error: Incorrect choice")
i-=1
avg=sum/i
print(avg)
一切都好,但如果用户输入“不正确的选择”,我怎样才能让它跳转到“if 语句”,再次询问用户是否要添加更多数字?在结构化编程中,我认为可以使用“goto”或“label”,但是 python 是面向对象的,我怎样才能让它在这里工作。请指教。
【问题讨论】:
-
Python 中有多种形式的control-flow。我建议您先阅读这些内容。它们是 Python 构建块的一部分。 Python 中没有“Goto”,只有控制流语句,包括 while、for、函数调用、生成器和条件。
-
就您的程序而言,您可以将输入语句和 Y/N 检查添加到嵌套的
while循环中。
标签: python python-3.x while-loop goto