Python 字典猜测游戏中选择变量的编码困难
我正在尝试创建一个猜测游戏,用户在字典中选择一个键并猜测它的值。 为了猜测值,我很难对选择的变量进行编码 以下是我到目前为止的情况:Python 字典猜测游戏中选择变量的编码困难,python,dictionary,Python,Dictionary,我正在尝试创建一个猜测游戏,用户在字典中选择一个键并猜测它的值。 为了猜测值,我很难对选择的变量进行编码 以下是我到目前为止的情况: def main(): capitals = {'AL' : 'Montgomery', 'AK' : 'Juneau', 'AZ' : 'Phoenix', 'AR' : 'Little Rock', 'CA' : 'Sacramento', 'CO' : 'Denver', 'CT' :
def main():
capitals = {'AL' : 'Montgomery', 'AK' : 'Juneau', 'AZ' : 'Phoenix',
'AR' : 'Little Rock', 'CA' : 'Sacramento', 'CO' : 'Denver',
'CT' : 'Hartford', 'FL' : 'Tallahassee', 'GA' : 'Atlanta',
'HI' : 'Honolulu', 'ID' : 'Boise', 'IL' : 'Springfield',
'IN' : 'Indianapolis', 'IA' : 'Des Moines', 'KS' : 'Topeka'}
print("Choose a state from the list", capitals.keys())
choice = input('Which state would you like to guess? : ')
choice == capitals.keys()
guess = input('Guess the capital of the state chosen : ')
answer = capitals.values()
if guess == answer:
print("Yay! You're CORRECT!")
else:
print("Sorry, You're INCORRECT!")
main()
程序似乎没有读取我的
if
语句。如何修复此问题?您的语义不正确。在if
语句之前插入
print (guess, answer)
这是基本的调试。您将看到问题:答案
是所有大写字母的列表;原始用户输入不可能等于整个列表。你只需要对比一个州的首都
您必须对
选项进行类似的检查,因为您在那里犯了相同的错误。所提供的代码有一些错误。下面是一个带有内联注释的工作版本,用于解释发生了什么。While循环允许您在继续之前检查输入数据
def main():
capitals = {'AL': 'Montgomery', 'AK': 'Juneau', 'AZ': 'Phoenix',
'AR': 'Little Rock', 'CA': 'Sacramento', 'CO': 'Denver',
'CT': 'Hartford', 'FL': 'Tallahassee', 'GA': 'Atlanta',
'HI': 'Honolulu', 'ID': 'Boise', 'IL': 'Springfield',
'IN': 'Indianapolis', 'IA': 'Des Moines', 'KS': 'Topeka'}
# initialize variables used in while loops
choice = ''
guess = ''
print("Choose a state from the list: {0}".format(' '.join(capitals.keys())))
# as long as choice is not in the list of capitals, keep asking
while choice not in capitals.keys():
choice = input('Which state would you like to guess? : ')
# get the correct answer for the chosen state
answer = capitals[choice]
# as long as the guess doesn't contain any non-whitespace characters, keep asking
while guess.strip() == '':
guess = input('Guess the capital of the state chosen : ')
# if the cleaned up, case-insensitive guess matches the answer, you win
if guess.strip().lower() == answer.lower():
print("Yay! You're CORRECT!")
# otherwise, you lose
else:
print("Sorry, You're INCORRECT!")
main()
在你的“如果猜测…”语句之前,放一些打印语句,例如打印(选择)、打印(猜测)和打印(回答)。我认为你的错误对你来说是显而易见的。另一种选择是开始使用具有步骤调试的IDE,例如PyCharm,这样您就可以看到变量一步一步地更改。你会想让自己养成观察变量的习惯,很快你就能在没有任何帮助的情况下回答这些问题:)我觉得说这句话像个暴躁的人,但这感觉像是一个家庭作业。