How to keep on calling from a infinite list [closed] - python

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 1 year ago.
Improve this question
I am making a chart that calls people from a list called readerlist. How do I call the 1st 2nd 3rd... from an infinite list without manually writing it all out.
def isNumber(s):
try:
int(s)
return True
except ValueError:
return False
readerlist = []
booklist = []
print ("welcome to the book club system".upper())
print()
while True :
print ("\n------------------------------------")
print ("|".ljust(12) + "OPTIONS MENU".ljust(23) + "|")
print ("|".ljust(35) + "|")
print ("| 1: Modify book total".ljust(35) + "|")
print ("| 2: Displays people and books out".ljust(35) + "|")
print ("| 3: Quit".ljust(35) + "|")
print ("------------------------------------")
while True :
choice = input("\nEnter your selection: ")
if choice == "1" or choice == "2" or choice =="3":
break
print ("Invalid option")
#3 - quit
if choice == "3" :
break
#2 - display totals so far
elif choice == "2" :
print ("\n\n")
print ("".ljust(10) + "BOOKS READ".center(30))
print ("NAME".ljust(15) + "BOOKS".ljust(15))
print (readerlist[0].ljust(15) + str(booklist[0]).ljust(15))
print (readerlist[1].ljust(15) + str(booklist[1]).ljust(15))
print (readerlist[2].ljust(15) + str(booklist[2]).ljust(15))
print (readerlist[3].ljust(15) + str(booklist[3]).ljust(15))
print (readerlist[4].ljust(15) + str(booklist[4]).ljust(15))
#1 - enter a new user, or update an existing user's total
elif choice == "1":
while True:
name = input("Enter your name: ")
if name != "<Empty>":
readerlist.append(name)
break
while True:
books = (input("Enter number of books read: "))
if isNumber (books):
books = int(books)
break
else:
print("Invalid number")
print ("")
print ("Thank you for using the Library program")
input ("<Hit ENTER to exit>")

Maybe this is what you want:
elif choice == "2" :
print ("\n\n")
print ("".ljust(10) + "BOOKS READ".center(30))
print ("NAME".ljust(15) + "BOOKS".ljust(15))
for i in readerlist:
print(readerlist[i].ljust(15) + str(booklist[i]).ljust(15))

Related

"If" statement gets ignored when function is recalled [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to create a simple program which will ask the user to input an age and then will ask the user to input another age to find the difference.
The problem in my program arrives when I ask the user to confirm their age.
When I ask the user to confirm the age, if the user answers confirms their choice, I want the program to keep running. But currently, I am stuck in a cycle which even if the user inputs a confirmation, the program skips my if statement and always runs my else: statement.
#This program will prompt you to state your age and then will proceed to
#calculate how long till __ age
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" and yourWish == "yes" and yourWish == "y" and yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if desiredAge == 'yes' and desiredAge == 'Yes':
print(Yes())
else:
No()
choose()
print('Goodbye.')
There were some indentation errors and you used and keyword instead of or keyword
here is a working code
print("Hello. ")
while True:
try:
myAge = int(input("Please enter your age: ")) #int( makes func be a #
except ValueError:
print("I'm sorry, please enter your age as a numeric value.")
continue #Continue function loops back to the function making it 'continue'
else: #If it is a # then it breaks
break
#Going to ask for the second variable
print("You are " + str(myAge) + ".")
print("What is your desired age? ")
def secondV():
desiredAge = int(input())
print("You wish to be " + str(desiredAge) + "?")
yourWish = input()
desiredAge = int(input())
print("Do you wish to be " + str(desiredAge) + "?")
yourWish = input()
def choose():
if yourWish == "Yes" or yourWish == "yes" or yourWish == "y" or yourWish == "Y":
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
if yourWish == 'yes' or yourWish == 'Yes':
print("Okay... calculating")
print("To be " + str(desiredAge) + ", you would have to wait " + str(desiredAge - myAge) + " years. ")
else:
print("Erm... please input your desired age now:")
secondV()
choose()
choose()
print('Goodbye.')

(Python) ELSE is being executed even when IF has been satisfied?

Doing my homework rn and a bit stuck, why does the code execute "else" even thought the "if" has been satisfied? Ignore the sloppy code, I'm very new :/
order1 = input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ")
while order == True:
if order1 == 1:
print("You have selected to order 1: " + orderBurger)
elif order1 == 2:
print("You have selected to order 1: " + orderFries)
elif order1 == 3:
print("You have selected to order 1: " + orderDrink)
else:
print("Invalid Input")
check = input("Is this your final item?:" + "1: " + q1 + "2: " + q2 + "Answer = ")
if check == 1:
print("Your items have been added to the basket")
break
elif check == 2:
check
elif check == 3:
check
else:
print("Invalid input")
This is the output
If you use type(order1), you'll see if your answer is a string or an int. If it's a string (and I think it is), you can convert it into int using int(order1), or replace your code by if order1 == '1'
Indentation is very important in Python. Based on how the indentations are implemented, the code blocks for conditions get executed.
A misplaced indent can lead to unexpected execution of a code block.
Here is a working demo of the ordering program
# File name: order-demo.py
moreItems = True
while (moreItems == True):
order = input("\n What would you like to order?\n"
+ " 1: Burger\n 2: Fries\n 3: Drink\n Answer = ")
if ((order == "1") or (order == "2") or (order == "3")):
print("You have selected to order " + order)
print("Your item has been added to the basket.\n")
else:
print("Invalid Input")
check = input("Is this your final item?: \n 1: Yes \n 2: No \n Answer = ")
if check == "1":
print("\n Thank you. Please proceed to checkout.")
moreItems = False
elif check == "2":
print("Please continue your shopping")
else:
print("Invalid input")
Output
$ python3 order-demo.py
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 1
You have selected to order 1
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 2
Please continue your shopping
What would you like to order?
1: Burger
2: Fries
3: Drink
Answer = 2
You have selected to order 2
Your item has been added to the basket.
Is this your final item?:
1: Yes
2: No
Answer = 1
Thank you. Please proceed to checkout.
$
replace first line with this :
order1 = int( input("What would you like to order?: \n \n" + "1: " + orderBurger + "\n" + "2: " + orderFries + "\n" + "3: " + orderDrink + "\n" + "\nAnswer = ") )

How to go back to the beginning of the while loop in my quiz [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 4 years ago.
Improve this question
This is a quiz that I have made that asks users to translate arabic words in to english. When the user reaches the end of the quiz, it asks if the user would like to play again. If the user inputs the word yes then quiz should restart. I need help on making this loop restart when the user says yes.
The code is listed below:
import time
x = 0
print("Welcome to the Arabic Vocabulary Test...")
print("Loading...")
time.sleep(1)
correct = 0
import random
words = ["بىت","مسجد","باب","كتب","قلم","مفت ح","مكتب","سرير","كرسي"]
while x <9:
quest = random.choice(words)
print("What is" , quest, "?" )
words.remove(quest)
ans = input()
x = x+1
if quest == "بىت" and ans == "a house":
print("Correct")
correct = correct + 1
elif quest == "مسجد" and ans == "a mosque":
print("Correct")
correct = correct + 1
elif quest == "باب" and ans == "a door":
print("correct")
correct = correct + 1
elif quest == "كتب" and ans == "a book":
print("correct")
correct = correct + 1
elif quest == "قلم" and ans == "a pen":
print("correct")
correct = correct + 1
elif quest == "مفت ح" and ans == "a key":
print("correct")
correct = correct + 1
elif quest == "مكتب" and ans == "a table":
print("Correct")
correct = correct + 1
elif quest == "سرير" and ans == "a bed":
print("correct")
correct = correct + 1
elif quest == "كرسي" and ans == "a chair":
print("correct")
correct = correct + 1
else:
print("Incorrect")
print("You got" ,correct , "out of 9.")
print("")
print("Check your answers")
print('''a house = "بىت"
a mosque = "مسجد"
a door = "باب"
a book = "كتب"
a pen = "قلم"
a key = "مفت ح"
a table = "مكتب"
a bed = "سرير"
a chair = "كرسي"
''')
again = input("Would you like to play again?: ")
You can put your code in a function and call it inside a while loop:
def quiz():
// the quiz code here
while True:
quiz()
again = input("Would you like to play again?: ")
if again != "yes":
# If the answer is not `yes`, stop the loop
break
By the way, some comment about your quiz code :)
You can use a dictionary to put the words and their answer:
words = {
"بىت" : "a house",
"مسجد" : "a mosque",
...
}
Then, an alternative way to code quiz would be:
def quiz():
# Get the list of words
questions = words.keys()
# Shuffle the questions
random.shuffle(questions)
count = 0
for quest in questions:
ans = input()
# Check the answer in the dict
if ans == words[quest]:
count += 1
print("Correct")
else:
print("Incorrect")
print("You got", count, "out of", len(questions), ".")
print("")
print("Check your answers")
# Print the keys and values of the `words` dictionary
for word, value in words.items():
print(word, "=", value)
Hope it helps!
Include all the quiz code inside the while loop. If the user would like to play again, simply just reset your counter, "x", to 0.
temp_words = words
while x <9:
quest = random.choice(temp_words)
print("What is" , quest, "?" )
temp_words.remove(quest)
ans = input()
x = x+1
if quest == "بىت" and ans == "a house":
print("Correct")
correct = correct + 1
elif quest == "مسجد" and ans == "a mosque":
print("Correct")
correct = correct + 1
elif quest == "باب" and ans == "a door":
print("correct")
correct = correct + 1
elif quest == "كتب" and ans == "a book":
print("correct")
correct = correct + 1
elif quest == "قلم" and ans == "a pen":
print("correct")
correct = correct + 1
elif quest == "مفت ح" and ans == "a key":
print("correct")
correct = correct + 1
elif quest == "مكتب" and ans == "a table":
print("Correct")
correct = correct + 1
elif quest == "سرير" and ans == "a bed":
print("correct")
correct = correct + 1
elif quest == "كرسي" and ans == "a chair":
print("correct")
correct = correct + 1
else:
print("Incorrect")
print("You got" ,correct , "out of 9.")
print("")
print("Check your answers")
print('''a house = "بىت"
a mosque = "مسجد"
a door = "باب"
a book = "كتب"
a pen = "قلم"
a key = "مفت ح"
a table = "مكتب"
a bed = "سرير"
a chair = "كرسي"
''')
again = input("Would you like to play again?: ")
if again is 'yes':
x = 0
temp_words = words

How to store last three scores

I have been doing a school project recently which which is about a school maths quiz. I successfully done two of the three tasks of my project. However the third task is seeming quite difficult.
I'm currently trying to store the last three scores of that student. However I can't quite get it to work. I did have a look at this thread: Displaying only the highest of a person's 3 most recent scores, saved in a .txt file. However I am having an error in my code for the for:
scores = file.readlines()
Which gives me an error saying that it's not readable. So unfortunately I couldn't get that code to work.
So what I'm trying to do is score the last three scores of the student. Then if there is more then 3, then I want to delete the least recent score.
This is my code:
import random
import csv
import operator
import os.path
import sys
user_scores = {}
validclass = "No"
classfile = "Class"
studentteacher = "None"
while studentteacher == "None":
studentteacherinput = input("Are you a Teacher or a Student?")
if studentteacherinput == "Teacher":
studentteacher = "Teacher"
print(studentteacher)
elif studentteacherinput == "Student":
studentteacher = "Student"
print(studentteacher)
else:
print("Please enter the one applicable ' Student ' or ' Teacher '.")
while validclass == "No":
pupilclass = input("What class are you in or what class would you like to see??")
print(pupilclass)
if pupilclass == "1":
if os.path.exists("class1scores.txt") and studentteacher == "Teacher":
file = open("class1scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class1scores.txt") and studentteacher == "Student":
file = open("class1scores.txt", "a")
classfile = "class1scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
elif pupilclass == "2":
if os.path.exists("class2scores.txt") and studentteacher == "Teacher":
file = open("class2scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class2scores.txt") and studentteacher == "Student":
file = open("class2scores.txt", "a")
classfile = "class2scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
elif pupilclass == "3":
if os.path.exists("class3scores.txt") and studentteacher == "Teacher":
file = open("class3scores.txt", "r")
validclass = "Yes"
elif os.path.exists("class3scores.txt") and studentteacher == "Student":
file = open("class3scores.txt", "a")
classfile = "class3scores.txt"
validclass = "Yes"
else:
file = open("class1scores.txt", "w")
validclass = "Yes"
file.seek(0)
scores = file.readline()
if studentteacher == "Teacher":
teacherinput = input("How would you like to sort the list? ' Alphabetically ' to sort it alphabetically with the students highest score, ' Highest ' for the highest scores with highest to lowest or ' Average ' for average scores with highest to lowest")
if teacherinput == "Alphabetically":
print("alphabetically")
csv1 = csv.reader(file, delimiter = ",")
sort = sorted(csv1, key = operator.itemgetter(0))
for eachline in sort:
print(eachline)
sys.exit()
if teacherinput == "Highest":
print("Highest")
if teacherinput == "Average":
print("Average")
namecheck = "invalid"
while namecheck == "invalid":
name = input("Please enter your name?")
if name.isalpha():
print("Your name is valid.")
namecheck = "valid"
#file.write(name + ",")
else:
print("Please enter a valid name, only containing letters.")
operation = input("Hello %s! Would you like to do Addition, Subtraction or Multiplication" % (name))
score = 0
if operation == "Addition":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 + number2
question = input("What is " + str(number1) + " + " + str(number2))
if question.isdigit() == True:
int(question)
else:
question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
elif operation == "Subtraction":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 - number2
if number2 >= number1:
answer = number2 - number1
question = input("What is " + str(number2) + " - " + str(number1))
else:
question = input("What is " + str(number1) + " - " + str(number2))
if question.isdigit() == True:
int(question)
else:
if number2 >= number1:
answer = number2 - number1
question = input("Please enter a positive answer with digits only. What is " + str(number2) + " - " + str(number1))
else:
question = input("Please enter a positive answer with digits only. What is " + str(number1) + " - " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
elif operation == "Multiplication":
for i in range(0, 10):
number1 = random.randint(1, 20)
number2 = random.randint(1, 20)
answer = number1 * number2
question = input("What is " + str(number1) + " x " + str(number2))
if question.isdigit() == True:
int(question)
else:
question = input("Please enter a answer with digits only. What is " + str(number1) + " + " + str(number2))
if int(question) == answer:
score += 1
print("Correct!")
else:
print("Wrong!")
print("Your final score is %s/10, Well Done!" % (score))
#file.write(str(score) + "\n")
#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = [] # Initialize score list
user_scores[name].append(score) # Add the most recent score
if len(user_scores[name]) > 3:
user_scores[name].pop(0) # If we've stored more than 3, get rid of the oldest
file.close()
Sorry for the inefficient method, but it's just the way I like to think. And thanks for your time.
#This is the code which I was trying to use to get the last 3 scores.
user_scores = {}
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = [] # Initialize score list
user_scores[name].append(score) # Add the most recent score
if len(user_scores[name]) > 3:
user_scores[name].pop(0) # If we've stored more than 3, get rid of the oldest
So I took that from the link mentioned above. My aim is to try and only get three scores, and not above 3.
As you seem to know, there are different modes you can open()(2/3) a file in. If you use "a" or "w", you can't read from the file. You can add a "+", to allow reading, too, though:
open("file.txt","a+")
Also, I'm not sure what version of Python you're using, but file() is a built-in type and function in Python 2, so you shouldn't use it as a variable name if that's the version you're using.
Implement a queue - https://docs.python.org/2/library/collections.html#collections.deque
from collections import deque
for line in scores:
name, score = line.rstrip('\n').split(',')
score = int(score)
if name not in user_scores:
user_scores[name] = deque(maxlen=3)
temp_q = user_scores[name]
temp_q.append(str(score))
user_scores[name] = temp_q
Now user scores is a dict with key as name, and values as a deque object with just 3 scores. You need to iterate through them, cast the queue to list and join the elements to write them to file.
filehandle = open('outputfile.csv' ,'w')
for key, values in user_scores.iteritems():
filehandle.write(name + ',')
filehandle.write(','.join(list(values)) + '\n')
filehandle.close()

Improving Code - Python [closed]

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.

Categories