我正在编写半径猜测游戏并且偶然发现了循环问题。 这可能看起来像一个愚蠢的问题,但突破正确的位置?或者它应该是别的吗?
import random
import math
number = random.randint(1, 20)
area = math.pi * number**2
guessesTaken = 0
print '%.0f is the area' % (area)
print('Take a guess.')
guess = input()
guess = int(guess)
guessesTaken = guessesTaken + 1
while guessesTaken < 6:
if guess < number:
print('Your guess is too low.')
if(guess > number):
print('Your guess is too high.')
if guess == number:
guessesTaken = str(guessesTaken)
print('Good job! You guessed my number in ' + guessesTaken + ' guesses!')
break
if guess != number:
number = str(number)
print('Nope. The number I was thinking of was ' + number)
答案 0 :(得分:1)
您应该将最后两个if
放在while
循环之外。此外,在while
内部,如果用户猜错了,您应该重新询问输入,否则guesses
永远不会改变,您只需要永远循环。
如果要放置最大迭代次数,则应在循环内增加guessesTaken
。
while guessesTaken < 6:
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
else:
break
guess = int(input('Try again: '))
guessesTaken += 1
if guess == number:
print('Good job! You guessed my number in {} guesses!'.format(guessesTaken))
else:
print('Nope. The number I was thinking of was {}'.format(number))
无论如何,如果你知道你最多会有6
次迭代,那么你应该只使用for
循环:
for _ in range(6): # loop 6 times
if guess < number:
print('Your guess is too low.')
elif guess > number:
print('Your guess is too high.')
else:
break
guess = int(input('Try again: '))