【问题标题】:In python how can I take input from user and jump to a different line after taking input?在 python 中,如何获取用户的输入并在输入后跳转到不同的行?
【发布时间】: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


【解决方案1】:

有几种方法 你可以使用“while”

while a not in ["Y","y","N","n"]:
    a=input("Do you want to add more (Y/N): ")

【讨论】:

  • 非常感谢 azro,我能够理解这一点,但想不出在上面的代码中添加它的方法。
猜你喜欢
  • 1970-01-01
  • 2012-10-19
  • 1970-01-01
  • 1970-01-01
  • 2020-10-04
  • 1970-01-01
  • 1970-01-01
  • 2011-08-25
相关资源
最近更新 更多