1

我是 python 新手,目前正在上课,我的程序看起来像:

if choice=="1":
    def addition():
        print("You are doing addition. X+Y=Z")
        X = int(input("Enter X:"))
        Y = int(input("Enter Y:"))
        sum = X + Y
        print ("your total is:")
        print (sum)


    Well = "y"
    while Well == "y":
        again = input("Would you like to go again? (y/n)")
        if again == "y":
            addition()
        if again == "n":
            project()
        else:
            print("sorry re-enter choice")

在显示实际添加部分之前,它会询问我是否要再去一次。我该如何解决?谢谢你的帮助 :)

4

4 回答 4

2

有很多方法,但你可以addition()像这样把你的函数放在顶部:

Well = "y"
while Well == "y":
    addition()
    again = input("Would you like to go again? (y/n)")
    if again == "n":
        project()
    if again not in ("n", "y"):
        print("sorry re-enter choice")
于 2013-04-15T03:07:39.193 回答
1

false只需添加一个在第一次运行时从变为的标志true,这样您就不会在第一次运行时看到“再次”语句。

于 2013-04-15T02:59:45.460 回答
1

几点:

  • 您不应将sum其用作变量名。它是一个内置的 Python。
  • 查看您用于循环检查的变量,您会很快注意到它。
于 2013-04-15T02:59:58.463 回答
1

我认为在你做完你的事情之后,问你是否想在循环结束时再去一次会更有意义:

while loop_condition:
    #do_your_stuff:
    bla bla bla

    #see if you should go again
    bla bla = raw_input("Do you want to go again")

事实上,99% 的时间你的 while 循环都会遵循这种模式(检查条件、运行循环体、更新条件),如果你以不同的顺序做事(比如在运行主体之前更新条件)它通常是表明你可能做错了什么。

于 2013-04-15T03:05:33.523 回答