猜游戏Python无限循环

时间:2019-09-10 03:18:55

标签: python random

我试图自学基本的python脚本并创建数字猜测游戏,但是我的while循环遇到了无限循环。该程序将无限次打印初始条目中的第一个打印语句。

#!/usr/bin/python
import random

print("Here is a guessing game!")
print("Try to guess the number. It is a value from 1-100")

answer = random.randint(1,100)
guess = int(input('Enter your guess: '))
counter = 0

while (guess != answer):
   counter += 1
   if guess < answer:
       print('Your guess is too low!')
   elif guess > answer:
       print('Your guess is too high!')
   else:
       print('Correct!')
       print('It took you' + count + ' guesses.')

2 个答案:

答案 0 :(得分:2)

#Try asking the guess again in each loop until the correct answer and print the counter outside the loop

#!/usr/bin/python
import random

print("Here is a guessing game!")
print("Try to guess the number. It is a value from 1-100")

answer = random.randint(1,100)
guess = int(input('Enter your guess: '))
counter = 0

while (guess != answer):
   counter += 1
   if guess < answer:
       print('Your guess is too low!')
   elif guess > answer:
       print('Your guess is too high!')
   guess = int(input('Try again, your new guess: '))
print('Correct!')
print('It took you' + counter + ' guesses.')

答案 1 :(得分:0)

用户应该在循环内输入一个值,所以我认为您需要将代码更改为此:

import random

print("Here is a guessing game!")
print("Try to guess the number. It is a value from 1-100")

answer = random.randint(1,100)
guess = int(input('Enter your guess: '))
counter = 0

while (guess != answer):
   counter += 1
   if guess < answer:
       print('Your guess is too low!')
       guess = int(input('Enter your guess: '))
   elif guess > answer:
       print('Your guess is too high!')
       guess = int(input('Enter your guess: '))
   else:
       print('Correct!')
       print('It took you' + str(counter) + ' guesses.')

这是因为用户一次输入了猜测值,所以当它进入循环时,它将永远循环并打印(太低或太高)