How to correctly execute these functions? [duplicate] - python

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()

Related

How do i fix an indention error in my text based adventure game [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am making a text-based adventure game, however i tried running part of my program and there is an indentation error in line where there are astricks in which i cannot fix. Could someone give me some pointers. Thanks! All help will be well appreciated
Here is apart of my code:
import random
import time
randint = random.randint(1, 9)
randint2 = random.randint(1, 8)
randint3 = random.randint(1, 7)
randint4 = random.randint(1, 3)
person_name = input('What is your name? ')
print('your name is: ',person_name)
print('you have been trapped in a haunted house....You have to hurry and escape this house')
time.sleep(0.9)
roomchoice_1 = input('You are currently located in the living room. Would you like to walk to the Kitchen, bedroom, or the basement?: ')
time.sleep(1.32)
if roomchoice_1 == 'Kitchen':
print('okay you are now in the kitchen, now solve the combination lock. It will help you get out of here!')
time.sleep(1.5)
print('You have three guesses, if you get all three wrong......well....you,ll die. Good Luck!')
time.sleep(1.5)
num1 = int(input('enter your first number, from 1 - 9'))
print(' the correct number is: ' + randint)
if num1 == randint:
print('correct! You may now move on')
else:
print('oops, that wasnt the correct number. Try again. You now have 2 tries remaining')
num2 = int(input('Choose your second number, from 1 - 8'))
if num2 == randint2:
print('Congrats you have successfully found the code')
else:
print('uhhh....that wasnt the correct number either...try again.')
num3 = int(input('choose your third and final number between 1 and 7'))
print('the correct number is', randint3)
if num3 == randint3:
print('well done ,success, you have opened the combination lock... You have obtained a key')
L_1 = input(' Now would you like to travel to the bedroom or basement')
if L_1 == 'Bedroom':
#insert bedroom code
***else:***
print('Oh NO!, you have guessed incorrectly three times....')
print(pass)# insert in print statement a code photo of a hole
print(person_name, ' has died')
print(pass)# insert text image of skull
if roomchoice_1 == 'bedroom':
print('You have walked into the bedroom.....')
time.sleep(1)
print('LOOK... there are three doors... You have to choose the correct one...carefull! You only have one chance')
choice_door = int(input('Choose one of the following doors: Door 1, Door 2, or Door 3'))
if choice_door = randint4:
print('Good Job... You have chosen the right door....')
time.sleep(1)
print('look behind the door... there is a chest...try open it...')
open_chest = input('Would you like to open the chest')
if open_chest == 'yes':
print('Look... there is another key... this might be the key that opens the from')
So it is highly recommended to ident your code with 'TAB' to avoid those mistakes, so if you have any thing inside you 'if' statement it should be with one TAB and so one. Always use the TAB to ident. So based on that, here it is.
import random
import time
randint = random.randint(1, 9)
randint2 = random.randint(1, 8)
randint3 = random.randint(1, 7)
randint4 = random.randint(1, 3)
person_name = input('What is your name? ')
print('your name is: ',person_name)
print('you have been trapped in a haunted house....You have to hurry and escape this house')
time.sleep(0.9)
roomchoice_1 = input('You are currently located in the living room. Would you like to walk to the Kitchen, bedroom, or the basement?: ')
time.sleep(1.32)
if roomchoice_1 == 'Kitchen':
print('okay you are now in the kitchen, now solve the combination lock. It will help you get out of here!')
time.sleep(1.5)
print('You have three guesses, if you get all three wrong......well....you,ll die. Good Luck!')
time.sleep(1.5)
num1 = int(input('enter your first number, from 1 - 9'))
print(' the correct number is: ' + randint)
if num1 == randint:
print('correct! You may now move on')
else:
print('oops, that wasnt the correct number. Try again. You now have 2 tries remaining')
num2 = int(input('Choose your second number, from 1 - 8'))
if num2 == randint2:
print('Congrats you have successfully found the code')
else:
print('uhhh....that wasnt the correct number either...try again.')
num3 = int(input('choose your third and final number between 1 and 7'))
print('the correct number is', randint3)
if (num3 == randint3):
print('well done ,success, you have opened the combination lock... You have obtained a key')
L_1 = input(' Now would you like to travel to the bedroom or basement')
if (L_1 == 'Bedroom'):
pass #insert bedroom code
else:
print('Oh NO!, you have guessed incorrectly three times....')
#print(pass) # insert in print statement a code photo of a hole
print(person_name, ' has died')
#print(pass)# insert text image of skull
if roomchoice_1 == 'bedroom':
print('You have walked into the bedroom.....')
time.sleep(1)
print('LOOK... there are three doors... You have to choose the correct one...carefull! You only have one chance')
choice_door = int(input('Choose one of the following doors: Door 1, Door 2, or Door 3'))
if choice_door == randint4:
print('Good Job... You have chosen the right door....')
time.sleep(1)
print('look behind the door... there is a chest...try open it...')
open_chest = input('Would you like to open the chest')
if open_chest == 'yes':
print('Look... there is another key... this might be the key that opens the from')

Relatively new to python and I'm trying to program a quiz that ask the user for multiple inputs and checks them with the dictionary of answers

I understand I need another for loop or while loop in order to run through the lists inside answer_inputs but I am have trouble with it. I understand that this is sort of a short answers test but there only a few answers possible per question.
questions = ["What are the three elements of a firing team?",
"What command level does a FiST belong to and what are its elements?",
"What Command level does a FSCC belong to and what are its elements?",
"What are the Fire Support Planning Phases?",
"What are the two general types of targets?"]
answer_inputs = [{"1.","\n2.","\n3.\n"},
{"Level:","\n1.","\n2.","\n3.","\n4.","\n5.\n"},
{"Level:","\n1.","\n2.","\n3.","\n4.","\n5.\n"},
{"1.\n2.\n3.\n"},
{"1.\n2.\n"}]
one = "observer" or "FDC" or "Howitzer" or "M777" or "155mm"
two = "Company FiST Leader" or "Forward Air Controller" or "FAC" or "Fire Support officer" or "Artillery FO" or "81mm Mortar Observer (FO)" or "Naval Gun-fire spotter team"
three = "Fire Support Coordinator" or "Tactical Air control Party" or "TACP" or "Liaison section" or "81mm mortar section" or "Shore Fire control Party"
four = "preperatory" or "conduct" or "consolidation"
five = "linear" or "point"
correct_choices = [{one,one,one},
{"Company", two, two, two, two, two},
{"Battalion", three, three, three, three, three},
{four, four, four},
{"linear" or "point","linear" or "point"}]
answers = ["Observer\nFDC\nHowitzer or M777 or 155mm",
"Level:Company\n1.Company FiST Leader\n2.Forward Air Controller (FAC)\n3.Fire Support officer (artillery FO)\n4.81mm Mortar Observer (FO)\n5.Naval Gun-fire spotter team\n:",
"Level:Battalion\n1.Fire Support Coordinator\n2.\n3.\n4.\n5.\n:",
"preperatory, conduct and consolidation",
"linear and point"]
def quiz():
score = 0
for question, choices, correct_choice, answer in zip(questions, answer_inputs, correct_choices, answers):
print(question)
user_answer = input(choices).lower().rstrip("s")
if user_answer in correct_choices:
print("Correct")
score += 1
else:
print("Incorrect",print("_"*10), answer)
print(score, "out of", len(questions), "that is", float(score / len(questions)) * 100, "%")
if __name__ == "__main__":
quiz()
Sample Multiple choice quiz.
import random
class QA:
def __init__(self, question, correctAnswer, otherAnswers):
self.question = question
self.corrAnsw = correctAnswer
self.otherAnsw = otherAnswers
qaList = [QA("Where is Minsk?", "in Belarus", ["in Russia", "such a city doesn't exist"]),
QA("What is the capital of Australia?", "Canberra", ["Sydney", "New York", "Australia doesn't exist"]),
QA("Which of the following is not on Earth?", "Sea of Tranquility",
["Mediterranean Sea", "Baltic Sea", "North Sea"]),
QA("Which of the following is not a continent?", "Arctica", ["Antarctica", "America"]),
QA("Which of the following is not an African country?", "Malaysia",
["Madagascar", "Djibouti", "South Africa", "Zimbabwe"])]
corrCount = 0
random.shuffle(qaList)
for qaItem in qaList:
print(qaItem.question)
print("Possible answers are:")
possible = qaItem.otherAnsw + [
qaItem.corrAnsw] # square brackets turn correct answer into list for concatenating with other list
random.shuffle(possible)
count = 0 # list indexes start at 0 in python
while count < len(possible):
print(str(count + 1) + ": " + possible[count])
count += 1
print("Please enter the number of your answer:")
userAnsw = input()
while not userAnsw.isdigit():
print("That was not a number. Please enter the number of your answer:")
userAnsw = input()
userAnsw = int(userAnsw)
while not (userAnsw > 0 and userAnsw <= len(possible)):
print("That number doesn't correspond to any answer. Please enter the number of your answer:")
userAnsw = input()
if possible[userAnsw - 1] == qaItem.corrAnsw:
print("Your answer was correct.")
corrCount += 1
else:
print("Your answer was wrong.")
print("Correct answer was: " + qaItem.corrAnsw)
print("")
print("You answered " + str(corrCount) + " of " + str(len(qaList)) + " questions correctly.")
Here is a quick solution i cobbled up for multiple correct answers. Quiz generation part can be skipped if you really want to hardcode but i recommend that you store your questions in a file like txt or json to be read later instead.
import random
questions = []
answers = []
options = []
# questions and answers generation
while True:
question = str(input("Enter a question: (type done to finish) "))
if question == "done":
break
questions.append(question)
answer = ""
nested_answers = []
while True:
answer = str(input("Enter a correct answer: (type done to finish) "))
if answer == "done":
answers.append(nested_answers)
break
nested_answers.append(answer)
nested_options = []
while True:
option = str(input("Enter a (wrong) option: (type done to finish) "))
if option == "done":
options.append(nested_options)
break
nested_options.append(option)
score = 0
for i in range(len(questions)):
question = questions[i]
print("\nQuestion " + str(i + 1) + ": " + question)
combined_options = options[i] + answers[i]
random.shuffle(combined_options)
print("Options")
for count, item in enumerate(combined_options, 1):
print(str(count) + ": " + item)
user_answer = int(input("Enter your answer (number): "))
user_choice = combined_options[user_answer - 1]
if user_choice in answers[i]:
print("Correct")
score += 1
else:
print("Wrong :(")
print("Final score: " + str(score))
Sample run:
Enter a question: (type done to finish) which of these are fruits
Enter a correct answer: (type done to finish) apple
Enter a correct answer: (type done to finish) pear
Enter a correct answer: (type done to finish) orange
Enter a correct answer: (type done to finish) done
Enter a (wrong) option: (type done to finish) lettuce
Enter a (wrong) option: (type done to finish) broccoli
Enter a (wrong) option: (type done to finish) done
Enter a question: (type done to finish) which of these are vegetables
Enter a correct answer: (type done to finish) lettuce
Enter a correct answer: (type done to finish) cabbage
Enter a correct answer: (type done to finish) done
Enter a (wrong) option: (type done to finish) cat
Enter a (wrong) option: (type done to finish) done
Enter a question: (type done to finish) done
Question 1: which of these are fruits
Options
1: apple
2: lettuce
3: broccoli
4: pear
5: orange
Enter your answer (number): 1
Correct
Question 2: which of these are vegetables
Options 1: cat
2: cabbage
3: lettuce
Enter your answer (number): 2
Correct
Final score: 2

How can i add or fix my program so it loops to the start

I need to add a loop to my program somewhere where can I add it in\
def start():
#introduction
print("Here is a quiz to test your knowledge of Pixar")
print("please enter the lower letter of the answer or it will not work")
person = input("Enter you Name: ")
points = -50
#Q1 ask a question
print("What year was toy story released")
answer = input("A. 1995 B. 2002 C.1999 = ")
# a is answer
if answer == "a":
print ("Your Right")
points += 11.1
else:
print ("you need to get better")
print ("the correct answer 1995 was ")
#Q10
print("What was the name of the bad guy in up")
answer = input("A. Kevin Wilson B. Charles Muntz C. Mike whiting = ")
if answer == "b":
print("that’s a righta")
points += 78.45
points += 0.25
else:
print("not quite")
print("the correct answer was Charles Muntz")
print("Well done" , person)
print("Your final score is {}".format(points))
print("you are the best" , person)
print("I Know" , person)
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
I want to add the loop so when you finish you go back to the start but I don't know how to do that could someone help me.
Consider using a While loop. Specifically, just inserting all your code as follows should do the job:
**While True:**
.....
.....
I have not run your code, but I think a break statement would be needed for your final "if" statement (in order to not run endlessly), specifically:
if op.lower() in {'q', 'quit', 'e', 'exit'}:
print("Goodbye!")
break
Apart from those edits, I think that all the inputting and whatnot should be fine.

Need quiz scoring function

I have to create a basic 3 question quiz on farming. It needs to ask the 3 questions, output whether you got it correct or incorrect and if you got it incorrect you can try again. It also needs to have a score function. I have completed the questions and the incorrect/correct part of the specification but no matter what I try I cannot get the score function to work. I have tried:
score = 0
def counter(score)
score = score + 1
def counter(score)
score = 0
score = score + 1
def counter(score)
global score
score = 0
score = score + 1
and then following that once the answer was correct the line read :
counter(score)
I have also tried
score = 0
then
score = score + 1
but nothing is working and I cannot figure out what is going wrong. It also needs to print how many the user got right at the end.
CODE:
score = 0
def quiz():
print("Here is a quiz to test your knowledge of farming...")
print()
print()
print("Question 1")
print("What percentage of the land is used for farming?")
print()
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make your choice: ")
if answer == "c":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer = input("Try again! ")
if answer == "c":
print("Correct")
score = score + 1
else:
print("Incorrect! Sorry the answer was C.")
print()
print()
print("Question 2")
print("Roughly how much did farming contribute to the UK economy in 2014.")
print()
print("a. £8 Billion.")
print("b. £10 Billion.")
print("c. £12 Billion.")
answer = input("Make your choice: ")
if answer == "b":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer = input("Try again! ")
if answer == "b":
print("Ccrrect!")
score = score + 1
else:
print("Incorrect! Sorry the answer was B.")
print()
print()
print("Question 3.")
print("This device, which was invented in 1882 has revolutionised farming. What is it called?")
print()
print("a. Tractor")
print("b. Wagon.")
print("c. Combine.")
answer == input("Make your choice. ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect.")
answer == input("Try again! ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect! Sorry the answer was A.")
print("You got {0}/3 right!".format(score))
A n00b (and working) way would be to do something like
score = 0
def quiz():
global score
The global keyword makes use of the global variable (which you declared outside your function quiz). Since you've not indented your code properly it's unclear if you're printing the last statement inside or outside the quiz function, but that doesn't matter. If you place both score and printing inside the quiz function or both outside you'll be fine. Good luck with homework!
So python scope is defined by indents (as mentioned by the comment above). So any statement that creates a layer of scope is seperated by an indent. Examples include classes, functions, loops, and boolean statements. Here is an example of this.
Class A:
def __init__(self, msg):
self.message = msg
def print_msg(self): # prints your message
print self.message
def is_hi(self):
if self.message == "hi":
return true
else:
return false
This shows the different layers of scope that can exist.
Your code is not working right now because you are defining a function and then putting nothing in its scope. You would have to put anything within the scope of the function for that error to go away but that is probably not what you are looking for.
Operators in any programming language are your bread and butter for transforming data from one state to another or for comparing data. We have three types: Arithmetic operators, Relational operators and Logical operators. It is crucial you understand them well and I would advise you to visit https://www.geeksforgeeks.org/basic-operators-python/ for reference. I can see from your answer above that there is some confusion between the assignment operator and the comparison operator:
This is the comparison operator:
answer == input("Make your choice. ")
What you expect to happen is that an input is read from the keyboard and set into the answer variable, but what's actually happening is your testing for a conditional comparison, in this case between an empty variable (called answer) and a python built-in function. What will happen is python will silently return a boolean describing the outcome of the conditional statement but will never set your variable to the new value because you didn't use the assignment operator.
This is the assignment operator:
answer = input("Make your choice. ")
A single equal symbol can make a big difference!
Now your code will correctly set the value a user types from their keyboard into the answer variable thanks to the power of the assignment operator.
I've refactored your code below to demonstrate the difference between assignment and comparison operations. I've also demonstrated using the newline character (\n) to create spaces between your text blocks.
import sys
def quiz():
score = 0
print("Here is a quiz to test your knowledge of farming...\n\n")
print("Question 1")
print("What percentage of the land is used for farming?")
print("a. 25%")
print("b. 50%")
print("c. 75%")
answer = input("Make your choice: ")
if answer == "c":
print("Correct!\n\n")
score = score + 1
else:
print("Incorrect! Sorry the answer was C.\n\n")
print("Question 2")
print("Roughly how much did farming contribute to the UK economy in 2014.\n")
print("a. £8 Billion.")
print("b. £10 Billion.")
print("c. £12 Billion.")
answer = input("Make your choice: ")
if answer == "b":
print("Correct!\n\n")
score = score + 1
else:
print("Incorrect! Sorry the answer was B.\n\n")
print("Question 3.")
print("This device, which was invented in 1882 has revolutionised farming. What is it called?\n")
print("a. Tractor")
print("b. Wagon.")
print("c. Combine.")
answer = input("Make your choice: ")
if answer == "a":
print("Correct!")
score = score + 1
else:
print("Incorrect! Sorry the answer was A.")
print("You got {}/3 right!".format(score))
if __name__ == "__main__":
quiz()

Loop something 4 times in Python

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.

Categories

Resources