Improving Code - Python [closed] - python

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.

Related

Why is my Python code ignoring my if-statement and not quitting when I add the answer "no"?

print("Welcome to my quiz page!")
playing = input("Do you want to play? ")
if playing.lower() == "yes": #when people answer no here, the quiz should stop but it doesn't. why?
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
When I answer "no" it still let me carry on playing the quiz instead of quitting. How can I stop it running when people answer no instead of yes?
The quiz does not stop because you have not included any code to stop the quiz when the user enters "no". To fix this, you can add an else statement after the if statement that checks if the user wants to play. The else statement should contain a break statement to exit the loop.
Here How you can do so:
print("Welcome to my quiz page!")
while True:
playing = input("Do you want to play? ")
if playing.lower() == "yes" or playing.lower() == "y":
print("Let's play! ")
score = 0
answer = input("What is the capital of Japan? ")
if answer.lower() == "tokyo":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What is a female Japansese dress called? ")
if answer.lower() == "kimono":
print("Correct!")
score += 1
else:
print("Incorrect!")
answer = input("What are Japanese gang members called? ")
if answer.lower() == "yakuza":
print("Correct!")
score += 1
else:
print("Incorrect!")
print("You've got " + str(score) + " questions correct!")
print("You've got " + str((score / 3) * 100) + "%,")
else:
break
You can make this more manageable by constructing a list of questions and answers rather than writing discrete blocks of code for each.
You need to be asking the user if they want to answer questions (or not).
So...
Q_and_A = [
('What is the capital of Japan', 'Tokyo'),
('What is a female Japansese dress called', 'kimono'),
('What are Japanese gang members called', 'yakuza')
]
score = 0
for q, a in Q_and_A:
if input('Would you like to try to answer a question? ').lower() in {'n', 'no'}:
break
if input(f'{q}? ').lower() == a.lower():
print('Correct')
score += 1
else:
print('Incorrect')
print(f'Your total score is {score} out of a possible {len(Q_and_A)}')
Thus if you want to add more questions and answers you just change the list of tuples. The rest of the code doesn't need to be changed

Python, code doing the first thing then looping to the end

I am making a small quiz and trying to learn python. The quiz takes the first answer then loops all the way to the bottom instead of asking the user the rest of the questions. It will print the first question, then ask for the answer , then it will run throught the rest of the code but it won't actually ask for the input or anything like that.
question_1 = ("ex1")
question_2 = ("ex2")
question_3 = ("ex3")
question_4 = ("ex4")
answer = input ("Please type the letter you think is correct: ")
count = 0
# answers
print (question_1)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "b" or answer == "B":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_2)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "a" or answer == "A":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_3)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "d" or answer == "D":
print ("Correct")
count +=1
else:
print ("Incorrect")
print (question_4)
print ("A. ")
print ("B. ")
print ("C. ")
print ("D. ")
if answer == "c" or answer == "C":
print ("Correct")
count +=1
else:
print ("Incorrect")
You are only asking for one input and then checking that answer against every question.
You will need to add a new input for every question and then check against that input
e.g.
count = 0
print('Q1')
ans1 = input('A/B/C?')
if ans1.lower() == 'c': # Checks for it as a lowercase so no need to repeat it
print('Correct')
count += 1
else:
print('Incorrect')
print('Q2')
ans2 = input('A/B/C?')
if ans2.lower() == 'b':
print('Correct')
count += 1
else:
print('Incorrect')
You need to have the input() function after each question. An input is asked for at each input, writing it once before all the questions won't work.
By the way, you might want to use lists and a loop to get the same done with less code.

make a random quiz with list in python

def ask_questions():
choice = (random.choice(question))
print(choice)
if choice == 0:
print options[0]
answer0 = raw_input(inputs)
if answer0 == answers[0]:
print("correct")
else:
print("incorrect")
elif choice == 1:
print choice
print options[1]
answer1 = raw_input(inputs)
if answer1 == answers[1]:
print("correct")
else:
print("incorrect")
elif choice == 2:
print choice
print options[2]
answer2 = raw_input(inputs)
if answer2 == answers[2]:
print("correct")
else:
print("incorrect")
elif choice == 3:
print choice
print options[3]
answer3 = raw_input(inputs)
if answer3 == answers[3]:
print("correct")
else:
print("incorrect")
elif choice == 4:
print choice
print options[4]
answer4 = raw_input(inputs)
if answer4 == answers[4]:
print("correct")
else:
print("incorrect")
elif choice == 5:
print choice
print options[5]
answer5 = raw_input(inputs)
if answer5 == answers[5]:
print("correct")
else:
print("incorrect")
def main()
date()
quiz_infos()
welcome()
ask_questions()
main()
I Would like to make a random chose of questions from list
i would like to know a way to make a random choice of the questions from the list and if that question is 1: to print the option 1 and my raw_input(inputs) same goes for question 2 3 4 etc
idk why my code dose not actually do that and prints just the question, so if elif functions dose not work!
im new to python(new in coding) so i might be doing something wrong for sure,
ny the way by variable[[[[ inputs = "What do you think the answer is?"]]]]
Thanks in regard!
the code is written in python 2.7 idle
There are simpler ways to do this, but here is your exact code modified for python 3 syntax with appropriate indentation (that works if the lists "question", "options" and "answers" as well as the constant "inputs" are all actually defined and not empty).
def ask_questions():
choice = (random.choice(question))
if choice == 0:
print(choice)
print(options[0])
answer0 = input(inputs)
if answer0 == answers[0]:
print("correct")
else:
print("incorrect")
elif choice == 1:
print(choice)
print(options[1])
answer1 = input(inputs)
if answer1 == answers[1]:
print("correct")
else:
print("incorrect")
etc...
C:\Users\me\Documents>python test.py
0
Question 1
User Input: Answer 1
correct
C:\Users\me\Documents>python test.py
4
Question 5
User Input: Answer 5
correct
As I said above, you have indentation errors in what you pasted in your submission if not also in your code. If your code hangs after printing the question, I suspect your "inputs" may be an empty string.
I personally would make each question:answer in a dictionary
Questions = {"What is your favorite Color?":"Blue","How many cats do I own?": "2"}
then you could return a random selection from the list using the KEYS method
import random
Questions = {"What is your favorite Color?":"Blue","How many cats do I own?": "2"}
random.choice(Questions.keys())
You can look here for dictionary information: Dictionary
and also here for the random module Random
Avoid adding a block of code for each question & answer by iterating the conditional statement through a single randomized list of lists.
Randomize the list of lists using .shuffle() method. The order inside the nested lists won't change, so for example L[0][0] is the question and L[0][1] is the answer of the first element of the randomized list.
Make the input case-insensitive with .lower() method.
Optional: add a count of right and wrong answers.
import random
L = [["Who is Batman's sidekick ?: ", "Robin"], ["Which is the capital of North Ireland ?: ", "Belfast"], ["What do caterpillars turn into ?: ", "Butterflies"]]
random.shuffle(L)
r = 0 # right answers count
w = 0 # wrong answers count
for i in range(0, len(L), 1):
user_input = input(L[i][0])
if user_input.lower() == L[i][1].lower():
print("That's right !")
r = r + 1
else:
print("Wrong answer")
w = w + 1
print(str(r) + " right and " + str(w) + " wrong answers")

want to print answer if q is answered incorrectly, and give two more chances

So I have an assessment due tomorrow (it is all finished) and was hoping to add a few more details in.
How would I:
a. Make it so that if you answer the question wrong, you can retry twice
b. if you completely fail, you get shown the answer
How would i do this? thanks
ps. The code lloks retarded, i couldn't get it in
} output = " " score = 0 print('Hello, and welcome to my quiz on Ed Sheeran!') for question_number,question in enumerate(questions): print ("Question",question_number+1)
print (question)
for options in questions[question][:-1]:
print (options)
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
print (score)
print (output)
else:
print ("Wrong!")
print (score)
print (output)
print(score)
What I have understood from your query is that you want user to input the option twice before we move to the next question.
Also you want to display the answer if the user has incorrectly answered in both the chances.
I don't know how your questions and answers are stored but you can use the below code as a pseudo code.
The below code should work:
print('Hello, and welcome to my quiz on Ed Sheeran!')
for question_number,question in enumerate(questions):
print ("Question",question_number+1)
print (question)
tmp = 0
for options in questions[question][:-1]:
print (options)
for j in range(2):
user_choice = input("Make your choice : ")
if user_choice == questions[question][-1]:
print ("Correct!")
score += 1
break
else:
print ("Wrong!")
tmp += 1
if tmp == 2:
print ('You got it wrong, Correct answer is: ' output)
print(score)

How to ask a string again if the wrong answer is entered?

I'm trying to get a string to keep repeating if the answer is wrong. How would I go about doing this? The code I have is below which works but doesn't repeat the answer.
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
if answer is '4':
print("Great job!")
elif answer != '4':
print ("Nope! please try again.")
while answer != '4':
print ("What is 2 + 2?")
break
There are a couple of things wrong with your code. Firstly, you are only asking for the answer once at the moment. You need to put answer = input() in a while loop. Secondly, you need to use == instead of is:
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = 0
while answer != '4':
answer = input()
if answer == '4':
print("Great job!")
else:
print ("Nope! please try again.")
There are a number of ways you can arrange this code. This is just one of them
print('Guess 2 + 2: ')
answer = int(input())
while answer != 4:
print('try again')
answer = int(input())
print('congrats!')
I think this is the simplest solution.
By now you've got more answers than you can handle, but here are another couple of subtleties, with notes:
while True: # loop indefinitely until we hit a break...
answer = input('What is 2 + 2 ? ') # ...which allows this line of code to be written just once (the DRY principle of programming: Don't Repeat Yourself)
try:
answer = float(answer) # let's convert to float rather than int so that both '4' and '4.0' are valid answers
except: # we hit this if the user entered some garbage that cannot be interpreted as a number...
pass # ...but don't worry: answer will remain as a string, so it will fail the test on the next line and be considered wrong like anything else
if answer == 4.0:
print("Correct!")
break # this is the only way out of the loop
print("Wrong! Try again...")
You only need the wrong-answer check as loop condition and then output the "great job" message when the loop is over (no if is needed):
print("Hello there, what is your name?")
MyName = input()
print ("Nice to meet you " + MyName)
print ("What is 2 + 2?")
answer = input()
while answer != '4':
print ("Nope! please try again.")
print ("What is 2 + 2?")
answer = input()
print("Great job!")
Here is my two cents for python2 :
#!/usr/bin/env python
MyName = raw_input("Hello there, what is your name ? ")
print("Nice to meet you " + MyName)
answer = raw_input('What is 2 + 2 ? ')
while answer != '4':
print("Nope ! Please try again")
answer = raw_input('What is 2 + 2 ? ')
print("Great job !")

Categories