I am writing a program that asks two users boy or girl names and whether they like them or not. This is the beginning of the program and I created a function so if they don't input boy or girl, it asks them again so the program can properly run.
user_name_class= BabyNames()
print "Let's get started!"
print "Who will user1 be and who will user2 be?"
name_user1 = raw_input("User1 = ")
name_user2 = raw_input("User2 = ")
print user_name_class.baby_namer(raw_input("Do you want boy or girl names? \n").lower())
class BabyNames():
def baby_namer(self, gender):
self.gender = gender
if 'b' not in gender or 'g' not in gender:
return self.start_wrong_input()
elif 'b' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(boy_rounds))))
return boy(boy_rounds[test])
elif 'g' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(girl_rounds))))
return girl(girl_rounds[test])
else:
pass
def start_wrong_input(self):
x = BabyNames()
print "You need to put boy or girl to move on!"
re_try = raw_input("Do you want boy or girl names? \n").lower()
if 'g' in re_try:
return x.baby_namer('girl')
elif 'b' in re_try:
return x.baby_namer('boy')
else:
print "You need to put boy or girl to move on!"
I know creating the class probably wasn't necessary, but I just learned about them so I tried incorporating them into my code.
What is happening is at "Do you want boy or girl?" if you input anything else besides that, it properly calls the function and re-asks it but then when you put boy or girl, it loops and continues to asks the question without breaking. Why is this happening and let me know if I need to elaborate on anything else!(ps I'm a beginner so it may not be pythonic, but I'm working on it!)
Use if 'b' not in gender and 'g' not in gender, using or always puts you back to the start_wrong_input method because if gender is girl b is not in girl and if gender is boy g is not in boy so if 'b' not in gender or 'g' not in gender: will always evaluate to True
class BabyNames():
def baby_namer(self, gender):
if 'b' not in gender and 'g' not in gender:
return self.start_wrong_input()
elif 'b' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(boy_rounds))))
return boy(boy_rounds[test])
elif 'g' in gender:
test = raw_input("What round are you on? (1-{}) \n".format(str(len(girl_rounds))))
return girl(girl_rounds[test])
else:
pass
def start_wrong_input(self):
print "You need to put boy or girl to move on!"
re_try = raw_input("Do you want boy or girl names? \n").lower()
if 'g' in re_try:
return self.baby_namer('girl') # use self.baby_namer, you don't need to use x = BabyNames()
elif 'b' in re_try:
return self.baby_namer('boy')
else:
print "You need to put boy or girl to move on!"
The error in your code is in baby_namer:
if 'b' not in gender or 'g' not in gender:
You probably want a 'and' there, you fail if it is not a boy or if it is not a girl. You could try with entering the 'boyg' value...
Apart from that, you should not use recursive calls to make loops, it's difficult to read ! Use a proper while loop.
You've create something that's called mutual recursion functions
function: baby_namer() calls start_wrong_input() and then start_wrong_input() calls back in return to start_wrong_input(). And you got yourself an infinite loop.
Related
So I'm creating this based of this resource, linked here: https://www.derekshidler.com/how-to-create-a-text-based-adventure-and-quiz-game-in-python/
EDIT: Here is a GitHub link to all the code: https://github.com/gabby-lucies/Quarter-1-Project/blob/master/intro.py
I'm currently stuck however, in my very first option, anytime to choose any of the options listed below, I get a NameError saying that my options are not defined. Can anyone give me any advice? Thanks! Also, sorry if this is a dumb question.
#importing
import time
#How players could respond
answer_A = ["A", "a"]
answer_B = ["B", "b"]
answer_C = ["C", "c"]
yes = ["Y", "y", "yes"]
no = ["N", "n", "no"]
#Objects
fwomp = 0
bownarrow = 0
sword = 0
money = 0
#playerName = input("Enter Your Name: ") #gets the player's name, obviously
required = ("\nUse only A, B, or C.\n")
#Startup
def intro():
#print("There is no saving. Sorry!")
#print("Hello! Please enter your name.")
#print("Nice to meet you!")
print("Let's begin!")
print("You wake up in a forest. You can't remember anything. You look around and find")
print("a small creek. You hear sound nearby that sounds like some sort of woodland creature.")
print("You also see some smoke in the distance. What would you like to do ?")
time.sleep(2)
#Choice 1 Options
print("A. Follow the creek.")
print("B. Follow the sound of the woodland creature.")
print("C. Walk towards the smoke.")
choice = input(">>> ") #gets choice
time.sleep(1.5)
if choice in answer_A:
option_creek() #Gives player creek option
elif choice in answer_B:
option_animal() #Give Fwomp options
elif choice in answer_C:
option_smoke() #Gives smoke options
else:
print(required)
intro()
def option_creek():
print("You follow the creek for an hour, and you eventually come across the river.")
print("You followed the river for another hour, and you found a riverside village.")
print("You walk into the village, desperately looking for food and water.")
print("You come across a large pub. It doesn't look very busy.")
print("You also come across an elegant resturant. It must be very expensive.")
print("There is also family outside of their house eating freshly picked food from their garden.")
print("Where will you go?")
print("A. Pub B. Resturant C. Family")
time.sleep(2.5)
choice = input(">>> ")
if choice in answer_A:
option_pub()
if choice in answer_B:
option_resturant()
if choice in answer_C:
option_family()
else:
print(required)
option_creek()
def option_smoke():
print("You walk towards the smoke. Eventually you find the source of the smoke.")
print("The smoke is coming from a lost and very angry tribe.")
print("They also don't speak your language.")
print("When they spot you, and you have nothing to offer them in return, so they assume you are there to kill them.")
print("Anways, fifty of them shot you with arrows all at once.")
time.sleep(2)
print("Also, you're dead!")
time.sleep(2)
option_smoke()
def option_animal():
print("Seriously, you walked towards a strange animal sound just like that?")
print("Luckily, it is only a Fwomp. It doesn't kill you, but it does glare at you strangely.")
print("Fwomps are cute, so you want to pet it.")
print("You also want to take the Fwomp.")
print("You're also hungry and horrible so you also kind of want to eat the Fwomp.")
print("What will you do?")
print("A. Pet Fwomp B. Take Fwomp C. Eat Fwomp")
time.sleep(2.5)
choice = input(">>> ")
if choice in answer_A:
fwomp = 1
option_petfwomp()
elif choice in answer_B:
fwomp = 1
option_takefwomp()
elif choice in answer_C:
option_eatfwomp()
else:
print(required)
option_animal()
I've looked over your github code, so i'm changing my answer for that
After each of your option functions, you're immediately calling it, shown here
def option_animal():
print("Seriously, you walked towards a strange animal sound just like that?")
print("Luckily, it is only a Fwomp. It doesn't kill you, but it does glare at you strangely.")
print("Fwomps are cute, so you want to pet it.")
print("You also want to take the Fwomp.")
print("You're also hungry and horrible so you also kind of want to eat the Fwomp.")
print("What will you do?")
print("A. Pet Fwomp B. Take Fwomp C. Eat Fwomp")
time.sleep(2.5)
choice = input(">>> ")
if choice in answer_A:
fwomp = 1
option_petfwomp()
elif choice in answer_B:
fwomp = 1
option_takefwomp()
elif choice in answer_C:
option_eatfwomp()
else:
print(required)
option_animal()
As python is a procedural language, only the code that is before this call in the file exists, thus, at the point where you call option_animal, option_petfwomp doesn't exist, however if you remove all of these function calls and move them to the end of the file, it should work.
Hope this helps
Your code is not wrong, it's simply incomplete. I'm assuming you're using this to learn Python. Let me ask you a quick question. When you press run, you get some options.
What will you do?
A. Pet Fwomp B. Take Fwomp C. Eat Fwomp
If I type "A" and hit enter, it runs option_petfwomp()
But in your code you haven't defined this function.
If you add:
def option_petfwomp():
print("option_petfwomp")
def option_takefwomp():
print("option_takefwomp")
def option_eatfwomp():
print("option_eatfwomp")
you'll understand how it works. Basically, you are controlling the flow of the program. If you define these functions, you can then call them from your game.
My advise:
Think about what you want your code to do.
Map it out as a diagram or psuedo-code.
Code it.
It seems like you copy-pasted the code, without knowing what it does, or knowing what you want it to do. That's all fine, but take time out to understand your code before hoping someone else will understand it for you.
I'm just writing some small code and I'm not able to make this work, I am only able to have one string which is e.g boy or girl but I would like to have both, do I have to make a separate elif statement or can I somehow put girl in there as well
gender = input("Are you a boy or a girl? : ")
if (gender != "boy"):
print("Get out of here you mutant")
exit()
You would need to have 3 conditions:
if gender == 'boy':
print ('You are a boy')
elif gender == 'girl':
print ('You are a girl')
else:
print("Get out of here you mutant")
Or you can do like that:
if gender in ('boy', 'girl'):
print('You are a {}'.format(gender)
else:
print("Get out of here you mutant")
In the second script you check if gender is a girl or a boy and if so it puts gender variable in the print output string.
I have been trying to figure out how to add a score counter for the mini quiz that I made. I've tried different things and even tried to look up how to do it but I just cannot figure it out for what ever reason. Please help!
This is the code:
score = 0
def question1():
print("1. Who hit the walk-off home run to extend the A's AL-record win streak to 20 games in 2002?"
"A. Kevin Millar"
"B. Scott Hatteberg"
"C. Sammy Sosa"
"D. Josh Donaldson")
a = input("Please enter your answer in a lower case letter:")
if a == 'C':
print('You are smart!')
score += 1
else:
print('Better luck next time!')
return
def question2():
print("2. Who was the last Tigers pitcher to throw a no-hitter?")
b = input("What is your final answer:")
if b == 'Justin Verlander':
print('I am impressed whith how smart you are')
score += 1
else:
print("Are you even trying")
return
def Quiz():
question1()
question2()
You need to declare score as global inside your functions.
def question2():
# declare that you're using the global variable score
global score
print("2. Who was the last Tigers pitcher to throw a no-hitter?")
b = input("What is your final answer:")
if b == 'Justin Verlander':
print('I am impressed whith how smart you are')
score += 1
else:
print("Are you even trying")
return
If you don't tell the interpreter that you're using the global variable, it assumes that you're referring to a score variable that was declared in the scope of the function.
As Allie Filter wrote, declaring score as global is one possibility. You can also take OOP inspired approach and create a class Test with question as a method and score as a class variable.
class Test:
score = 0
def question1(self):
print("1. Who hit the walk-off home run to extend the A's AL-record win streak to 20 games in 2002?"
"A. Kevin Millar"
"B. Scott Hatteberg"
"C. Sammy Sosa"
"D. Josh Donaldson")
a = input("Please enter your answer in a lower case letter:")
if a == 'C':
print('You are smart!')
self.score += 1
else:
print('Better luck next time!')
return True
def question2(self):
...
...
def take_quiz(self):
self.question1()
self.question2()
return self.score
You can run your test by creating an instance of Test and calling method take_quiz() on it.
Some basics of OOP can be found here and in documentation.
FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround==("Yes") or FarmGround==("yes"): #this is if
print("You patted the animal") #print statement if you patted the animal it will go onto the next if statement
if print=("You patted the animal"):
elif FarmGround==("No") or FarmGround==("no"): #this is elif
print("You didn't patt the animal and it is triggered")
undescribed image
Your code is quite clear. What I understand is you want to ask another question if animal is patted.
FarmGround=input("Do you want to pat the animal? ") #this is the input
if FarmGround=="Yes" or FarmGround=="yes": #this is if
print("You patted the animal")
holy_field = input("Did you clear the field?")
if holy_field.lower() == "yes":
print("Do something else. Don't look at me.")
else:
print("When are you going to do it ?")
elif FarmGround== "No" or FarmGround== "no": #this is elif
print("You didn't patt the animal and it is triggered")
You can indent additional statements, including if statements inside your existing if block, just like you're indented the first print statement. It's not clear from your question what exactly you want to do, so I'll fill in some pseudo-code (which you can replace with whatever you actually want):
FarmGround=input("Do you want to pat the animal? ")
if FarmGround==("Yes") or FarmGround==("yes"):
print("You patted the animal")
some_other_answer = input("Some other question?") # here's more code inside the first if
if some_other_answer == "Foo": # it can include another if statement, if you want it to
print("Foo!")
elif FarmGround==("No") or FarmGround==("no"):
print("You didn't patt the animal and it is triggered")
Indentation matters in python. To nest an if statement in another if statement, just indent it below the first with 4 spaces.
If ( var1 == 1 ):
If ( var2 == 2 ):
print "Both statements are true."
I am making a program on python 3. I have a place that I need the script to restart. How can I do this.
#where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
print("Press any key to exit")
input()
It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy" or gender == "girl":
print("Lets get on with the story.")
break
print("Sorry. You cant have that. Type boy or girl.")
print("Press any key to exit")
input()
Simple but bad solution but you get the idea. I am sure, you can do better.
while True:
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")
if gender == "boy":
print("Lets get on with the story.")
elif gender == "girl":
print("lets get on with the story.")
else:
print("Sorry. You cant have that. Type boy or girl.")
#restart the code from start
restart = input("Would you like to restart the application?")
if restart != "Y":
print("Press any key to exit")
input()
break
Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:
phrase = "hello, world"
while (input("Guess the phrase: ") != phrase):
print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful
This outputs the following, with my user input shown as well:
Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct
or you can have two separate function written over, It's same as above(only it's written as two separate function ) :
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while (not(game(phrase))):
print("Incorrect.")
print("Correct")
main()
Hope this is what you are looking for .