asking for raw_input over and over - python

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.

Related

Accessing lists / data passing to class from list

I recently was trying to work on a twist to a program I am writing for my first program really. And I have everything working if the user is told to enter some values each time the game runs.
However, I was thinking that it should have a default set of characters that my program/game would use every time. My first goal was to get this to just give every player the same default 3 characters. But eventually this would need to have a have a list expanded of at least the character names.
My trouble comes in that I have taken a if loop that gathered the data each time if they said they have new characters to create, and have tried to modify it to the best of my knowledge to use a list and have it use the position in the loop to get that list number.
Then pass that data down the same paths I had created in the class. But it seems to be just skipping this section which right now I cant see why(I am sure this is a inexperienced moment) Or I am trying to access the list incorrectly? Anyway help on this would be huge, I have included my code below.
I have added commented lines to indicate the section of code that appears to be skipping.
And clarification I hope on this question is Is the for in loop the right way to solve this issue? And if so am I accessing this the correct way?
print ("Welcome to Chose your own adventure python edition")
print ("")
players = []
playerCharacters = []
def playerNames():
playerNum = int(input("How many players are playing? "))
if playerNum > 4:
print("I am sorry, unfortunately only four players are permitted.")
return
for playerId in range(playerNum):
newPlayerName = input(f"What is player {playerId + 1}'s name?")
players.append(newPlayerName)
print(f"Welcome: {' & '.join(players)}!")
def characters():
charAmount = 3
for index, player in enumerate(players):
playerCreate = input("{} (player {}), do you have a character to create. (y/n)".format(
player, str(index+1)))
if playerCreate.lower() =="y":
charAmount = int(input("How many characters does this player begin the game with?"))
for x in range(0,(charAmount)):
getCharName = input("Enter Next Char name ")
getCharDice = input("Please enter the number of dice this char will use. ")
getCharRole = input("Please enter the villagers role. ")
charData = {
"name": getCharName,
"diceCount": getCharDice,
"role": getCharRole,
"playerName": player
}
newCharacter = Character(characterData=charData)
newCharacter.printSummary()
playerCharacters.append(newCharacter)
if playerCreate.lower() == "n":
defaultCapture = input("Would you like to begin with the default charatures. (y/n)?" )
if defaultCapture.lower() == "y":
###Beginning of skipped code
for x in range (0,3):
DefaultCharName = ["Bob", "Sally", "Tommy"]
DefaultDiceCount = 1
DefaultRole = ['Builder', "Recruiter" , "Nothing"]
charData = {
"name": DefaultCharName(x),
"diceCount": DefaultDiceCount,
"role": DefaultRole(x),
"playerName": player
}
DefaultCharacters = Character(characterData=charData)
DefaultCharacters.printSummary()
playerCharacters.append(DefaultCharacters)
###End of skipped section
if defaultCapture.lower == "n":
print("Well it looks as though you dont really want to play.")
continue
print("Summary ==========================")
for player in playerCharacters:
print("{characterName} Controlled by {playerName}".format(
playerName=player.playerName,
characterName=player.name ))
return
class Character:
name = "default name"
playerName = "john/jane doe"
diceCount = "1"
role = "vanillaPaste"
def __init__(self, characterData):
self.playerName = characterData['playerName']
self.role = characterData['role']
self.diceCount = characterData['diceCount']
self.name = characterData['name']
def printSummary(self):
print("{player} summary: \r\n \r\nCharacters:\r\nName: {characterName} \r\nDice: {dice} \r\nRole: {role} \r\n"
.format(
characterName=self.name,
player=self.playerName,
dice=self.diceCount,
role=self.role
);
playerNames()
characters()
While your code is, like the comments say, a little too long for a minimal SO question, in this case it's an easy fix.
Just before your "start of skipped section", you have
if defaultCapture.lower == "y":
which is missing the parentheses to actually call .lower(), to lower-case the string. (Comparing a function to a string would always be false.)
That expression should be
if defaultCapture.lower() == "y":
try to check the indentation of the for loop and when you enter something, do not have spaces. You should use
defaultCapture.lower().split =="y"
OR
defaultCapture.lower().split.contains("y")// Add the brackets()

How do I feed a string from 1 function into 2 other functions, and print it in python?

I'm creating a text adventure game, and want to make it so if the user types 'x' or 'examine', it prints the description for a room (which is stored in a string inside the a function)
This is the code:
def look(dsc):
print(dsc)
def usr_input(dsc):
a = input(">>> ")
if a == "examine" or a == "x":
look(dsc)
if a == "help":
print("north, n, east, e, south, s, west, w, up, u, down, d, inventory, i, examine, x")
if a == "north" or a == "n" or a == "forwards":
return "north"
if a == "east" or a == "e" or a == "right":
return "east"
if a == "south" or a == "s" or a == "backwards":
return "south"
if a == "west" or a == "w" or a == "left":
return "west"
if a == "up" or a == "u":
return "up"
if a == "down" or a == "d":
return "down"
else:
print("Sorry, I don't understand that. (Type 'help' for a list of commands")
usr_input()
return False
def room_00():
room_description = "Description goes here"
print(room_description)
usr_input(room_description)
room_00()
Basically, I need the function 'look' to print the description for that room whenever the user types x, but I can't get the functions to link.
Your code seems to run without any issue, ignore the guy above, Python 3 does need brackets for print calls.
It is returning a traceback though because on line 28, you're calling the usr_input() function without providing a parameter.
You can fix this by defining the function like so:
def look(dsc=''):
print(dsc)
This will pass an empty string to the function unless you pass it a string of your own.
The other issue is that you're using raw if statements. So that last evaluation here:
if a == "down" or a == "d":
return "down"
else:
print("Sorry, I don't understand that. (Type 'help' for a list of commands")
usr_input()
return False
goes to the else branch because x is neither "down" nor "a", you should replace all if statements below the first one with elif, and leave the last else in place
Try a = raw_input('>>> ') and then a = a.strip()
also
def look(dsc):
print dsc
You need a tab there and no need for ()
I think the right solution will be creating the class Room, instances of which would store room description and maybe something else, perhaps, a list of doors to other rooms (you are not going to have only one room, are you?)
And this class should also have look method doing you already know what.
I think you should store the current room in some global variable and when you need the current room's description, you just access that variable, get the Room object and call its look method.
As I know, accessing function local variable is impossible. If I am wrong, correct me please.

Python fill-in-the-blanks code

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.

Simple Quiz - How Do I Link Variables?

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.

Simple Phonebook

this is some simple code I wrote for a phonebook.
It does not seem to work though, and I do not know why.
I am very new to python, and I am sure there are many errors.
def startup(contactlist = {}):
print "Welcome to Contacts+\n"
print "Please enter your name"
name = raw_input()
print "Hi " + name + " would you like to check your existing contacts or make new ones?"
print "To make new contacts type in 'New'"
print "To check existing contacts type in 'Contacts'"
choose = ""
choose = raw_input()
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
def newcontact():
startup(contactlist = {})
print "To create a new contact please first input the name"
contactname = raw_input()
print "Next enter the phone number"
contactnumber = raw_input()
print "Contact created!"
contactlist[name] = number
def checkcontact():
startup(contactlist = {})
print contactlist
startup()
Have you tried to run this...?
This if/elif statement shouldn't be indented:
if choose == "'New'" or choose == "'new'" or choose == "New" or choose == "new":
newcontact()
elif choose == "'Contacts'" or choose == "'contacts'" or choose == "Contacts" or choose == "contacts":
checkcontact()
And why do you have:
startup(contactlist = {})
in the beginning of newcontact() and checkcontact() function?
Four things you can do right now to make your code better:
Go read about this gotcha in Python. We tricked you. (We're sorry! We had good reasons.) You can't really do that with lists and dicts, and you have to use a Python idiom involving None to do it right.
Use raw_input's first argument. Instead of print('Hey user!'); raw_input(), just write raw_input('Hey user!').
Learn the in keyword. Whenever you find yourself saying if x == 'x' or x == 'y' or x == 'z', it's probably easier to write if x in 'xyz' (strings are iterable, remember?). You can also get rid of two of those cases by stripping off quotes the user might enter if you don't want them -- choose.strip("'").
Fix your function calls. Functions in Python can be called in two ways, using positional arguments f(a, b, c) or keyword arguments f(a, b=0, c=2). Calls like startup(contactlist={}) are just explicitly setting that argument to the empty dict, its default value, so this is always equivalent to startup() the way you have it defined.

Categories

Resources