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.
Related
Trying my hand at writing a very simple Game of Chance game on Codecademy while working through their Python course. I was doing ok (I think) for a while and the code returned what I expected it to, but now it feels I'm stuck and googling things frantically hasn't really helped me and I don't just want to look at the actual solution because where's the fun in that so here goes.
My thought process was the game should initially ask the player to input their guess and their bid, then run the code in game() and print the outcome. This was then to be locked in a while loop to check if the user wanted to continue playing or not and if the answer was "Yes" to restart the game() function again. This is where I am stuck as I just can't figure out what to put in line 26 after the "Yes" check returns True.
I guess the TL/DR version of my actual question is how do you (without giving the actual code away) call a function from within a while loop? Wondering if perhaps I'm simply headed in the wrong direction here and need to review while loops once more.
Thanks!
# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game():
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
money = 100
if guess == num:
money = (money + bid)
print("You Won")
print("You now have: " + str(money) +" money")
return money
else:
money = (money - bid)
print("You lost, you will die poor")
print("You now have: " + str(money) +" money")
return money
# Run game() while there's still money left in the pot
def structure():
while money > 0:
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
game() # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
game()
Ok so a few things to go through here.
First off, the concept of a local variable is coming into play here and is why your money variable is not communicating properly between your two functions. Each of your functions uses it's own money variable, which is completely independent of the other.
So this is the root of your current problem, where your money > 0 loop never actually runs. Secondly, although this might have just been done for troubleshooting, you don't actually call structure which is supposed to control game().
Lets try something like this where we keep money in the structure function and pass an update version to the game function as a parameter. Then, because you have game() returning money, you can just update the money value in your structure() call.
# Import stuff
import random
# Generate random number from 1 - 9
num = random.randint(1, 10)
# The actual game, asking user for input and returning the outcome
def game(money):
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
if guess == num:
money = (money + bid)
print("You Won")
print("You now have: " + str(money) +" money")
return money
else:
money = (money - bid)
print("You lost, you will die poor")
print("You now have: " + str(money) +" money")
return money
# Run game() while there's still money left in the pot
def structure():
money = 100
money = game(money)
while money > 0:
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
money = game(money) # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
structure()
Notice because of how your while loop is written, in order to get game() to run the first time I had to call it before the while loop. Maybe as a challenge, see if you can be rewrite the structure of your loop so that you don't have to do this!
Welcome to SO. Your code is overall fine. Here's one way to slightly change your code to make it work:
... Most of the code ...
money = 10
def structure():
another_go = "Yes" # initialize to 'Yes', so we'll
# always have a first game.
while money > 0:
if another_go == "Yes":
game() # This is where I'm stuck
elif another_go == "No":
print("Oh well, suit yourself")
break
else:
print("Pick Yes or No")
print(another_go)
# move 'another go' to the end of the loop
another_go = input("Would you like to play again? Yes or No: ")
structure() # call this function to start
# make money a global parameter with a -ve value
money = -1
def game():
global money
guess = int(input("Guess the number: "))
bid = int(input("Bet on the game: "))
# Then, if money has default(game started for first time), update it
if(money < 0):
money = 100
.
.
.
.
while money > 0:
global money
another_go = input("Would you like to play again? Yes or No: ")
if another_go == "Yes":
game(money) # Pass remaining money to game()
.
.
.
I'm having a bit of trouble with changing a variable value (canteen) to make it so that it runs from 3 to 0. I'm not sure why the value of canteen does not go to less than 2 every time I hit the "1" key. How do I make it so that the value of canteen becomes zero when the player hits the "1" key 3 times?
# Global Variables
km_travelled = 0
thirst = 0
camel_tiredness = 0
natives_travelled = -20 # Player always starts 20 km away from player once player reaches checkpoint
def introduction():
print("Welcome to Camel!")
print("You have stolen a camel to make your way across the great Mobi desert")
print("The natives want their camel back and are chasing you down! Survive ")
print("your desert trek and out run the natives \n \n")
def choices():
print("1. Drink from your canteen.")
print("2. Ahead at moderate speed.")
print("3. Ahead at full speed.")
print("4. Stop for the night.")
print("5. Status check.")
print("9. Quit \n")
def questions(answer):
canteen = 3
if "9" in answer:
print("GAME EXIT.")
done = True
elif "1" in answer:
print("You drank from the canteen")
canteen = canteen - 1
print(canteen)
def main():
# Global variables
done = False
# Go through once
introduction()
while not done:
choices()
answer = input("What is your choice? ")
questions(answer)
if __name__ == '__main__':
main()
The canteen variable is locally scoped, to the questions function. And each time you run that function, it is reinitialised to the value 3. Since the if statement is only executed once inside the function, it will never go lower than 2.
One simple way to solve this - even though it's not good practice - is to have canteen as a global variable. Put canteen = 3 outside any function, alongside the rest of your globa variables. Remove that statement from the questions function, and replace it with global canteen so that Python knows you are referring to the global variable when you alter it within the function.
Note that you will have a similar problem with the done variable, and can consider making this global too.
And finally, as I hinted at, global variables are bad to have in any program that isn't extremely simple - because they can be affected by everything in the program, and therefore make it very hard to figure out what is going on. There are a number of alternative ways to approach constructing complex programs which avoid global variables, which I would encourage you to look at. Using classes (which hold state internally, rather than globally) is one such way which is well-supported in Python.
Since while statement evaluates to true, the value 3 is assigned to the variable canteen after every choice. You can replace canteen = 3 with global canteen and assign the variable canteen outside it's function.
If you want to avoid using global, you can use a dictionary like this example:
def questions(answer, canteen):
if "9" in answer:
print("GAME EXIT.")
done = True
elif "1" in answer:
print("You drank from the canteen")
canteen['c'] = canteen['c'] - 1
print(canteen['c'])
def main():
# Global variables
done = False
canteen = {'c': 3}
# Go through once
introduction()
while not done:
choices()
answer = input("What is your choice? ")
questions(answer, canteen)
It is because you're defining canteen = 3 at the beginning of your questions() loop. You should define it once, with your global variables.
# Global Variables
km_travelled = 0
thirst = 0
camel_tiredness = 0
natives_travelled = -20 # Player always starts 20 km away from player once player reaches checkpoint
canteen = 3 # Define it here, as a global variable
### Truncated ###
def questions(answer):
# canteen = 3 # Don't define here
global canteen # but refer to the top one here
if "9" in answer:
print("GAME EXIT.")
done = True
elif "1" in answer:
print("You drank from the canteen")
canteen = canteen - 1
print(canteen)
def main():
# Global variables
done = False
# Go through once
introduction()
while not done:
choices()
answer = input("What is your choice? ")
questions(answer)
if __name__ == '__main__':
main()
I'm trying to get my balance to add up but I don't know how to save my balance to a variable from a random number. In the screenshot below, it shows that they are giving and my balance does not add up.
Steps taken:
I've tried passing bank instead of money through my functions
Read the python docs doesn't say anything about saving rand ints as variables
Tried if and then statement but same issue. My balance was not adding up.
Import different libraries did not work
import random
def main():
bank=0
backstory()
pet=input("what pet do you have? ")
print("nice! your pet will be a ", pet)
decisions(pet, bank)
#outcome()
def backstory():
print('You are a homeless person and are trying to get money to feed yourself and your pet.')
print('Everything you choose to do will effect how your outcome will be.')
print('You have five decisions you can make')
print('dont forget to eat or feed your pet so neither if you two will die!')
def decisions(animal,money):
print('enter "beg" to beg for money')
print('enter "work" to work for money')
print('enter "eat" to eat food')
print('enter "feed" to feed your pet')
print('enter "steal" to steal from someone!')
print('enter "skip" to do nothing and skip a decision for the day')
cont=0
bank=0
while cont<=4:
pick=input("what will be youre decision? ")
if pick=="beg":
beg(bank)
cont+=1
elif pick=="work":
work(money)
cont+=1
elif pick=="eat":
eat(money)
cont+=1
elif pick=="feed":
feed(money)
cont+=1
elif pick=="steal":
steal(money)
cont+=1
elif pick=="skip":
skip(money)
cont+=1
else:
print("sorry! thats not an option! please pick something from above")
#outcome(animal, money)
print("all done")
def beg(bank):
names=["Alvin and the Chipmunks", "Bob", "Timmy", "Alex", "Carah", "A very Rich Man"]
amount=random.randint(1,20)
print(random.choice(names), "gave you ", amount, "!")
bank=amount+bank
print("your balance is ", bank)
main()
Because your bank is always local variable, in beg function , you don't make bank return, so bank in decisions function is always zero, so you need return it in beg function , like this:
def main():
bank=0
backstory()
pet=input("what pet do you have? ")
print("nice! your pet will be a ", pet)
decisions(pet, bank)
#outcome()
def backstory():
print('You are a homeless person and are trying to get money to feed yourself and your pet.')
print('Everything you choose to do will effect how your outcome will be.')
print('You have five decisions you can make')
print('dont forget to eat or feed your pet so neither if you two will die!')
def decisions(animal,money):
print('enter "beg" to beg for money')
print('enter "work" to work for money')
print('enter "eat" to eat food')
print('enter "feed" to feed your pet')
print('enter "steal" to steal from someone!')
print('enter "skip" to do nothing and skip a decision for the day')
cont=0
bank=0
while cont<=4:
pick=input("what will be youre decision? ")
if pick=="beg":
bank = beg(bank)
cont+=1
elif pick=="work":
work(money)
cont+=1
elif pick=="eat":
eat(money)
cont+=1
elif pick=="feed":
feed(money)
cont+=1
elif pick=="steal":
steal(money)
cont+=1
elif pick=="skip":
skip(money)
cont+=1
else:
print("sorry! thats not an option! please pick something from above")
#outcome(animal, money)
print("all done")
def beg(bank):
names=["Alvin and the Chipmunks", "Bob", "Timmy", "Alex", "Carah", "A very Rich Man"]
amount=random.randint(1,20)
print(random.choice(names), "gave you ", amount, "!")
bank=amount+bank
print("your balance is ", bank)
return bank
and then run it
main()
You will get it.
You are a homeless person and are trying to get money to feed yourself and your pet.
Everything you choose to do will effect how your outcome will be.
You have five decisions you can make
dont forget to eat or feed your pet so neither if you two will die!
what pet do you have? beg
nice! your pet will be a beg
enter "beg" to beg for money
enter "work" to work for money
enter "eat" to eat food
enter "feed" to feed your pet
enter "steal" to steal from someone!
enter "skip" to do nothing and skip a decision for the day
what will be youre decision? beg
Alvin and the Chipmunks gave you 16 !
your balance is 16
what will be youre decision? beg
Alvin and the Chipmunks gave you 9 !
your balance is 25
what will be youre decision? beg
Alvin and the Chipmunks gave you 10 !
your balance is 35
what will be youre decision? beg
Alvin and the Chipmunks gave you 1 !
your balance is 36
what will be youre decision? beg
Carah gave you 13 !
your balance is 49
all done
I'm trying to create a game I used to play as a kid. The premise for the game is that there is a group of players and they take turns guessing baseball players. You don't just randomly guess players, but you guess a player using the previous guessed players first initial of their last name. For example if a player guessed Alex Rodriguez an acceptable follow up guess is Randy Johnson. If the player is incorrect they are out of the game. This is a simple game and something I want to use to learn python. I've been doing tutorials from Code Academy and Learn Python the Hard Way, but now I'm ready to start creating something. What I've gotten so far is something that sorta works, but I can't figure out a way to pull in a player database from a website and how to remove players and correctly create a round about session of player guessing. I've included my code and I'm hoping someone out there is kind enough to help guide me on my first project!
def players(name):
name_total = float(name)
print name_total
player = []
while name_total > 0:
player_name = raw_input("Enter Player Name ")
player.append(player_name)
name_total -= 1
print player
player_database = ['Barry Bonds', 'Alex Rodriguez', 'Brad Ausmus']
def guess(player_guess):
player_guess = player_guess
if player_guess in player_database:
print "Good guess!!"
player_database.remove(player_guess)
while player_database > 1:
guess(raw_input("Guess a player"))
else:
print "You lose"
return player_database
players(raw_input("How many players? "))
guess(raw_input("Guess a player "))
The problem is in the second while.
Your recursive function is being called infinite times, making your program break.
It should be an if...
Try this code:
def players(name):
name_total = float(name)
print name_total
player = []
while name_total > 0:
player_name = raw_input("Enter Player Name ")
player.append(player_name)
name_total -= 1
print player
player_database = ['Barry Bonds', 'Alex Rodriguez', 'Brad Ausmus']
def guess(player_guess):
player_guess = player_guess
if player_guess in player_database:
print "Good guess!!"
player_database.remove(player_guess)
if player_database > 1:
guess(raw_input("Guess a player"))
else:
print "You lose"
return player_database
players(raw_input("How many players? "))
guess(raw_input("Guess a player "))
I'm asked to produce a trivia game that has 10 questions. Each question should be picked at random. Every four questions Python should ask if the user wants to play again. If the user says "yes" then it continues again, if they say "no" it ends. If the game reaches the point that there are no more questions it should apologize and end the program.
I have two issues. Right now it doesn't seem to be using my playAgain() function. It also is giving me this error, "NameError: global name 'rounds' is not defined" this also comes up for the correct variable. I'm not sure how I can define these outside the mainObject() without modifying the data that they obtain in mainObject().
What should I do?
import random, sys
question1 = "In which US state would you find the zip code 12345?"
question2 = "What never works at night and requires a gnomon to tell the time?"
question3 = "What color is a polar bear's skin?"
question4 = "What is Indiana Jones' first name?"
question5 = "Which is bigger, the state of Florida or England?"
question6 = "How many white stripes are there on the American flag?"
question7 = "How many daily tides are there?"
question8 = "Which country has the longest coastline?"
question9 = "How many of the gifts in the song 'The Twelve Days of Christmas' do not involve birds?"
question10 = "It occurs once in a minute Twice in a week and once in a year what is it?"
answer1 = "New York"
answer2 = "Sundial"
answer3 = "Black"
answer4 = "Henry"
answer5 = "Florida"
answer6 = "Six"
answer7 = "Two"
answer8 = "Canada"
answer9 = "Six"
answer10 = "E"
Questions = [question1, question2, question3,
question4, question5, question6,
question7, question8, question9, question10]
Answers = [answer1, answer2, answer3, answer4,
answer5, answer6, answer7, answer8, answer9,
answer10]
print ("Welcome to the Dynamic Duo's WJ Trivia Game!!")
print ("Press \"enter\" to play.")
input()
last = len(Questions)-1
#rounds = 0
#correct = 0
playagain = " "
def playAgain():
if (rounds == 4 or rounds == 8):
print("Do you want to play another round? (Yes or No)")
playAgain = input()
accept = "Yes"
if PlayAgain.lower() == accept.lower():
mainObject()
else:
sys.quit()
def mainObject():
correct = 0
last = len(Questions)-1
rounds = 0
playagain = "yes"
while (last>=0): #This continually checks to make sure that there is a new question
randomQuestion = random.randint(0, last)
rounds += 1
print ("Round " + str(rounds))
print (Questions[randomQuestion])
userAnswer = input()
questionAsked = (Questions[randomQuestion])
answerRequired = (Answers[randomQuestion])
isitcorrect = False
if answerRequired.lower() == userAnswer.lower():
isitcorrect = True
if isitcorrect == True:
print("Good job! You got the correct answer of " + Answers[randomQuestion])
correct += 1
print("You have " + str(correct) + " points.")
else: print("Too bad, you got it wrong. The correct answer is " + answerRequired)
Questions.remove(questionAsked)
Answers.remove(answerRequired)
last = len(Questions)-1
playAgain()
mainObject()
print("I'm sorry, there are no more trivia questions. Your total score is " + str(correct))
print("Thanks for playing!")
You need to uncomment
rounds = 0 # at the top
and insert
global rounds
in the functions. You are incrementing rounds (local) in main, but rounds in playAgain is undefined.
There are other ways to solve the problem. But this is likely the quickest, and easiest to understand.
The variable rounds is defined in the mainobject() function, and is local to that function. It is not accessible from outside of that function.
One simple fix would be to pass rounds to the playagain() function
thus
def playagain(rounds):
...
def mainobject():
....
playagain(rounds)