对于没有停止的循环

时间:2018-04-03 13:44:51

标签: python-3.x while-loop

所以,我不知道如何解决这个问题,但是我得到了一个无限循环,似乎无法弄清楚如何做到这一点。

# user guesses the number. Returns Yes or try again.
import random

# Instruct user to guess a number.
number = int(input("Guess a number, see if you're right."))

rn = random.randint(1,10)

while number != rn:  # User number is not equal to rn then continue.
    print("Sorry. Try again.")

    if number < rn:  # tells player that the number is too low.
        print("Higher")

    if number > rn:  # Tells the player that the number is too high.
        print("Lower")

    if number == rn:  # User number equals random number break
        break

    print("Well, you got it. Congrats!")

2 个答案:

答案 0 :(得分:0)

如果他们没有做对,你需要得到用户的新猜测:

# user guesses the number. Returns Yes or try again.
import random

# Instruct user to guess a number.
number = int(input("Guess a number, see if you're right."))

rn = random.randint(1,10)

while number != rn:  # User number is not equal to rn then continue.
    print("Sorry. Try again.")

    if number < rn:  # tells player that the number is too low.
        print("Higher")

    if number > rn:  # Tells the player that the number is too high.
        print("Lower")

    # Ask for a new number
    number = int(input("Guess another number."))

# Move this to outside the loop
print("Well, you got it. Congrats!")

答案 1 :(得分:0)

只要不等于 ,你就需要调用输入,在中断之前也要成功,否则你可能无法达到它。

# user guesses the number. Returns Yes or try again.
import random

# Instruct user to guess a number.
number = int(input("Guess a number, see if you're right: "))

rn = random.randint(1,10)

while number != rn:  # User number is not equal to rn then continue.
    print("Sorry. Try again.")

    if number < rn:  # tells player that the number is too low.
        print("Higher")
        number = int(input("Guess again, see if you're right: "))

    if number > rn:  # Tells the player that the number is too high.
        print("Lower")
        number = int(input("Guess again, see if you're right: "))

    if number == rn:  # User number equals random number break
        print("Well, you got it. Congrats!")
        break