I'm making a Myth/Truth game. The user has to guess if the printed statement is Myth or Truth. I'm trying to put all the questions into a list and then print them randomly.
After each statement is printed, the user will type in something and the program will check if their input is valid or not ("M" or "T").
But if the input is invalid, a prompt will be shown and the user will have to answer that question again.
Then, if the input is not invalid and they got it right, 10 scores will be added to their grades and we move on to the next question.
At the end of the game, the program will show the result.
def ask():
userGrade = 0
questionsList = ['a','b','c','d','e','f','g','h','i','j','k']
#print first question randomly
#user input
#check if the input is valid
#check if the input is "M" or "T"
#add score to userGrade
#print the next question randomly
#....
#print the last question
#...
print('You got', userGrade, 'scores!')
ask()
The problem is that I don't know how to code it. Can anyone help me?
I tried to search for a tutorial on Youtube but it is just so hard to follow :(
CodePudding user response:
Something like this might work:
import random
def ask():
user_score = 0
# I would suggest making the question list a dictionary containing
# the questions and the answers:
question_list = {'q1':'M', 'q2':'T', 'q3':'T'} #etc.
# Get a shuffled list of the questions so that we can iterate through them:
question_list_shuffled = random.sample(question_list.keys(), len(question_list))
for question in question_list_shuffled: # loop through the questions and their answers.
print(question)
inputted_answer = input().strip().lower()
# strip makes sure the program ignores
# leading and trailing whitespace, and lower makes
# sure the program ignores lower and upper.
while inputted_answer not in ['m', 't']:
# Keeping asking the user until they input 'M' or 'T'
inputted_answer = input("Sorry, not a valid answer. Try again:\n").strip().lower()
if inputted_answer == question_list[question].lower():
# Compares the input to the key (answer) of the question in the dictionary.
user_score = 10
print(f'You got {user_score} scores!')
ask()
See also:
- Datastructures in Python: https://docs.python.org/3/tutorial/datastructures.html
- Random in Python: https://docs.python.org/3/library/random.html
- For Loops in Python: https://wiki.python.org/moin/ForLoop
- How to use random.sample: https://pynative.com/python-random-sample/
CodePudding user response:
I tried using itertools
from itertools import chain, repeat
def ask():
userGrade = 0
questionsList = ['a','b']
answers=[]
valid_out=['T','M']
for i in range(len(questionsList)):
prompts = chain([questionsList[i] ": "], repeat("Try again!\n" questionsList[i] ": "))
replies = map(input, prompts)
valid_response = next(filter(valid_out.__contains__, replies))
if valid_response in valid_out:
userGrade =10
print('You got', userGrade, 'scores!')
ask()