简体   繁体   中英

Python “higher/lower” game not working as expected

The game works like this: the user is given a google search term like : "limousine" and the monthly searches the term has, then it is presented with another term. The user has to guess if the latter term has a higher or lower number of searches in order to receive a point. When running the python script I have encountered confusing behavior. Even though the answer is right the game stops.

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

This is the CSV data:

"search","number_of_searches"
"Rolex",2740000,
"April The Giraffe",1500000,
"Scarlet Johansson",3350000,
"Maldives",1220000,
"Fargo",823000,
"Profiteroles",201000,
"Road Runner",369000,
"Limousine",246000,
"Birthday Cake",2250000,
"The Secret",301000,
"Ralph Lauren",2240000,
"The Silence Of The Lambs",368000

Problem Solved. The values[] list stores data of type str not int . Simply writing int(values[]) when comparing will resolve the issue. Now the comparison is done between int types not between strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM