我试图创建一个猜谜游戏,用户在字典中选择一个键并猜测它的值。 我很难尝试为选择编码变量,以便猜测值。
这是我到目前为止所做的:
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
语句似乎没有被程序读取。我该如何解决这个问题?
答案 0 :(得分:1)
您的语义不正确。在if
语句之前,插入
print (guess, answer)
这是基本调试。你会看到问题:answer
是所有大写的列表;原始用户输入无法等于整个列表。您只需要与该州的资本进行比较。
你必须对choice
进行类似的检查,因为你在那里犯了同样的错误。
答案 1 :(得分:0)
提供的代码存在一些问题。这是一个带内联注释的工作版本,用于解释正在发生的事情。 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()