【问题标题】:PYTHON: Unable to loop properlyPYTHON:无法正确循环
【发布时间】:2014-02-10 05:21:49
【问题描述】:

编辑:谢谢,问题已得到解答!

该程序运行正常,除了它不会循环以允许用户玩新游戏这一事实。即,在输入太多、太少或完美的更改量后,程序会询问“再试一次(y/n)?:”。但是我不知道为什么它不循环......而且当它循环时,它不需要包含关于解释游戏的大段。只是关于“输入加起来为“+str(number)+”美分的硬币,每行一个。”这一行。有什么建议吗?

#Setup

import random
playagain = "y"

#Main Loop

if (playagain == "y"):

    number = random.randint(1,99) #Generation of how many cents
    total = 0 #Running sum of guessed coins.

    print("The purpose of this exercise is to enter a number of coin values")
    print("that add up to a displayed target value. \n")
    print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
    print("Hit return after the last entered coin value.\n")
    print("Enter coins that add up to "+str(number)+" cents, one per line.\n")

    while (True):
        if (total == 0):
            word = "first"
        else:
            word = "next"

        guess = str(input("Enter "+str(word)+" number: ")) #Records coin value

        #Entry Validation
        if (guess == ""): #When user is done guessing.
            if (total < number):
                print("Sorry - you only entered "+str(total)+" cents.\n")
                break
            elif (total > number):
                print("Sorry -  total amount exceeds "+str(number)+" cents.\n")
                break
            else:
                print("Correct!")
                break
        elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25): 
            total = total + int(guess)        

        else:
            print("Invalid entry")
playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.

【问题讨论】:

  • 在此处仅粘贴代码的相关部分可能会得到更好的答案。
  • 如果您认为问题已回答,请接受!

标签: python loops nested-loops


【解决方案1】:

通过使用 break,您将完全退出 while 循环,并且永远不会检查 playagain 条件。如果您想查看用户是否想再次播放,请将“playagain”检查放在另一个 while 循环中。

#Setup

import random
playagain = "y"

#Main Loop

while (playagain == "y"):

    number = random.randint(1,99) #Generation of how many cents
    total = 0 #Running sum of guessed coins.

    print("The purpose of this exercise is to enter a number of coin values")
    print("that add up to a displayed target value. \n")
    print("Enter coins values as 1-penny, 5-nickel, 10-dime,and 25-quarter.")
    print("Hit return after the last entered coin value.\n")
    print("Enter coins that add up to "+str(number)+" cents, one per line.\n")

    while (True):
        if (total == 0):
            word = "first"
        else:
            word = "next"

        guess = str(input("Enter "+str(word)+" number: ")) #Records coin value

        #Entry Validation
        if (guess == ""): #When user is done guessing.
            if (total < number):
                print("Sorry - you only entered "+str(total)+" cents.\n")
                break
            elif (total > number):
                print("Sorry -  total amount exceeds "+str(number)+" cents.\n")
                break
            else:
                print("Correct!")
                break
        elif (int(guess) == 1) or (int(guess) == 5) or (int(guess) == 10) or (int(guess) == 25): 
            total = total + int(guess)        

        else:
            print("Invalid entry")
    playagain = str(input("Try again (y/n)?: ")) #BRETT: I can't seem to get this to loop properly.

【讨论】:

    【解决方案2】:

    您将playagain 设置为y/n,但如果playagain 等于“y”,则代码不会回到开头。尝试将if playagain == "y" 变成while playagain == "y"。这样,如果 playagain 仍然设置为“y”,它会经历第一次并继续回到开头。

    另外,缩进最后一行 (playagain = str(....)),使其成为 while playagain == "y" 循环的一部分。如果不是,那么代码将陷入无限循环,因为在 while 循环内不会更改 playagain。

    【讨论】:

    • 是的,就是这个。那个“break”不起作用,所以改成“while”修复了它。是的,之后,缩进需要调整
    【解决方案3】:

    将最后一行缩进到while True 行。并将if (playagain == "y"): 更改为

    while (playagain == "y"):
    

    【讨论】:

    • 谢谢,这有助于解决问题
    • 如果是这样的话,你可以接受答案。
    【解决方案4】:

    您的“主循环”不是循环,它只是一个 if 语句。此外,最好使用 raw_input,因为 input 会评估您的输入。尝试类似这样的方法:

    playagain = 'y'
    #Main loop
    while playagain == 'y':
        print "do gamelogic here..."
        playagain = raw_input("Try again (y/n)?: ")
    

    在您的游戏逻辑中,您可以使用布尔值来检查您是否需要打印游戏说明:

    show_explanation = True
    while playagain == 'y':
        if show_explanation:
            print "how to play is only shown once..."
            show_explanation = False
    
        print "Always do this part of the code"
        ...
    
        playagain = raw_input("Try again (y/n)?: ")
    

    【讨论】:

    • 我使用的是 Python 3,并且 AFAIK,raw_input() 不存在吗?公平地说,我猜“主循环”并不是一个真正的循环。但是为了工作,它已经被改为“while”。关于布尔逻辑的想法非常聪明。没想到!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2016-07-30
    相关资源
    最近更新 更多