如果用户输入“再次运行?”,则重新启动Python程序'是'

时间:2016-11-15 17:54:23

标签: python

while True:
# main program

    number = (" ")
total = 0

num1 = int(input("enter a number"))
total = total + num1
num2 = int(input("enter a number"))
total = total + num2
num3 = int(input("enter a number"))
total = total + num3

if total > 100:
    print("That's a big number!")
else:
    print("That's a small number.")
print(total)

while True:
        answer = raw_input("Run again? (y/n): ")
        if answer in y, n:
            break
        print("Invalid input.")
    if answer == 'y':
        continue
    else:
        print 'Goodbye'
        break

基本上我希望程序在用户输入“y”作为“再次运行”的响应时重新启动?任何帮助将非常感激。谢谢。

3 个答案:

答案 0 :(得分:1)

正如@burhan建议的那样,只需将主程序包装在一个函数中。顺便说一下,你的代码有一些错误,可以使用一些帮助:

  • if answer in y, n: - 你的意思是if answer not in ('y', 'n')
  • number = (" ")是一条不相干的行
  • while True在您的主程序中毫无意义
  • print("Invalid input.")低于break,因此永远不会被执行

所以你会有类似的东西:

def main():
    total = 0

    num1 = int(input("enter a number"))
    total = total + num1
    num2 = int(input("enter a number"))
    total = total + num2
    num3 = int(input("enter a number"))
    total = total + num3

    if total > 100:
        print("That's a big number!")
    else:
        print("That's a small number.")
    print(total)

while True:
    answer = raw_input("Run again? (y/n): ")
    if answer not in ('y', 'n'):
        print("Invalid input.")
        break
    if answer == 'y':
        main()
    else:
        print("Goodbye")
        break

答案 1 :(得分:-1)

def main():
    total = 0
    num1 = int(input("enter a number"))
    total = total + num1
    num2 = int(input("enter a number"))
    total = total + num2
    num3 = int(input("enter a number"))
    total = total + num3

    if total > 100:
        print("That's a big number!")
    else:
        print("That's a small number.")
    print(total)

    answer = raw_input("Run again? (y/n): ")

    if answer not in ('y', 'n'):
        print("Invalid input.")
    if answer == 'y':
        main()
    else:
        print 'Goodbye'


if __name__ == '__main__':
    main()

当用户输入非数字输入等时,您应该添加一些检查以处理案例。

答案 2 :(得分:-2)

你的代码看起来真的搞砸了。尝试下次写一些更好(干净)的代码。

while True:
    total = 0

    num1 = int(input("enter a number"))
    num2 = int(input("enter a number"))
    num3 = int(input("enter a number"))
    total = num1 + num2 + num3

    if total > 100:
        print("That's a big number!")
    else:
        print("That's a small number.")
    print(total)

    con = int(input("Run again? 1/0: "))
    if con==0:
        break