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!")
当我输入一个高于随机数的输入数时,这会导致无限循环。
我该如何解决这个问题?
答案 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)
在您的代码中,if
和else
仅适用于usernumber < randomnumber
。这就是为什么你最终会得到一个无限循环 - 因为你没有编码if-else
分支,这将处理这种情况。