尝试除了while循环Python 2.7

时间:2016-02-21 14:44:42

标签: python while-loop

以下是我猜测随机数的代码。我必须检查输入以确保它是一个整数并且在1-20范围内。一切正常。如果它不是一个整数或超出范围,它会输出正确的响应但是它会继续通过while循环。我认为尝试除了会在继续之前将其发回去。我在这里做错了什么?我无法弄清楚这个问题。谢谢你的帮助!

import random

tries = 0

name=(raw_input('Hello! What is your name? '))

number = random.randint(1, 20)
print('Hello, ' + name + ', I am thinking of a number between 1 and 20.')


while tries < 6:

    guess = (raw_input('Take a guess.' ))

    try:
        guess = int(guess)
    except ValueError:
        print 'You did not enter a valid number, try again.'    

    tries = tries + 1

    if guess<1 or guess>20:
        print 'Your guess is not between 1 and 20'

    if guess < number:
        print 'Your guess is too low.' 
    if guess > number:
        print 'Your guess is too high.'

    if guess == number:
        break

if guess == number:
    print 'Good job, ',name,'! You guessed my number in ',tries,' guesses!'

if guess != number:
     print 'Sorry, The number I was thinking of was ',number

3 个答案:

答案 0 :(得分:2)

您所做的只是提出ValueError时要打印一条额外的行。如果您希望循环从头开始,请在continue块中添加except。如果要将无效输入计为尝试次数,请将递增tries的行移动到循环的开头。

tries += 1 # increment tries here if invalid inputs should count as a try, too
           # increment tries after the except block if only valid inputs should count as a try
# get input here
try:
    guess = int(guess)
except ValueError:
    # inform user that the input was invalid here
    continue # don't execute the rest of the loop, start with the next loop

你可以在另一个continue放置,检查数字是太高还是太低:

if guess<1 or guess>20:
    print 'Your guess is not between 1 and 20'
    continue

或使用if / elif结构:

if guess<1 or guess>20:
    print 'Your guess is not between 1 and 20'
elif guess < number:
    print 'Your guess is too low.' 
elif guess > number:
    print 'Your guess is too high.'
else: # guess == number
    break

我推荐if / elif。循环中有多个继续可能会让人难以理解。

答案 1 :(得分:1)

你告诉它打印一些东西,但Python不知道你不希望它在那次迭代中做其他事情。有时您可能希望它仅在 错误时继续运行。要说“跳过此循环”,请使用continue

try:
    guess = int(guess)
except ValueError:
    print 'You did not enter a valid number, try again.'
    continue

答案 2 :(得分:1)

您需要在两次测试后继续,并且只有在成功通过测试后才增加尝试。

import random
tries = 0
name=(raw_input('Hello! What is your name? '))
number = random.randint(1, 20)
print('Hello, ' + name + ', I am thinking of a number between 1 and 20.')

while tries < 6:

    guess = (raw_input('Take a guess.' ))

    try:
        guess = int(guess)
    except ValueError:
        print 'You did not enter a valid number, try again.'
        continue

    if guess<1 or guess>20:
        print 'Your guess is not between 1 and 20'
        continue

    tries = tries + 1

    if guess < number:
        print 'Your guess is too low.'
    if guess > number:
        print 'Your guess is too high.'

    if guess == number:
        break

if guess == number:
    print 'Good job, ',name,'! You guessed my number in ',tries,' guesses!'

if guess != number:
     print 'Sorry, The number I was thinking of was ',number