gpt4 book ai didi

python - 除了 while 循环 Python 2.7 之外的尝试

转载 作者:行者123 更新时间:2023-11-28 22:38:32 26 4
gpt4 key购买 nike

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

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

最佳答案

您所做的就是在引发 ValueError 时打印额外的一行。如果您希望循环从头开始,请在 except block 中添加 continue。如果您想将无效输入计为尝试次数,请将增加 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。在一个循环中有多个 continue 会让人难以理解。

关于python - 除了 while 循环 Python 2.7 之外的尝试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35537528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com