在用户输入特定的输入后,如何循环运行并结束程序,

时间:2018-08-20 09:26:17

标签: python python-3.x

我想知道您好,如果您能为我学校的python代码提供帮助,当用户输入的答案不符合结束条件时,我基本上不理解如何结束代码,并且不知道当他/她写诸如按Enter回车之类的内容时如何发出重新输入消息

operation = int(input("how long has your company been operating for?: "))
if operation > 5:
    print("Wow your company has gone on for quite some time now, huh?")

else:
    print("Sorry your company does not fit into our criteria")

例如,在这里,如果用户输入4,则程序会显示“对不起,您的公司不符合要求”,但是请不要结束它突出显示的代码,直到下一个程序,并且如果用户按Enter或键入字母当我只想重复问题并说“请输入适当的答案”时,它会带给我回溯错误。

Employees = int(input("How many employees are currently working in your company?"))
if Employees > 1000:
    print("Great to see your company is growing")
else:
    print("Sorry you must have at least 1000 employees if you want to be our supplier")

这也与最后执行的程序有同样的问题,例如它不应该返回数字(1000),并且不接受随机输入,而只是说回溯错误而不是重新键入消息并说“请提供适当的输入” “

2 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

answered = False

while not answered:
   inp = input("how long has your company been operating for?: ")
   try:
       operation = int(inp)
   catch ValueError:
       print("Wrong input, try again")
       continue

   if operation > 5:
       print("Wow your company has gone on for quite some time now, huh?")
       answered = True

   else:
       print("Sorry your company does not fit into our criteria")
       sys.exit()

答案 1 :(得分:1)

import sys

while True:
    operation = input("how long has your company been operating for?: ")
    if operation.isdigit():
        operation = int(operation)
        if operation > 5:
            print("Wow your company has gone on for quite some time now, huh?")
            break
        else:
            print("Sorry your company does not fit into our criteria")
            exit()
    else:
        print("please enter a number")