Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

Python: Random trivia trivia question/answer, in parameters

I am new to learning python and want to run bit of a trivia. Basically, I want to ask a random question from a list and then using an 'in' operator, figure if the user input of Y/N is correct or not. I'm stuck with determining how to check whether it is correct or not. Maybe my (incorrect) code can explain better.

import random

Players = ['Patrice Evra', 'Rio Ferdinand', 'Sergio Ramos', 'Gerard Pique']
Clubs = ['Manchester United', 'Nice', 'Monaco', 'Marseille', 'West Ham United', 'Sevilla', 'Real Madrid', 'Barcelona']
Ramos = ['Sevilla', 'Real Madrid']
Evra = ['Manchester United', 'Nice', 'Monaco', 'Marseille', 'West Ham United']
Ferdinand = ['Leeds United', 'Manchester United']
Pique = ['Barcelona', 'Manchester United']
print('Did ' + random.choice(Players) + ' play for ' + random.choice(Clubs) + ' ? Y/N')
answer = input()

This is where I'm stuck and not even sure if this is the right way to go about this. Thanks for the help.

question from:https://stackoverflow.com/questions/65829496/python-random-trivia-trivia-question-answer-in-parameters

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Most importantly you have to save your random choice so you can verify it later. So you should asign two variables before:

player = random.choice(Players)
club = random.choice(Clubs)
print('Did ' + player + ' play for ' + club + ' ? Y/N')

Then you can verify that yourself via if statements. But a faster (more complex) way would be:

did_play = club in [Evra, Ferdinand, Ramos, Pique][Players.index(player)]

It would be better to store the variables Evra, Ferdinand, Ramos and Pique differently, but for now that should to the trick.

A better way to store those variables would be in a dictionary like such:

player_clubs = {
"Patrice Evra": ['Manchester United', 'Nice', 'Monaco', 'Marseille', 'West Ham United'],
"Rio Ferdinand": ['Leeds United', 'Manchester United'],
"Sergio Ramos": ['Sevilla', 'Real Madrid'],
"Gerard Pique": ['Barcelona', 'Manchester United']
}

That way you can easier check if they played in a certain club like:

did_play = club in player_clubs[player]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...