我该如何修改我的代码来打印出多少答案是对的还是错的?

2024-10-05 17:56:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要这个程序打印出你猜对错的次数。我有一本关于城市和国家的字典,例如“英国”:“伦敦”。代码如下:

def choices (Correct):
    list=[Correct]
    f=0
    cities=ccdict.values()
    while f + 1<5:
        f=f+1
        list.append(cities[random.randint(0, len(cities))])
    list.sort()
    return list


countries = ccdict.keys()
randcountry = countries[random.randint(0, len(countries))]
print "What is the capital of " + randcountry + "?"
print "If you want to stop this game, type 'exit'"
randlist = choices(ccdict[randcountry])

for i in range(0,5):
        print str(i+1) + " - " + randlist[i]

input=raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")

if input == "exit":                               
    print "Now exiting game!" + sys.exit()       

elif  randlist[int(input)-1] == ccdict[randcountry]:
    print "Correct"

else:
    print "WRONG! The capital of " + randcountry + " is " + ccdict[randcountry]

Tags: oftheinputisexitcountrieslistchoices
1条回答
网友
1楼 · 发布于 2024-10-05 17:56:22

int()移动到if测试后的

input = raw_input("Give me the number of the city that you think is the capital of " + randcountry + " ")

if input == "exit":
    print "Now exiting game!"
    sys.exit()

elif  randlist[int(input) - 1] == ccdict[randcountry]:
    print "Correct"

注意上面的版本如何在最后一分钟将input转换为整数。你知道吗

相关问题 更多 >