gpt4 book ai didi

Python 猜我的数字(逆数猜)UnboundLocalError

转载 作者:行者123 更新时间:2023-12-01 05:42:15 25 4
gpt4 key购买 nike

我正在尝试编写一个简单的数字猜测程序。在这个特定的程序中,Python 正在猜测用户正在思考的数字,而不是相反。

我的代码返回 UnboundLoalError。

而且,这一切似乎都太长太麻烦了。我怎样才能缩短它?

谢谢。

# Guesses a number

from random import randint
number = ""

def numberGuesser():
while True:
print "Think of a number between 1 and 50"
raw_input("Hit a key when ready")
number = randint(1,50)
answer = raw_input("Is your number: %d?. y/n> " % number)
if answer == 'y':
print "Great!"
raw_input("Hit a key to exit.")
elif answer == 'n':
greater_or_smaller()
else:
print "Please type y or n"



def greater_or_smaller():
while True:
greater_or_smaller = raw_input("Is\
your number greater or smaller than %d? g/s> " % number)
if greater_or_smaller == 'g':
number = randint(number, 50)
answer = raw_input("Is your number %d? y/n> " % number)
if answer == 'y':
print "Hooray!"
elif answer == 'n':
greater_or_smaller()

elif greater_or_smaller == 's':
number = randint(1, number)
answer = raw_input("Is your number %d? y/n> " % number)
if answer == 'y':
print "Hooray!"
elif answer == 'n':
greater_or_smaller()


numberGuesser()

最佳答案

这个:

        if greater_or_smaller == 'g':
number = randint(number, 50)
answer = raw_input("Is your number %d? y/n> " % number)
if answer == 'y':
print "Hooray!"
elif answer == 'n':
greater_or_smaller()

elif greater_or_smaller == 's':
number = randint(1, number)
answer = raw_input("Is your number %d? y/n> " % number)
if answer == 'y':
print "Hooray!"
elif answer == 'n':
greater_or_smaller()

可能是:

        if greater_or_smaller in ['g','s']:
number = randint(number, 50) if greater_or_smaller == 'g' else randint(1, number)
answer = raw_input("Is your number %d? y/n> " % number)
if answer == 'y':
print "Hooray!"
elif answer == 'n':
greater_or_smaller()

此外,您可能应该编写一个小函数来处理与用户的交互,以确保答案包含在预期答案列表中。

类似于:

def get_input(prompt_text, valid_options):
x = raw_input(prompt_text)
while x not in valid_options:
print x, "is not a valid value. Expected are :", valid_options
return x

关于Python 猜我的数字(逆数猜)UnboundLocalError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17232651/

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