简体   繁体   English

打破基本python的循环

[英]Breaking a loop for basic python

I have been working on this for a while now.我已经为此工作了一段时间。 I have been able to get parts of this to work, but never the whole thing.我已经能够让这部分工作,但从来没有完成。 The end goal is to loop the user back into another game if they so choose.最终目标是将用户循环回另一个游戏,如果他们愿意的话。 I think the issue is with my break statement, but I am not sure how to route around it.我认为问题出在我的 break 语句上,但我不确定如何绕过它。 I have included all my code so that any mistakes can be found.我已经包含了我所有的代码,以便可以发现任何错误。 Apologies if this has already been answered, I couldn't find a page with this kind of problem.抱歉,如果已经回答了这个问题,我找不到存在此类问题的页面。

def game():
    import random
    from random import randint
    n = randint(1, 10)
    print('Enter a seed vlaue: ')
    the_seed_value = input(' ')

    random.seed(the_seed_value)

    guessesTaken = 0

    print("what is your name?")
    myName = input("")

    guess = int(input("Enter an integer from 1 to 99: "))

    while n != "guess":


        if guess < n:
            print ("guess is low")
            guessesTaken = guessesTaken + 1
            guess = int(input("Enter an integer from 1 to 99: "))
        elif guess > n:
            print ("guess is high")
            guessesTaken = guessesTaken + 1
            guess = int(input("Enter an integer from 1 to 99: "))
        else:
            print ("Congradulations " + myName +  " you guessed it in " + str(guessesTaken) + " guesses!") 
            break 


    print('Want to play agian? y/n')
    answer = input(" ")
    if answer == "n":
        print ("Ok, See you next time!")

    elif answer == "y":
        print("Starting new game!")
        game()


def main():
    game()

if __name__ == "__main__":
    main()

For one, @kerwei notes correctly that your while line has an issue, and needs to be changed from while n != "guess": to while n != guess: .一方面,@kerwei 正确地指出您的while行有问题,需要从while n != "guess":更改为while n != guess:

For two, your while loop is satisfied when the player guesses correctly, bypassing the Congrats line.第二,当玩家猜对时,你的 while 循环就得到满足,绕过Congrats行。

Since the game is currently structured to stay in the loop until the player guesses correctly, a simple fix would be to remove the else: line from the loop and place the victory statement afterwards.由于游戏目前的结构是保持循环直到玩家猜对了,一个简单的解决方法是从循环中删除else:行并在之后放置胜利语句。 That is,那是,

def game()
    ...
    while n != guess:
        if guess < n:
            ...
        elif guess > n:
            ...
    print('Congrats!')
    print('play again?')
    ... 

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

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