I'm stuck trying to figure out how to match the correct answer with the correct question. Right now if the user's answer is equal to any of the answers, it returns correct. Please help.
easy_question = "The capitol of West Virginia is __1__"
medium_question = "The device amplifies a signal is an __2__"
hard_question = "A program takes in __3__ and produces output."
easy_answer = "Charleston"
medium_answer = "amplifier"
hard_answer = "input"
questions_and_answers = {easy_question: easy_answer,
medium_question: medium_answer,
hard_question: hard_answer}
#print(easy_answer in [easy_question, easy_answer])
#print(questions_and_answers[0][1])
print('This is a quiz')
ready = input("Are you ready? Type Yes.")
while ready != "Yes":
ready = input("Type Yes.")
user_input = input("Choose a difficulty: Easy, Medium, or Hard")
def choose_difficulty(user_input):
if user_input == "Easy":
return easy_question
elif user_input == "Medium":
return medium_question
elif user_input == "Hard":
return hard_question
else:
print("Incorrect")
user_input = input("Type Easy, Medium, or Hard")
print(choose_difficulty(user_input))
answer = input("What is your answer?")
def check_answer(answer):
if answer == easy_answer:
return "Correct"
elif answer == medium_answer:
return "Correct"
elif answer == hard_answer:
return "Correct"
print(check_answer(answer))
You will want to keep track of the question:
question = choose_difficulty(user_input)
print(question)
answer = input("What is your answer?")
def check_answer(question, answer):
if questions_and_answers[question] == answer:
return "Correct"
return "Incorrect"
print(check_answer(question, answer))
There's a lot more cool stuff you can do, but this is a minimal example that should solve your problem!
EDIT:
When you did
questions_and_answers = {easy_question: easy_answer,
medium_question: medium_answer,
hard_question: hard_answer}
you created a dictionary (or dict as it's known in Python). See examples. Basically, you can do lookups by the first term (the question) and it'll return the second term (the answer).
The way I would do it: create 2 variables, x and y. If the users chooses "Easy", it sets x to 1, "Medium" sets it to 2 and so on. Then you ask him for an answer. The answer to the easy question, if correct, sets y to 1, on the medium to 2 and so on. Then you have a check if x == y. If yes, then he has answered correctly to the question.
Related
I created this function and want to call the returned result but, I'm not sure how to get the variable back. If possible I'd also like a different message to pop up if the user types n. Could anyone help?
def give_entertainment():
random_form_of_entertainment = random.choice(form_of_entertainment)
good_user_input = "y"
while good_user_input == "y":
user_input = input(f"We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ")
if good_user_input != user_input:
random_form_of_entertainment = random.choice(form_of_entertainment)
continue
else:
print("Awesome! Glad we got that figured out. Your trip is all planned! ")
return random_form_of_entertainment
x = give_entertainment()
Should store the return of your function into x.
With:
print(x)
you should see what's stored in your x variable.
Call the method while assigning it to a variable.
some_var = your_method()
Now this some_var variable have the returning value.
I'd personally use a recursive function for this, I made it work with y/n/invalid_input cases. Also with this an invalid input won't update random_form_of_entertainment so the user has to say y or n for it to change. I hope this is what you're looking for!
def give_entertainment():
random_form_of_entertainment = random.choice(forms_of_entertainment)
good_user_input = "y"
bad_user_input = "n"
invalid_input = True
while invalid_input:
user_input = input(f'We have chosen {random_form_of_entertainment} for your entertainment! Sound good? y/n: ')
if user_input == good_user_input:
print("Awesome! Glad we got that figured out. Your trip is all planned for!")
return random_form_of_entertainment
elif user_input == bad_user_input:
print("Sorry to hear that, let me try again...")
return give_entertainment()
else:
print("I don't recognize that input, please try again.")
continue
chosen_result = give_entertainment()
print(f'You chose {chosen_result}!')
I am a programming beginner and I am trying to build a fill-in-the-blank quiz. I am almost finished but I am stuck on 2 problems I am not able to solve, whatever I do. I would really appreciate your help with this. Thank you for helping me with this!
If you try to run the code and play the game:
1) It prints the quiz according to the difficulty(easy-insane) and quiz you want to play(apple, bond and programming quiz) which is great but afterwards it prompts you to choose difficulty again (the player_level() function keeps going even though the player/user has already chosen the difficulty level. I don't really understand why it does it? The player_level() procedure seems perfectly okay and logical to me.
2) The errors:
a) local variable blanks_index referenced before assignment
b) global name list_of_answers is not defined.
I know that it is related to the initialize_game() function but I don't know how to change the code so it refers all the variables (blanks_index, answers_index, player_lives) correctly.
It could be solved by creating global variables(I guess) but that is not a good practice so I am trying to avoid it. Formerly, the whole function initialise_game() and play_game() were one function, but as there are over 25 lines of code in one function, it is not a good practice as it is long and messy and I know that I can separate it but I don't know how.
Here is the code:
"""3 diffferent quizzes : Apple quiz, James Bond quiz, Programming quiz"""
"""Quiz and answers about Apple"""
Apple_quiz = ("The most valuable company in terms of market cap in 2016 is, ___1___."
"It was founded in ___2___. Its flagship product is called ___3___."
"___1___ has many competitors, the biggest rival is ___4___,founded by"
" nobody but the richest man on the planet,___5___ ___6___.")
list_of_answers_Apple = ["Apple", "1976", "Iphone", "Microsoft", "Bill", "Gates"]
"""Quiz and answers about Bond"""
Bond_quiz = ("James Bond is agent ___1___. He serves his country,___2___ ___3___"
" against its enemies. His car of choice is usually ___4___ ___5___."
" His favorite drink is ___6___.")
list_of_answers_Bond = ["007", "United", "Kingdom", "Aston", "Martin", "Martini"]
"""Quiz and answers about programming basics"""
Programming_quiz = ("___1___ are created with the def keyword. ___1___ are also called ___2___"
" You specify the inputs a ___1___ take by adding ___3___ separated by commas"
" between the parentheses. ___3___ can be standard data types such as string, number"
" ,dictionary, tuple, and ___4___ or can be more complicated such as ___5___"
" and ___6___ functions.")
list_of_answers_Programming = ["Functions", "procedures", "arguments", "lists", "objects", "lambda"]
blank_space = ["___1___", "___2___", "___3___", "___4___", "___5___", "___6___]"]
#List of levels with corresponding lives/guesses that player can have
quiz_list = ["Apple", "Bond", "Programming"]
level_list = ["easy", "medium", "hard", "superhard", "insane"]
lives_easy = 5
lives_medium = 4
lives_hard = 3
lives_superhard = 2
lives_insane = 1
def choose_quiz():
""" Prompts player to pick a type of quiz and loads the quiz """
#Input = player_quiz (raw input from player)
#Output = loaded quiz, player chose
while True:
player_quiz = raw_input("Please, select a quiz you want to play: "
"(Apple, Bond or Programming): ")
if player_quiz == "Apple":
return Apple_quiz
elif player_quiz == "Bond":
return Bond_quiz
elif player_quiz == "Programming":
return Programming_quiz
else:
print "We don't have such quiz, pick again!"
def answers_for_quiz():
""" Loads appropiate answers to the quiz that player has chosen"""
#Input = player quiz (raw input from player)
#Output = loaded quiz answers from the quiz player chose
player_quiz_pick = choose_quiz()
if player_quiz_pick == Apple_quiz:
return list_of_answers_Apple
elif player_quiz_pick == Bond_quiz:
return list_of_answers_Bond
elif player_quiz_pick == Programming_quiz:
return list_of_answers_Programming
def player_level():
""" Loads a difficulty that player chooses """
#Input = player_level_input (raw input of player choosing a difficulty)
#Output = corresponding number of lives:
#Easy = 5 lives, Medium = 4 lives
#Hard = 3 lives, Superhard = 2 lives
#Insane = 1 life
while True:
player_level_input = raw_input("Please type in a difficulty level: "
"(easy, medium, hard, superhard, insane): ")
if player_level_input == "easy":
return lives_easy #Easy = 5 lives
elif player_level_input == "medium":
return lives_medium #Medium = 4 lives
elif player_level_input == "hard":
return lives_hard #Hard = 3 lives
elif player_level_input == "superhard":
return lives_superhard #Superhard = 2 lives
elif player_level_input == "insane":
return lives_insane #Insane = 1 life
else:
print "We do not have such difficulty! Pick again!"
def correct_answer(player_answer, list_of_answers, answers_index):
""" Checks, whether the the answer from player matches with the answer list. """
#Input: player_answer (raw input that player enters in order to fill in the blank)
#Output: "Right answer!" or "Wrong! Try again!" this output will be later used in the game
if player_answer == list_of_answers[answers_index]:
return "Right answer!"
return "Wrong! Try again!"
def initialize_game():
"""Functions that sets up a game so we can play it """
player_quiz_pick, player_level_pick, list_of_answers = choose_quiz(), player_level(), answers_for_quiz()
print player_quiz_pick
print "\nYou will get maximum " + str(player_level_pick) + " guesses for this game. Good luck.\n"
blanks_index, answers_index, player_lives = 0, 0, 0
#for elements in blank_space:
while blanks_index < len(blank_space):
player_answer = raw_input("Please type in your answer for " + blank_space[blanks_index] + ": ")
if correct_answer(player_answer,list_of_answers,answers_index) == "Right answer!":
print "Correct answer! Keep going!\n"
player_quiz_pick = player_quiz_pick.replace(blank_space[blanks_index],player_answer)
answers_index += 1
blanks_index += 1
print player_quiz_pick
if blanks_index == len(blank_space):
print "Congratulations! You nailed it! You are the winner!"
else:
player_level_pick -= 1
if player_level_pick == 0:
print "Game over! Maybe next time!"
break
else:
print "One life less, that sucks! Have another shot!"
print "You have " + str(player_level_pick) + " guesses left."
initialize_game()
Your main problem is that you keep calling the same functions over and over again and do not save the input into variables. Here are some tips about your code and questions:
You are not doing anything with your player_level() method call, so the player doesn't actually chooses a level in a way that affects the game. You should change the function call, so the returned value will be stored.
//the call to the method:
player_level_pick = player_level()
Afterwards, you keep calling the player_level() method, and not using the actual answer that the user supplied. Change all player_level() appearences to player_level_pick - the variable you use to save the answer (as I showed above). Same goes to all other unneeded function calls such as choose_level().
You should initialize number_of_guesses, player_lives, list_of_answers, and other vars to a matching value to player_level_pick as well, so it will hold the right value according to the level. Likewise, you should change this line:
# the line that checks if game is over
# change from:
if number_of_guesses == player_lives:
# to :
if number_of_guesses == 0:
In order to return multiple values, you have to use tuples. Using multiple return statements one after the other does not work anywhere.
so, instead of:
return list_of_answers
return number_of_guesses
return blanks_index
return answers_index
return player_lives
you should use tuples, and unpack them properly:
# the return statement:
return (list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives)
# and the unpacking in the calling function:
list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives = initialize_game()
this way, all of the returned values go into the wanted variables in the calling function. this way, you need to call the initialize_game() from play_game(). it will be the efficient way for you.
Just saying it again, as I said in the end of (4) - you should unit initialize_game() and play_game() into a single function (because a lot of data is the same needed data), or just call initialize_game() from play_game().
Better practice then using this recursivly: return choose_level(), you should use a while True: loop, and just brake when you get a proper answer.
print("what type of device do you have phone, tablet or laptop(put brackets at the end of your answer)?")
answer = input ("press enter and type in your answer. phone(), tablet() or console()")
def phone():
import webbrowser
print("Do you have an iphone or samsung?")
answer = input ('iphone/samsung:')
if answer == "iphone":
print("what type of iphone?")
answer = input ('5, 6 or 7:')
if answer == "samsung":
print("what type of samsung do you have?")
answer = input ('s5, s6 or s7:')
Indent block, be more careful!
def phone():
import webbrowser
print("Do you have an iphone or samsung?")
answer = input ('iphone/samsung:')
if answer == "iphone":
print("what type of iphone?")
answer = input ('5, 6 or 7:')
if answer == "samsung":
print("what type of samsung do you have?")
answer = input ('s5, s6 or s7:')
x = input("press enter and type in your answer. phone(), tablet() or console() ")
if x == 'phone()':
phone()
elif x == 'tablet()':
tablet()
elif x == 'console()':
console()
Essentially, what you have is this...
def foo():
print("stuff")
answer = input("type foo()")
And answer == "foo()" is True.
You never called foo(), though, you just typed it in as a string.
You need to run it.
exec(answer)
But, exec is really bad, so instead, you should instead use if and elif's to call the corresponding function.
if answer == 'foo()':
foo()
I am having an issue getting my code to print only my question. I am able to get it to print both the question and answer, but now further. I am sure there are more problems further down the rode, but this is where I am stuck at the moment.
#gives the blank spaces in the questions to the quiz
num_of_blank = ["blank1", "blank2", "blank3", "blank4"]
#Below are the levels of questions for the quiz
easy_question = """A blank1 is something that holds a blank2, and a blank3 is a list of characters in order.
You can also blank4 a string to a variable."""
medium_question = """An example of blank1 is an blank2 statement. If statements can run at most blank3 time.
Unlike the if statement, a blank4 loop can run any number of times."""
hard_question = """A blank1 is when you have a list within a list. Lists support blank2, this means we can change the value of a list
after it has been created. When you have two different ways to refer to the same object that is called blank3. In a blank4 loop, for
each element in the list, you will assign that element to the name and evaluate the block."""
#the answers to each quiz
easy_answers = ["variable", "value", "string", "assign"]
medium_answers = ["control flow", "if", "one", "while"]
hard_answers = ["nested", "mutation", "aliasing", "for"]
#determines the level of difficulty for the questions for the user
def question_level(difficulty):
difficulty = raw_input("Please select a level of difficulty for your questions: Easy, Medium, or Hard. ").lower()
question, answers = question_level()
if difficulty == "easy":
return (easy_questions, easy_answers)
elif difficulty == "medium":
return (medium_question, medium_answers)
elif difficulty == "hard":
return (hard_question, hard_answers)
else:
print "That is not a level."
question_level()
print question_level()
You are calling your function inside your function, which is a recursive call which you don't want in this case. Try checking for errors outside your function, something like:
def question_level():
difficulty = raw_input("Please select a level of difficulty for your questions: Easy, Medium, or Hard. ").lower()
if difficulty == "easy":
return (easy_question, easy_answers)
elif difficulty == "medium":
return (medium_question, medium_answers)
elif difficulty == "hard":
return (hard_question, hard_answers)
else:
print "That is not a level."
return None
q = None
while q is None:
q = question_level()
print(q)
You have a recursive call on this line
question, answers = question_level()
Just remove the question_level() part and init answers to something else.
Below is my complete code with comments describing what each section should operate. In the picture,I have provided it shows how each condition would be verified with depending on the users inputting 'y' for yes and 'n' for no concerning symptoms.
The problem, I'm having is that I should be only asking the minimal question, in order to get the diagnosis of the exact condition without having to answer any other questions.
Ex. Don't have a fever and don't have a stuffy nose: Hypochondriac.
It should print: You are Hypochondriac, just by inputting no for Fever and no for a Stuffy Nose.
I have to go through the entire questionnaire to display the diagnosis but that shouldn't be.
How can i modify my code to only ask the minimal questions required?
![#Description: Creata a medical diagnosis program
#that asks the user whether they have a fever, a rash,
#a stuffy nose and if their ear hurts.
#Get user inputs on whether they have specific conditions
userFever = input("Do you have a fever (y/n): ")
userRash = input("Do you have a rash (y/n): ")
userEar = input("Does your ear hurt (y/n): ")
userNose = input("Do you have a stuffy nose (y/n): ")
#Conditional statements that determine the diagnosis of the user
if userFever == 'n' and userNose == 'n':
print("Diagnosis: You are Hypchondriac")
elif userFever == 'n' and userNose == 'y':
print("Diagnosis: You have a Head Cold")
elif userFever == 'y' and userRash == 'n' and userEar == 'y':
print("Diagnosis: You have an ear infection")
elif userFever == 'y' and userRash == 'n' and userEar == 'n':
print("Diagnosis: You have the flu")
elif userFever == 'y' and userRash == 'y':
print("Diagnosis: You have the measles")][1]
Just construct a hierarchy of questions depending on which one discriminates most. In your case is very easy because the symptoms are totally disjoint. The fever would be the top question: if you don't have fever, you're only interested in knowing if there's stuffy nose or no. If there is, you want to know if there's a rash before asking for the ear. So, I'd start like this:
userFever = input("Do you have a fever (y/n): ")
if userFever == 'n':
userNose = input("Do you have a stuffy nose (y/n): ")
if userNose == 'n':
...
else:
...
else:
# The other questions
Given that this looks like homework, I leave the rest to you :P
Well especially if you want to extend this program I would recommend using something like this:
from itertools import islice
class Diagnosis:
diagnoses = ("You are Hypchondriac", "You have a Head Cold",
"You have an ear infection", "You have the flu", "You have the measles"
)
def __init__(self):
self.diagnosis = 0 # Consider using an enum for this
self.queue = (self.check_fever, self.check_nose, self.check_rash,
self.check_ear)
def ask(self, question):
answer = input(question + " [y/N] ").lower()
return answer != "" and answer[0] == "y"
def make(self):
queue_iter = iter(self.queue)
for func in queue_iter:
skip = func()
# return -1 if you want to break the queue
if skip == -1:
break
if skip > 0:
next(islice(queue_iter, skip, skip + 1))
def check_fever(self):
return 1 if self.ask("Do you have a fever?") else 0
def check_nose(self):
if self.ask("Do you have a stuffy nose?"):
self.diagnosis = 1
return -1
def check_rash(self):
if self.ask("Do you have a rash?"):
self.diagnosis = 4
return -1
return 0
def check_ear(self):
if self.ask("Does your ear hurt?"):
self.diagnosis = 2
else:
self.diagnosis = 3
return -1
def get_result(self):
return self.diagnoses[self.diagnosis]
if __name__ == "__main__":
diagnosis = Diagnosis()
diagnosis.make()
print("Diagnosis: " + diagnosis.get_result())
Basically put all functions you need in the queue and return the number of functions you want to skip or return -1 if you're finished.
This is the old 'Guess who' game - otherwise known as a binary decision tree.
Rather than do your homework here is a different example
male?
/ \
N Y
blonde? beard?
/ \ / \
N Y N Y
Sam Jane hat? Andy
/ \
N Y
Bob Fred
In terms of solving these then an OO approach is almost always best as it is easily understandable and adding extra items easy. Use a recursive method to get the answer...
class Question(object):
no = None
yes = None
def __init__(self, question):
self.question = question
def answer(self):
r = raw_input("%s (y/N): " % self.question).lower()
next = self.yes if r == 'y' else self.no
# check if we need to descend to the next question
if hasattr(next, 'answer'):
return next.answer()
# otherwise just return the answer
return next
# create a bunch of questions
male = Question("Are you male?")
blonde = Question("Are you blonde?")
beard = Question("Do you have a beard?")
hat = Question("Are you wearing a hat?")
# hook up all the questions according to your diagram
male.no = blonde
male.yes = beard
blonde.no = "Sam"
blonde.yes = "Jane"
beard.no = hat
beard.yes = "Andy"
hat.no = "Bob"
hat.yes = "Fred"
# start the whole thing rolling
print "You are %s." % male.answer()