无限循环帮助需要

时间:2017-02-08 17:06:28

标签: python loops while-loop

print("Hi. Welcome on Guess The Number!!")
from random import randint
randomnumber = randint(1,100)
print("Guess the number!!")
usernumber = int(input("Which number am I thinking about?"))
try = 0
while usernumber != randomnumber:
    if usernumber < randomnumber:
        print("Lower...")
        print()
        try += 1
        usernumber = int(input("Which number am I thinking about"))
    elif usernumber < randomnumber:
        print("Higher")
        print()
        try += 1
        usernumber = int(input("which numberam I thinking about?"))
print("Finally!!!")
if try <= 10:
    print("Well done!!")
elif try > 10:
    print("U lost")
print()
print("The End!")

当我输入一个高于随机数的输入数时,这会导致无限循环。

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

您的elif语句与if语句相同。两者都检查

usernumber < randomnumber:

将其更改为

elif usernumber > randomnumber:

同样使用try作为变量名称会引发错误。请改用其他名称。我将其更改为tryy

print("Hi. Welcome on Guess The Number!!")
from random import randint
randomnumber = randint(1,100)
print("Guess the number!!")
usernumber = int(input("Which number am I thinking about?"))
tryy = 0
while usernumber != randomnumber:
    if usernumber < randomnumber:
        print("Lower...")
        print()
        tryy += 1
        usernumber = int(input("Which number am I thinking about"))
    elif usernumber > randomnumber:
        print("Higher")
        print()
        tryy += 1
        usernumber = int(input("which numberam I thinking about?"))
print("Finally!!!")
if tryy <= 10:
    print("Well done!!")
elif tryy > 10:
    print("U lost")
print()
print("The End!")

答案 1 :(得分:0)

在您的代码中,ifelse仅适用于usernumber < randomnumber。这就是为什么你最终会得到一个无限循环 - 因为你没有编码if-else分支,这将处理这种情况。