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)
Related
I'm trying to make a guessing game with three questions and three guesses total but I can't get the value from the inputs so I can't progress any further. Rough draft for my code
guesses = 3
def guess():
if guesses >= 0:
alive = True
else:
print("You Failed")
Q1 = "What is 1+1"
Q2 = ""
Q3 = ""
def retry():
input("Wrong Answer Try Again")
def questions():
Q1 = input("What is 1+1")
def answer():
if Q1 == "2":
print("Q2")
else:
retry()
if retry() == 2:
print("Q2")
questions()
answer()
I've tried using lists functions if statements but I can't get the value of the inputs no matter what as its always a local variable.
Here's a simple approach to this problem.
The crucial part is the list of 2-tuples. Each tuple maintains a question and the correct answer to that question. By adding more questions and answers to the list your program can become more elaborate without having to change anything else in the code.
Something like this:
Questions = [("What is 1+1", "2"), ("What is 2+2", "4"), ("What is 3+3", "6")]
score = 0
TRIES = 3
for q, a in Questions:
for _ in range(TRIES): # number of tries allowed
if input(f'{q}? ').lower() == a.lower() :
score += 1
print('Correct')
break
else:
print("Incorrect please try again")
else:
print('Maximum tries exceeded')
print(f'Your final score is {score}')
I'm stuck with a problem that asks 5 questions. If any of them has the answer no It should print ALIEN! or else Cool.
This is what I have got so far:
human = input("Are you human? ")
human = input("Are you living on planet Earth? ")
human = input("Do you live on land? ")
human = input("Have you eaten in the last year? ")
human = input("Is 2 + 2 = 4? ")
if human == "yes":
print("Cool")
elif human == "no":
print("ALIEN!")`
You could use any() to check if any of the answers to questions is 'no' and print message accordingly:
human = [input("Are you human? "), input("Are you living on planet Earth? "),
input("Do you live on land? "), input("Have you eaten in the last year? "), input("Is 2 + 2 = 4? ")]
if any(x.lower() == 'no' for x in human):
print('ALIEN!')
else:
print('Cool')
You have the variable human that is changed every time and given a new value using input() Try and make multiple variables instead of just using human.
human = input("Are you human? ")
var1 = input("Are you living on planet Earth? ")
var2 = input("Do you live on land? ")
var3 = input("Have you eaten in the last year? ")
var4 = input("Is 2 + 2 = 4? ")
if(human == "yes"):
print("Cool")
elif(human == "no"):
print("ALIEN!")
If you're not worried about storing the variables and only care if one of the questions comes up as "no" or "n":
x=["human?","on earth?", "on land?","someone who eats food?","sure that 2+2=4?"]
for i in x:
if input("Are you {}".format(i)).lower() in ['no','n']:
print("Alien!")
break
else:
print("Cool")
Just a side note: Here you can see a great case for using a for loop since there is code that is repeated many times. Personally, I would do the following to solve this problem.
Create a list of questions
Iterate through the list of questions
If any answer is no, break and print Alien.
Now for the code:
# Initialize our list
lst = ["Are you human? ", "Are you living on planet Earth? ","Do you live on
land? ","Have you eaten in the last year? ","Is 2 + 2 = 4? "]
#Create a flag for Alien
flag = False
#Iterate through the list
for question in lst:
answer = input(question)
if answer == 'no':
#Print alien
print('Alien')
#Change Flag
flag = True
#Break out of the loop
break
#Check to see if our flag was thrown during the loop
if flag == False:
print('cool')
If you want more help on solving coding challenges like this one, check out this intro to python course: https://exlskills.com/learn-en/courses/learn-python-essentials-for-data-science-intro_to_python/content
So, I'm quite new to python and I've been trying make a game. It goes as follows.
-Asks for name (Done)
-Returns a username made of the first two letters of each name (Done)
-Asks user to play (Issue is here)
What happens is that it rolls the dice if you pick yes but is meant to give you a simple goodbye when you say no, however when you say no it still rolls the dice and then returns the result and tell you if you've won or not.
Everything else seems to work fine, it's just where even if you type the response to the elif, the if still takes place. If anybody could take a look at this for me I'd be thankful.
from random import randint
print ("Hello, whats is your first name?")
first_name = input()
print ("What is your second name?")
second_name = input()
username = first_name[0] + first_name[1] + second_name[0] + second_name[1]
print (username + ", I want to play a game. Do you accept?")
game = input()
if game.lower() == "yes":
print ("Great, let's play. I'm going to roll a dice, if it lands on a 6, you win. If not, you lose.")
dice_roll = (randint(1,6))
print (dice_roll)
if dice_roll == 6:
print ("Congrats, you win.")
elif dice_roll != 6:
print ("Sorry. You lose.")
elif game.lower() == "no":
print ("Fine, leave then.")
I think you have an indentation issue with your code. That is why the dice is rolled even if the user typed in something different from "yes"
from random import randint
print("Hello, whats is your first name?")
first_name = input()
print("What is your second name?")
second_name = input()
username = first_name[0] + first_name[1] + second_name[0] + second_name[1]
print (username + ", I want to play a game. Do you accept?")
game = input()
if game.lower() == "yes":
print ("Great, let's play. I'm going to roll a dice, if it lands on a 6, you win. If not, you lose.")
dice_roll = (randint(1,6))
print (dice_roll)
if dice_roll == 6:
print ("Congrats, you win.")
elif dice_roll != 6:
print ("Sorry. You lose.")
elif game.lower() == "no":
print ("Fine, leave then.")
You can wrap the logic of rolling the dice inside an if statement if the user inputs yes. Otherwise, you can branch to an else statement and print goodbye.
if game.lower() == "yes":
# Roll dice here
else:
# Print out goodbye
I have researched this subject, and cannot find a relevant answer, here's my code:
#Imports#
import random
from operator import add, sub, mul
import time
from random import choice
#Random Numbers#
beg1 = random.randint(1, 10)
beg2 = random.randint(1, 10)
#Variables + Welcoming message#
correct = 0
questions = 10
print ("Welcome to the Primary School Maths quiz!!")
print ("All you have to do is answer the questions as they come up!")
time.sleep(1)
#Name#
print("Enter your first name")
Fname = input("")
print ("Is this your name?" ,Fname)
awnser = input("")
if awnser == ("yes"):
print ("Good let's begin!")
questions()
if input == ("no"):
print("Enter your first name")
Fname = input("")
print ("Good let's begin!")
#Question Code#
def questions():
for i in range(questions):
ChoiceOp = random.randint (0,2)
if ChoiceOp == "0":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1*beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "1":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1-beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
if ChoiceOp == "2":
print (("What is " +beg1 ,op ,beg2))
begAns = input("")
if int(begAns) == beg1+beg2:
print("That's right -- well done.\n")
correct = correct +1
else:
print("No, I'm afraid the answer is ",begAns)
questions()
If I'm perfectly honest I'm not quite sure what's wrong, I have had many problems with this code that this wonderful site has helped me with, but anyway this code is designed to ask 10 random addition, subtraction and multiplication questions for primary school children any help I am thankful in advance! :D
You have both a function def questions() and a variable questions = 10. This does not work in Python; each name can only refer to one thing: A variable, a function, a class, but not one of each, as it would be possible, e.g. in Java.
To fix the problem, rename either your variable to, e.g., num_questions = 10, or your function to, e.g., def ask_question()
Also note that you call your questions function before it is actually defined. Again, this works in some other languages, but not in Python. Put your def quesitons to the top and the input prompt below, or in another function, e.g. def main().
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
This code works but is not as efficent as possible. Can you tell me how to make it more efficent? I belevie there is away to not have so many functions but I have forgotten how. The script is a multi choose quiz. I have defined each question as a new function. Is this the best way to do this?
def firstq (): # 1st Question
global q1list,answer1
q1list = ["Wellington","Auckland","Motueka","Masterton"]
q1count = 0
print ("Question 1")
print ("From which of the following Towns is the suburb NEWLANDS located?")
while q1count < 4:
print (q1count," ",q1list[q1count])
q1count = q1count + 1
answer1 = int(input("What number answer do you choose?"))
if answer1 == 0: print ("Correct answer!")
elif answer1 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def secq (): #Second Question
global q2list,answer2 # Makes answer2 and q2list avalible anywhere on the page.
q2list = ["Wellington","Christchurch","Pairoa","Dunedin"] # List of answers to choose from.
q2count = 0 # defines what the q2 count is. SEE BELOW
print ("Question 2")# prints "question 2"
print ("What NZ town is known for L&P?") # Prints the question
while q2count < 4:
print (q2count," ",q2list[q2count]) # Whilst the number of answers (q2list) is below 4 it will print the next answer.
q2count = q2count + 1
answer2 = int(input("What number answer do you choose?")) # asks for answer
if answer2 == 2: print ("Correct answer!") # If answer is correct, prints "Correct answer"
elif answer2 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.") # If answer is correct, prints "Sorry! Incorrect Answer. Better luck with the next Question."
print("Next Question below:") # prints "Next Question
# these provide spacing!
print(" ")
print(" ")
def thrq ():
global q3list,answer3
q3list = ["Lewis Carroll","J.K. Rowling","Louis Carroll","Other"]
q3count = 0
print ("Question 3")
print ("Who wrote the book Alice In Wonderland?")
while q3count < 4:
print (q3count," ",q3list[q3count])
q3count = q3count + 1
answer3 = int(input("What number answer do you choose?"))
if answer3 == 0: print ("Correct answer!")
elif answer3 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fouq ():
global q4list,answer4
q4list = ["WA","DC","WD","WC"]
q4count = 0
print ("Question 4")
print ("What is the abbreviation for Washington?")
while q4count < 4:
print (q4count," ",q4list[q4count])
q4count = q4count + 1
answer4 = int(input("What number answer do you choose?"))
if answer4 == 1: print ("Correct answer!")
elif answer4 != 1: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def fivq ():
global q5list,answer5
q5list = ["Yes","No, they're found around New Zealand","No","No, they're found around the UK"]
q5count = 0
print ("Question 5")
print ("Are walruses found in the South Pole?")
while q5count < 4:
print (q5count," ",q5list[q5count])
q5count = q5count + 1
answer5 = int(input("What number answer do you choose?"))
if answer5 == 2: print ("Correct answer!")
elif answer5 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sixq ():
global q6list,answer6
q6list = ["G.M.","General M's","G Motors","Grand Motors"]
q6count = 0
print ("Question 6")
print ("What is the other name for General Motors?")
while q6count < 4:
print (q6count," ",q6list[q6count])
q6count = q6count + 1
answer6 = int(input("What number answer do you choose?"))
if answer6 == 0: print ("Correct answer!")
elif answer6 != 0: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def sevq ():
global q7list,answer7
q7list = ["Greece","USA","Egypt","Italy"]
q7count = 0
print ("Question 7")
print ("Which of the following countries were cats most honored in?")
while q7count < 4:
print (q7count," ",q7list[q7count])
q7count = q7count + 1
answer7 = int(input("What number answer do you choose?"))
if answer7 == 2: print ("Correct answer!")
elif answer7 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print("Next Question below:")
print(" ")
print(" ")
def eigq ():
global q8list,answer8
q8list = ["I find","I see","I presume","I am"]
q8count = 0
print ("Question 8")
print ("Complete this phrase-Dr. Livingstone,")
while q8count < 4:
print (q8count," ",q8list[q8count])
q8count = q8count + 1
answer8 = int(input("What number answer do you choose?"))
if answer8 == 2: print ("Correct answer!")
elif answer8 != 2: print ("Sorry! Incorrect Answer. Better luck with the next Question.")
print(" ")
print(" ")
def end():
if answer1 == 0 and answer2 == 2 and answer3 == 0 and answer4 ==1 and answer5 ==2 and answer6 ==0 and answer7 == 2 and answer8 == 2: print("YAY, all questions correct! You have won the 1 million!")
else: print("Sorry you have some incorrect questions! You have not won any money! :(") # If all answers are correct, this will display YAY, all questions correct! You have won the 1 million! If not it will print Sorry you have some incorrect questions! You have not won any money! :(.
def printorder ():
# Defines ther order that it will be printed in
firstq()
secq()
thrq()
fouq()
fivq()
sixq()
sevq()
eigq()
end()
name = l" " # while name is blank it will continue
while name != "quit": #While the name is not quit it will continue. If name is quit it will stop.
print ("The $1,000,000 Quiz! Can you win the 1 Million?")#Prints Welcome Message
name = input("Lets Get Started! What is your name: ")# asks for name
if name == "quit":
break # if the name is quit it will stop if not....
printorder()# ....prints printorder
This is just a pointer.
Instead of
def sixq():
global q6list, answer6
...
create a function
def question(qlist, qanswer):
...
and pass in qlist and qanswer as parameters, much of the code is duplicated and can be eliminated this way. And you also eliminate the use of globals at the same time. You can return whatever value(s) you need to the calling code at the end of this function using return. (note that Python allows you to return more than one value)
Adjust above as needed, ie if you need to supply another parameter etc. Essentially you want to factor out duplicate code into a single function, and provide the necessary parameters for what makes it unique.
Finally, using a single function in place of eight, will making maintaining your code much easier. If you find a problem with your code, or simply want to change something, you'll only have to correct it in one place, rather than in 8 different functions .. this is a major benefit.