繁体   English   中英

我希望我的 python 代码在用户请求或输入无效后重新开始

[英]I want my python code to start over again after the user has requested so or has given invalid input

如果用户提供了无效输入,我希望代码自行重复。 另一种询问方式是:

ans2 = input ('Do you want to continue (y/n)')
if ans2 == 'y':
#repeat the code and I don't know how to do that
if ans2 == 'n':
print ('Ok Goodbye')
exit

你可以把它放到循环中

while True:
    data = input("Enter data: ")

    if <valid_condition>:
        # do something
        ans2 = input('Do you want to continue (y/n)')
        if ans2 == "y":
            continue
        else:
            break
    else:
        print("Invalid data")
        ans2 = input('Do you want to continue (y/n)')
        if ans2 == "y":
            continue
        else:
            break
        

这是一个相当普遍的结构。

def yourcode():
   pass  # your code here

ans2 = ''
while not ans2 in ['y','n']:
   ans2 = input ('Do you want to continue (y/n)')
   if ans2 == 'y':
      yourcode()
      ans2 = ''
   elif ans2 == 'n':
      print ('Ok Goodbye')
      exit
   else:
      print('Invalid response')

您可以像下面这样在 function 中定义代码,您可以在最后调用 function 并再次重复调用它

def function():
    ans2 = input ('Do you want to continue (y/n)')
    if ans2 == 'y':
        function()
    if ans2 == 'n':
        print ('Ok Goodbye')
        sys.exit()
function()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM