简体   繁体   中英

Why does my while loop repeat true when the user's input can be false?

I have 2 lists containing countries and their capitals, and I assigned them to each other using the zip function. My program randomizes a country from the list and I ask the user to type in the capital in whichever country is shown.

import random
x = random.randrange(5)

country_names = ['Germany', 'Italy', 'Netherlands', 'France', 'Albania', 'Canada'] 
capital_list = ['Berlin', 'Rome', 'Amsterdam', 'Paris', 'Tirana', 'Ottawa'] 

dictionary_list = [ {"COUNTRY": country, "CAPITAL": capital,} for country, capital in 
zip(country_names, capital_list, )]

item = random.choice(list(country_names))
print(item)

score = 0
while True:

    user_input = input('Name ' + item + "'s" + ' Capital:')
    user_input = str(user_input)

    answer = False
    for i in capital_list:
        if user_input == i:
            answer = True

    if answer:
        print("Correct")
        score = score + 1
    else:
        print("Incorrect")

Here is an example output:

Albania
Name Albania's Capital: Tirana
Correct
Name Albania's Capital:

It is true that Albania's capital is Tirana, but the problem is that my program will always say 'correct' even if I give it the wrong capital.

How can my while loop actually check my dictionary_list and give a correct or incorrect answer? And how can I repeat the process without my program saying 'Name Albania's Capital' again?

This does what you ask:

import random

country_names = ['Germany', 'Italy', 'Netherlands', 'France', 'Albania', 'Canada'] 
capital_list = ['Berlin', 'Rome', 'Amsterdam', 'Paris', 'Tirana', 'Ottawa'] 

dictionary = dict(zip(country_names, capital_list))

score = 0

while True:
    item = random.choice(list(country_names))
    print(item)

    user_input = input('Name ' + item + "'s capital:")

    if dictionary[item] == user_input:
        print("Correct")
        score = score + 1
    else:
        print("Incorrect")

Multiple problems here. Most importantly, you have

    answer = False
    for i in capital_list:
        if user_input == i:
            answer = True

This code just looks at each capital in the list of capitals and returns True if what the user typed is in that list. You make no effort to see if it is the right country or not.

A better data structure might be a dictionary, in which the keys are the countries, and the value is the capital:

dictionary_list = [ country: capital for country, capital in zip(...)]

then you can write

item = random.choice(list(country_names))
expected_answer = dictionary_list[item]

and the only correct answer is expected_answer

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