Hi I have this project of Mad libs but I donĀ“t know how to make a function that ask the user what level of difficulty between easy, medium or hard they want, and depending on their answer redirect them to the desired level of mad libs. This is what I have so far. Thanks.
parts_of_speech_words = ["VERB","PLACE","ADJECTIVE","NOUN","PLURALNOUN","ADVERB"]
level_easy = """I __VERB__ to go to the __PLACE__
but I don't go in the __ADJECTIVE__
I am __ADJECTIVE__ of the __NOUN__
and getting __VERB__ by a __NOUN__."""
level_medium = """Begging to hear __NOUN__
My ears remain __ADJECTIVE__
__NOUN__ for signs
my __NOUN__ remain __VERB__
Yet __NOUN__still VERB."""
level_hard = """I __VERB__ you without __NOUN__
how, or when, or from where,
I love you __ADVERB__,
without __PLURALNOUN__ or pride;
So I love you because I know
no other way that this:
Where I does not VERB, nor you,
so close that your NOUN
on my chest is my hand,
so close that your NOUN close
as I fall ADJECTIVE."""
greeting = raw_input ("Welcome to mad libs, What's your name? ")
prompt = raw_input ("Select your level: easy, medium or hard: ")
def entry_level_prompt (variable_level):
easy = level_easy
medium = level_medium
hard = level_hard
for e in variable_level:
if prompt == easy:
return level_easy
print level_easy
if prompt == medium:
return level_medium
print level_medium
if prompt == hard:
return level_hard
print lever_hard
print "Ok %s you chose the %s level" % (greeting , prompt)
print entry_level_prompt (variable_level)
def parts_of_speech (words_string, list_of_part_of_speech):
for pos in list_of_part_of_speech:
if pos in words_string:
return pos
return None
def play_mad_libs (split_string, list_of_part_of_speech):
replaced = []
split_string = split_string.split ()
for words_string in split_string:
replacement = parts_of_speech (words_string, list_of_part_of_speech)
if replacement != None:
user_input = raw_input ("Type in a: " + replacement + " ")
words_string = words_string.replace (replacement, user_input)
replaced.append(words_string)
else:
replaced.append(words_string)
replaced = " ".join(replaced)
return replaced
print play_mad_libs (entry_level_prompt, parts_of_speech_words)
You have a bug in your code. You are calling entry_level_prompt(variable_level) but variable_level does not exist outside of the method scope.
To control the difficulty, you can create a method called get_difficulty()
def get_difficulty():
choice = ""
while choice not in ('easy', 'medium', 'hard'):
choice = raw_input("choose your difficulty: ")
if choice == "easy":
return level_easy
elif choice == "medium":
return level_medium
elif choice == "hard":
return level_hard
else:
print("Invalid choice...")
You've confused the selector -- "easy", "medium", or "hard" -- with the variable you want to return -- level_easy, level_medium, or level_hard. You cannot use the variable prompt for both purposes at the same time.
I recommend that you keep variable prompt as you started: it holds the user input. Then, simply test it and return the needed script:
if prompt == "easy":
return level_easy
elif prompt == "medium"
return level_medium
elif prompt == "hard"
return level_hard
else:
"Please enter easy, medium, or hard for the level."
Related
racks = "1"
racksPerSecond = 0
gameScreenChoice1 = "Traffic Drugs (1) "
gameScreenChoice2 = "Get Slaves (2) "
print("You are NBA Young Boy (Never Broke Again)")
startScreen = input("To start your journey out the trenches press 1: ")
if startScreen == "1":
print("What do you want to do?")
waysToGetRacks = input(gameScreenChoice1 + gameScreenChoice2)
def TrafficDrugs(slaveQuestion1):
(
slaveQuestion1 == input(" Push P if you want a rack")
if TrafficDrugs(slaveQuestion1):
racks += "1"
)
def getSlaves():
()
if waysToGetRacks == "1":
TrafficDrugs()
if waysToGetRacks == "2":
getSlaves()
Dont ask about the varaibles, but im very confused why im getting a error
You don't need brackets inside your func:
def TrafficDrugs(slaveQuestion1):
slaveQuestion1 == input(" Push P if you want a rack")
if TrafficDrugs(slaveQuestion1):
racks += "1"
you can't call a recursive function you have just defined you need to enter a valid parameter in order to pass the if statement.
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.
I want to optimize my code to return well in a part of a code.
I know that I can do that with do while but I think it's maybe heavy with a lot of do while.
I identify where I want to return in comments
Can you suggest me a solution to solve my problem?
#return here 0
mainMenu()
choix = input()
if choix == 1:
print "Enter your username"
username = raw_input()
print "Enter your password"
password = raw_input()
createAccount.createAccount(username,password)
#return here 1
educatorMenu()
choix = input()
if choix == 1:
print "Enter his age"
ageChild = raw_input()
print "Enter his photo"
photoChild = raw_input()
educator.createChildAccount(ageChild, photoChild)
elif choix == 2:
childrenList = educator.seeChildrenList()
#Return to where it is written "return here 0"
elif choix == 3:
childrenList = educator.seeChildrenList()
print "Associate children?"
choixEnfant = input()
educator.associateChildren(childrenList,choixEnfant-1, educator.getIdEducator(username))
#Return to where it is written "return here 1"
Thanks a lot.
Note: I will not re-write/optimize your code, because I feel it should be a task for you to do so. Furthermore, there are quite some functions and references missing to rewrite it; you did not deliver an MWE.
Consequently, you may find this useful as a starting point and try to adapt this (very basic structure) to suit your needs. However, be warned: This also is far from being efficient, but it will help you to extend your knowledge of the basics.
def menu_main():
q = ['What would you like to do?',
'1: List educators',
'2: Create educator',
'3: Manage educator\'s children',
'4: Exit'].join('\n ')
return int(input(q).strip()[0])
def menu_educator_create():
usr = input('Enter username:').strip()
pwd = input('Enter password:').strip()
return (usr, pwd)
def menu_educator_manage():
q = ['What would you like to do?',
'1: List children',
'2: Add child',
'3: Return'].join('\n ')
return int(input(q).strip()[0])
if __name__ == '__main__':
edus = {}
exit = False
while not exit:
print('===')
cmd = menu_main()
if cmd == 1:
# List educators
pass
elif cmd == 2:
# Create educator
usr, pwd = menu_educator_create()
pass
elif cmd == 3:
# Manage children
# (should somehow obtain current educator first)
exit_edu = False
while not exit_edu:
subcmd = menu_educator_manage()
if subcmd == 1:
# List children
pass
elif subcmd == 2:
# Add child
pass
elif subcmd == 3:
# Return
exit_edu = True
else:
# None of the above
print('Unknown choice from educator menu.')
elif cmd == 4:
# Exit
exit = True
else:
# None of the above
print('Unknown choice from main menu.')
First off. My code:
UserInput = ("null") #Changes later
def ask_module(param, param2):
elif UserInput == (param):
print(param2)
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("test"):
print("test indeed")
ask_module("test2", "test 2")
I am not that good at coding, so this is probably something that I have done really wrong
This post seems a bit duchy, since I almost just have code,
but I have absolutely no idea on how to make this work.
What the code looks like without shortening:
while True:
UserInput = input()
UserInput = UserInput.lower()
print()
if UserInput == ("inventory"):
print("You have %s bobby pin/s" %bobby_pin)
print("You have %s screwdriver/s" %screwdriver)
elif UserInput == ("look at sink"):
print("The sink is old, dirty and rusty. Its pipe has a bobby pin connected")
else:
print("Did not understand that")
EDIT: I see that it might be hard to see what I'm asking.
I'm wondering how I can shorten my original code
If all your elif blocks have the same pattern, you can take advantage of this.
You can create a dictionary for the text you want to print and then do away with the conditionals.When it comes to choosing which one to print, you simply fetch the relevant text using its corresponding key. You use the get(key, default) method. If there is no key in the dictionary, the default value will be returned. For example,
choices = {'kick': 'Oh my god, why did you do that?',
'light him on fire': 'Please stop.',
'chainsaw to the ribs': 'I will print the number %d',
}
user_input = input().lower()
# individually deal with any strings that require formatting
# and pass everything else straight to the print command
if user_input == 'chainsaw to the ribs':
print(choices[user_input] % 5)
else:
print(choices.get(user_input, 'Did not understand that.'))
I found a solution, just stop using elif entirely.
Example:
userInput = "null"
def ask_question(input, output):
if userInput == (input):
print(output)
else: pass
while True:
userInput = input()
ask_question("test","test")
ask_question("test2", "test2")
ask_question("test3", "test3")
I apologize for how simplistic this may be, but I am a little confused looking at one part of this code.
# Geek Translator
# Demonstrates using dictionaries
geek = {"404": "clueless. From the web error message 404, meaning page not found.",
"Googling": "searching the Internet for background information on a person.",
"Keyboard Plague": "the collection of debris found in computer keyboards.",
"Link Rot" : "the process by which web page links become obsolete.",
"Percussive Maintainance" : "the act of striking an electronic device to make it work.",
"Uninstalled" : "being fired. Especially popular during the dot-bomb era."}
choice = None
while choice != "0":
print(
"""
Geek Translator
0 - Quit
1 - Look Up a Geek Term
2 - Add a Geek Term
3 - Redefine a Geek Term
4 - Delete a Geek Term
"""
)
choice = input("Choice: ")
print()
# exit
if choice == "0":
print("Good-bye.")
# get a definition
elif choice == "1":
term = input("What term do you want me to translate?: ")
if term in geek:
definition = geek[term]
print("\n", term, "means", definition)
else:
print("\nSorry, I don't know", term)
# add a term-definition pair
elif choice == "2":
term = input("What term do you want me to add?: ")
if term not in geek:
definition = input("\nWhat's the definition?: ")
geek[term] = definition
print("\n", term, "has been added.")
else:
print("\nThat term already exists! Try redefining it.")
# redefining an existing term
elif choice == "3":
term = input("What term do you want me to redefine?: ")
if term in geek:
definition = input("What's the new definition?: ")
geek[term] = definition
print("\n", term, "has been redefined.")
else:
print("\nThat term doesn't exist! Try adding it.")
# delete a term-definition pair
elif choice == "4":
input("What term do you want me to delete?")
if term in geek:
del geek[term]
print("\nOkay, I deleted", term)
else:
print("\nI can't do that!", term, "doesn't exist in the dictionary.")
# some unknown choice
else:
print("\nSorry, but", choice, "isn't a valid choice.")
input("\n\nPress the enter key to exit.")
I understand how all of this works with the exception of the print() function after choice = input(Choice: ")
Why is that there? If I remove it, nothing changes (as far as I can tell), so I was curious about its significance.
print() with no parameters prints a newline. The point is to show a blank line in the terminal output.
It prints a new line (which is visible as an empty line in the console output).
An empty print() outputs a newline, so maybe the only reason it's there is to add a newline?