Python“高/低”游戏没有按预期工作

2024-05-07 13:35:38 发布

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

游戏的工作原理是这样的:给用户一个google搜索词,比如:“limousine”和该词的每月搜索量,然后它会显示另一个词。为了得到一个点,用户必须猜测后一个词的搜索次数是高是低。在运行python脚本时,我遇到了令人困惑的行为。即使答案是正确的,游戏也会停止。在

import pandas
from random import choice, randint

columnNames = ['search','number_of_searches']
search_registry = pandas.read_csv('data.csv', names = columnNames)

keywords = search_registry.search.tolist()
values = search_registry.number_of_searches.tolist()

points = 0
stop = 0

while stop != 1:

    randomIndex_1 = randint(1,len(keywords)-1)
    print ( keywords[randomIndex_1] + " has {} monthly global searches ".format(values[randomIndex_1]) )

    randomIndex_2 = choice([i for i in range(1,len(keywords)) if i != randomIndex_1])
    print ( "How many does {} have? Higher or Lower?".format(keywords[randomIndex_2]))

    ans = input()

    if ans == 'higher':
        if values[randomIndex_1] < values[randomIndex_2]:
            points+=1
        elif values[randomIndex_1] > values[randomIndex_2]:
            print("GAME OVER. You got {} points".format(points))
            stop=1

    if ans == 'lower':
        if values[randomIndex_1] > values[randomIndex_2]:
            points+=1
        elif values[randomIndex_1] < values[randomIndex_2]:
            print("GAME OVER. You got {} points".format(points))
            stop=1

这是CSV数据:

^{pr2}$

Tags: 用户importformat游戏searchifpointsregistry
1条回答
网友
1楼 · 发布于 2024-05-07 13:35:38

问题解决了。values[]列表存储str而不是int类型的数据。比较时只需写int(values[])就可以解决这个问题。现在比较是在int类型之间进行的,而不是在字符串之间。在

相关问题 更多 >