I'm trying to loop this block 4 times so it displays at the end the contestant who came 1st, 2nd, 3rd and 4th. Can someone help? List - contestants
total = 0
contestants = ["Vera Lynn" , "Billy Halliday", "Frank Sinatra"]
contestant_name = input(" What's Your Name: \n " ) # Asking For The Contestants Name
print("Judges make your votes\n")
for vote in range(0, 4): # Making A Loop
judge = input("Yes Or No: ")
if judge == 'Yes':
total = total + 1
print(total)
if total >= 2:
print("Well Done ", contestant_name, " you have", total, "votes." +
" you are moving on to the next round")
else:
print("Unlucky", contestant_name, " you have", total, "votes." +
" Unfortuanely you are not moving to the next round")
Not exactly sure if this is what you are going for -- I agree with the others that this code needs to be restructured and that you should include current and expected output. That said I hope this will serve as a good starting point for you.
contestants = {"Vera Lynn": 0, "Billy Halliday": 0, "Frank Sinatra": 0}
contestants[input("What's your name?")] = 0
print("Judges make your votes\n")
for name in contestants.keys():
print("judging %s" % name)
for vote in range(0, 4):
vote = input("Yes or No: ")
if vote == "Yes":
contestants[name] += 1
if contestants[name] >= 2:
print("Well Done ", name, " you have", contestants[name], "votes." +" you are moving on to the next round")
else:
print("Unlucky", name, " you have", contestants[name], "votes." + " Unfortuanely you are not moving to the next round")
# to place and print them:
placing = sorted(contestants, key=contestants.get)
for i, val in enumerate(placing):
print("%s was number %d" % (val,i+1))
I understand this is very basic and has some problems but hopefully it will help you gain a better understanding of the basics. I recommend Learn Python The Hard Way if you want to learn more. Good luck.
Related
This question already has answers here:
How do I forward-declare a function to avoid `NameError`s for functions defined later?
(17 answers)
Closed 29 days ago.
name = input("Please enter your name: ")
is not defined on line 15. Is there a way to make this work? I tried switching this line of code:To the bottom but then it does not prompth the user if they want to play.
Is there also a way i can prompth the user what subject they want to get tested on, then it will call the function to that subject and prompth the user with questions regarding that subject.
You're accessing variables/functions that are not defined or not within the scope where they are being accessed.
You need to define the math_Questions() function before you call it, that means moving it above the while loop at the top level.
Additionally, the variables incorrect and correct are not accessed within your function as they are not within the scope of the function. You can either create new variables inside the function or declare them as global variables at the top level, the former is the more preferred approach as you should avoid global variables where possible as it reduces the modularity of your code.
Working example
def math_Questions():
incorrect = 0
correct = 0
ans1 = input("Question 1: Ron had 6 bags of flour but used up 4 bags on Sunday. How many bags of flour did he have left?: ")
if ans1 == "2":
print("\nCorrect! " + ans1 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
incorrect += 1
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
print("")
ans2 = input("Question 2: The Miller parking lot was full at the capacity of 15 this morning, now at the end of the day, 12 left the lot. How many cars are left in the parking lot?: ")
if ans2 == "3":
print("\nCorrect! " + ans2 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans3 = input("Question 3: Mrs. Sheridan has 11 cats. How many more cats does Mrs. Sheridan need to have 43 cats?: ")
if ans3 == "32":
print("\nCorrect! " + ans3 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans4 = input("Shelly bought a bed sheet for $1699. She gave the shopkeeper $2000. What amount will be returned by the shopkeeper?: ")
if ans4 == "301":
print("\nCorrect! " + ans4 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
return (correct, incorrect)
name = input("Please enter your name: ")
print("")
run = int(input("Hello " + name + ", would you like to play a game? (Enter 1 to continue, 2 to exit): "))
print("")
while run == 1:
print("I will be asking a series of questions in each categories: mathematical, scientifical. Each question getting harder.")
correct, incorrect = math_Questions()
print("correct:", correct, ", incorrect: ", incorrect)
As for prompting the user for the subjects they want to get tested on, you can just make new functions for each subject and call based on the subject the user selects:
if (subject == "chemistry"):
chem_questions()
I would also suggest storing the question and answer pairs within a dict or json object to make the code more readable and the program more modular and scalable.
Firstly, you need to properly format your code for a start. Correct indents are important in python. Each indent should be exactly 4 spaces, no more, no less. It also makes your code much easier to read.
Secondly, you should declare your methods and classes first, then your code to call those methods.
Thirdly, you need to be careful of initialising variables that then get called in the function (ie correct = 0 and incorrect = 0). This is generally bad practice. In order to work they need to be re-declared in method as global. In your case, just declare them in method ONLY. Your code should look more like:
def math_questions():
correct = 0
incorrect = 0
ans1 = input("Question 1: Ron had 6 bags of flour but used up 4 bags on Sunday. How many bags of flour did he have left?: ")
if ans1 == "2":
print("\nCorrect! " + ans1 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
incorrect += 1
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
print("")
ans2 = input("Question 2: The Miller parking lot was full at the capacity of 15 this morning, now at the end of the day, 12 left the lot. How many cars are left in the parking lot?: ")
if ans2 == "3":
print("\nCorrect! " + ans2 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans3 = input("Question 3: Mrs. Sheridan has 11 cats. How many more cats does Mrs. Sheridan need to have 43 cats?: ")
if ans3 == "32":
print("\nCorrect! " + ans3 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
ans4 = input("Shelly bought a bed sheet for $1699. She gave the shopkeeper $2000. What amount will be returned by the shopkeeper?: ")
if ans4 == "301":
print("\nCorrect! " + ans4 + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
name = input("Please enter your name: ")
print("")
run = int(input("Hello " + name + ", would you like to play a game? (Enter 1 to continue, 2 to exit): "))
print("")
while run == 1:
print("I will be asking a series of questions in each categories: mathematical, scientifical. Each question getting harder.")
math_questions()
Furthermore, I would recommend breaking down your code into smaller chunks and re-use code where possible. All your if statements have the same format and lend themselves to being put into another function or some loop. Look at:
def question_answered_correctly(new_question, correct_answer):
ans = input(new_question)
return ans == correct_answer:
def math_questions():
correct = 0
incorrect = 0
question_list = [
{
'question': "Question 1: Ron had 6 bags of flour but used up 4 bags on Sunday. How many bags of flour did he have left?: ",
'answer': '2'},
{
'question': "Question 2: The Miller parking lot was full at the capacity of 15 this morning, now at the end of the day, 12 left the lot. How many cars are left in the parking lot?: ",
'answer': '3'},
{
'question': "Question 3: Mrs. Sheridan has 11 cats. How many more cats does Mrs. Sheridan need to have 43 cats?: ",
'answer': '32'},
{
'question': "Question 4: Shelly bought a bed sheet for $1699. She gave the shopkeeper $2000. What amount will be returned by the shopkeeper?: ",
'answer': '301'}
]
for question in question_list:
if question_answered_correctly(question['question'], question['answer']):
print("\nCorrect! " + question['answer'] + " is the right answer.")
correct += 1
else:
print("\nYou are way off. Start from the very beginning, or continue with the next one.")
incorrect += 1
print("")
print('So far, you answered correctly to {0} questions and incorrectly to {1}. Keep Going!'.format(correct, incorrect))
name = input("Please enter your name: ")
print("")
run = int(input("Hello " + name + ", would you like to play a game? (Enter 1 to continue, 2 to exit): "))
print("")
while run == 1:
print("I will be asking a series of questions in each categories: mathematical, scientifical. Each question getting harder.")
math_questions()
I have been working on this project for the past 2 days and I am nearly finished but I would really like to add a working scoring system but I couldn't find any answers on google. Pls Send Help.
import random
score = 0
def main():
bet = input("Place Your Bet On A Number From 1-10 (quit to exit): ")
number = random.randint(1, 10)
if(bet == number):
global score
score+=1
print("Correct!, ", score)
print(" ")
else:
score-=1
print("Incorrect!, ", score)
print(" ")
print("Your Bet: ", bet)
print("The ACTUAL number: ", number)
print(" ")
if(bet == "quit"):
exit()
while True:
main()
I tried adding a scoring system to my game but it kept deducting points even though I was right. I searched on google but all of the answers were outdated and didn't work on my program.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I'm a newbie here so sorry if I accidentally break any rules. Basically I'm a beginner to Python and have made a piece of code for a quiz on TV Show Trivia. I wanted to ask the community here if there are any ways to tidy it up, such as unnecessary repetition etc. Also, I wanted to know if there is a way to make it so that the quiz appears in a pop up window, with a space to type in the answer. Here is the code I have so far:
print("Shall we start?")
input("Press Enter to continue...")
score = 0
Que_1 = input("Who's missing - Rachel, Ross, Chandler, Pheobe?: ")
if Que_1 == "Monica" or "monica":
print("That's right, well done!!")
score = score + 1
else:
print("I'm sorry, that's the wrong answer :( ")
score = score - 1
Que_2 = input("What is the first name of the women Leonard from The Big Bang
Theory ended up marrying?: ")
if Que_2 == "Penny" or "penny":
print("Congratulations, that was correct!!")
score = score + 1
else:
print("Incorrect")
score = score - 1
Que_3 = input("What is the full name of the actor who plays the 10th
Doctor?: ")
if Que_3 == "David Tennant" or "david tennant":
print("Oui")
score = score + 1
else:
("Non")
score = score - 1
Que_4 = input("Which sister died in Charmed?: ")
if Que_4 == "Prue" or "prue":
print("You know it")
score = score + 1
else:
print("You don't know it")
score = score - 1
Que_5 = input("Who is the main character of 13 reasons why(Full Name)?: ")
if Que_5 == "Hannah Baker" or "hannah baker":
print("Correctumondo")
score = score + 1
else:
print("Failumundo")
score = score - 1
Que_6 = input("Complete the name 'Tracy ______': ")
if Que_6 == "Beaker" or "beaker":
print("Perfect")
score = score + 1
else:
print("Not perfect")
score = score - 1
Que_7 = input("Lily, Jas and ______ : ")
if Que_7 == "Martha" or "martha":
print("On the button")
score = score + 1
else:
print("Sucks to be you")
score = score - 1
Que_8 = input("Is Missy from Ackley Bridge straight, lesbian or bisexual?:")
if Que_8 == "Straight" or "straight":
print("Right on")
score = score + 1
else:
print("Way off")
score = score - 1
Que_9 = input("From the 4 o' Clock Club, who is Josh's brother?: ")
if Que_9 == "Nathan" or "nathan":
print("Unmistaken")
score = score + 1
else:
print("Mistaken")
score = score - 1
Que_10 = input("What does Sophie from My Parents Are Aliens have to eat in
order to shapeshift? : ")
if Que_10 == "Ice cream" or "Ice Cream" or "ice cream":
print("Amen to that")
score = score + 1
else:
print("Ughhhh just no")
score = score - 1
if score == 10:
print("10 out of 10. Your a boss at this")
elif 5 <= score < 10:
print("Your score is", score, "pretty good, try to get 10 next time")
elif 1 <= score < 10:
print("Your score is", score, "Better luck next time")
Try this code (I did not include all the questions):
questions = [
"Who's missing - Rachel, Ross, Chandler, Pheobe?: ",
"What is the first name of the women Leonard from The Big Bang Theory ended up marrying?: ",
"What is the full name of the actor who plays the 10th Doctor?: ",
"Which sister died in Charmed?: "
]
answers = [
"monica",
"penny",
"david tennant",
"prue"
]
yes_nos = [
["That's right, well done!!", "I'm sorry, that's the wrong answer :( "],
["Congratulations, that was correct!!", "Incorrect"],
["Oui", "Non"],
["You know it", "You don't know it"]
]
if __name__ == '__main__':
print("Shall we start?")
input("Press Enter to continue...")
score = 0
for i, q in enumerate(questions):
ans = input(q + '\n').lower()
if ans == answers[i]:
print(yes_nos[i][0])
score += 1
else:
print(yes_nos[i][1])
print()
if score == 10:
print("10 out of 10. Your a boss at this")
elif 5 <= score < 10:
print("Your score is", score, "\nPretty good, try to get 10 next time")
elif 1 <= score < 10:
print("Your score is", score, "\nBetter luck next time")
Easygui is great for small dialog boxes:
response = easygui.enterbox("What is your favorite ice cream flavor?")
Which will pop up a window like this.
Hope this helps!
In term of optimization, you can use the method lower()
if Que_1.lower() == "monica":
That will remove the first letter as an upper case
You can also use += 1
print("That's right, well done!!")
score += 1
You will not need to do score = score + 1
And on the first Que_1, you need to set after the else with the score that equals to 0 as it is your first if.
You may need to check dictionaries and if it can help you.
And last, you can use this question to give you some insight about what you can do.
The start of my code works fine but,the bottom part consisting on the score and answer doesn't. I'm doing a school project on this and need a solution quick. But I have to be using loops! The part where i'm trying to tell the user that the answer is correct isn't working. The part where i'm revealing the right answer isn't working as well. The score isn't working as well.
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
print(qn_num[0])
print(qn_num[1])
print(qn_num[2])
print(qn_num[3])
print(qn_num[4])
print_question(qn1)
answer = input ()
answer =int(answer)
if answer == 2:
print ("good work")
score = score + 1
else:
print ("better luck next time")
score = score - 1
You can ask the answer in an infinite loop, and also show the score
print ('WELCOME TO THE MULTIPLE CHOICE TEST\n')
name = input('WHAT IS YOUR NAME? ')
print ('\nHI THERE ' + name + '! LET''S PLAY A GAME!\n')
print ('I will ask you 10 questions and give you three choices for each question.\n\nYou select which choice is the correct answer. Eg. A, B,C or D\n')
score = 0
score = int(score)
qn1 = ["What's color of sky?", "a)Red", "b)Blue", "c)White", "d)Black"]
def print_question(qn_num):
for st in qn_num:
print(st)
print_question(qn1)
allowed_answers = ["a", "b", "c", "d"]
wrong_answer = True
while(wrong_answer):
answer = input ("select answer: ")
if answer == 'b':
print ("good work")
score = score + 1
wrong_answer = False
elif answer not in allowed_answers:
print ("Bad input, you have to chose between " + ",".join(allowed_answers) )
else:
print ("better luck next time")
score = score - 1
print("Your score is: " + str(score))
This is my first Python program where I've used if, while and functions. I've also passed parameters. The problem is the IF. Can you help me? I wanted the program to give the user two tries to answer and then end. If correct then it ends but if not correct it doesn't stop, keeps looping.
"""this is a quiz on computer science"""
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()
The problem is you aren't incrementing the attempt if they get it wrong the second time. You need another attempt = attempt + 1 (Or alternatively attempt += 1) after the break
So your elif block would look like:
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
attempt = attempt + 1
This allows the attempt counter to increment even if they fail the second time, tiggering the fail and end of loop.
You just add attempt +=1 after the loops.
q1Answer="c"
def questionOne():
print("Here is a quiz to test your knowledge of computer science...")
print()
print("Question 1")
print("What type of algorithm is insertion?")
print()
print("a....searching algorithm")
print("b....decomposition ")
print("c....sorting algorithm ")
print()
def checkAnswer1(q1Answer): #q1Answer is a global variable and is needed for this function so it goes here as a parameter
attempt=0 #These are local variables
score=0
answer = input("Make your choice >>>> ")
while attempt <1:
if answer==q1Answer:
attempt= attempt+1
print("Correct!")
score =score + 2
break
elif answer != q1Answer:
answer =input("Incorrect response – 1 attempt remaining, please try again: ")
if answer ==q1Answer:
attempt = attempt + 1
print("Correct! On the second attempt")
score =score + 1
break
else:
print("That is not correct\nThe answer is "+q1Answer )
score =0
attempt += 1
break
return score # This is returned so that it can be used in other parts of the program
##def questionTwo():
## print("Question 2\nWhat is abstraction\n\na....looking for problems\nb....removing irrelevant data\nc....solving the problem\n")
def main():
q1answer = questionOne()
score = checkAnswer1(q1Answer)
print ("Your final score is ", score)
main()