This question already has answers here:
How do I sort a dictionary by value?
(34 answers)
Closed 6 years ago.
I am trying to sort a dictionary, "Highest" and "Average" from highest to lowest, but I can not get the dictionary to sort from the text file. I am not sure if I should be using an array instead or if there is a way around it?
This is my code:
import random
score = 0
print("Hello and welcome to the maths quiz!")
while True:
position = input("Are you a pupil or a teacher?: ").lower()
if position not in ("teacher","pupil"):
print ("Please enter 'teacher' or 'pupil'!")
continue
else:
break
if position == 'pupil':
your_name = ""
while your_name == "":
your_name = input("Please enter your name:") # asks the user for their name and then stores it in the variable name
class_no = ""
while class_no not in ["1", "2", "3"]:
class_no = input("Please enter your class - 1, 2 or 3:") # Asks the user for an input
score = 0
for _ in range(10):
number1 = random.randint(1, 11)
number2 = random.randint(1, 11)
operator = random.choice("*-+")
question = ("{0} {1} {2}".format(number1,operator,number2))
solution = eval(question)
answer = input(question+" = ")
if answer == str(solution):
score += 1
print("Correct! Your score is, ", score , )
else:
print("Your answer is not correct")
class_no = ("Class " + class_no + ".txt")
print("Congratulations {0}, you have finished your ten questions!".format(your_name))
if score > 5:
print("Your total score is {0} which is over half.".format(score))
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(your_name, score))
with open(class_no, "a") as Student_Class:
Student_Class.write(your_name)
Student_Class.write(",")
Student_Class.write(str(score))
Student_Class.write("\n")
else:
while True:
Group = input("Which class would you like to view first? 1, 2 or 3?: ")
if Group not in ("1", "2", "3"):
print ("That's not a class!")
continue
else:
break
Group = ("Class " + Group + ".txt")
while True:
teacherAction = input("How would you like to sort the results? 'alphabetical', 'highest' or 'average'?: ").lower() # Asks the user how they would like to sort the data. Converts answer into lower case to compare easily.
if teacherAction not in ("alphabetical","highest","average"):
print ("Make sure you only input one of the three choices!")
continue
else:
break
with open (Group, "r+") as scores:
PupilAnswer = {}
for line in scores:
column = line.rstrip('\n').split(',')
name = column[0]
score = column[1]
score = int(score)
if name not in PupilAnswer:
PupilAnswer[name] = []
PupilAnswer[name].append(score)
if len(PupilAnswer[name]) > 3:
PupilAnswer[name].pop(0)
if teacherAction == 'alphabetical':
for key in sorted(PupilAnswer):
print(key, PupilAnswer[key])
elif teacherAction == 'highest':
highest = {}
for key, value in PupilAnswer.items():
maximum = max(value)
highest[key] = maximum
for key in sorted(highest, key=highest.get, reverse=True):
print (key, highest[key])
else:
for name in sorted(PupilAnswer):
average = []
for key in (PupilAnswer[name]):
average.append(key)
length = len(average)
total = 0
for key in (average):
total = total + (key)
totalAverage = (total)/length
print (name, totalAverage)
print ("Thank you for using the quiz!")
input("Press 'enter' to exit!")
There is no "sorted" in dictionaries. They are a set of key-value items. Un-ordered.
You can use an OrderedDict.
Related
I want to add a scoring system on my code.
Every time that the player gets a correct answer, a 5 point score will be added to the player's overall score. This is my code below:
def easyLevel():
n = 2
while n <= 7:
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern + " " + random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
easyAns = str(input("What was the pattern?: "))
if easyAns == pattern:
n = n + 1
print("That's correct!")
else:
print("Sorry, that's incorrect.")
break
How can I save the scores in a file? Along with the last pattern that the player answered correctly.
Also, is there a way I could print the pattern and score outside of this function? if so, how can I do that?
Would appreciate your help. Thank you!
What if you use a global variable to store the score?
import random
import string
score = 0 # set the global variable score to 0
def easyLevel():
global score #this tells python that when we assign to score in this function, we want to change the global one, not the local one
n = 2
while n <= 7:
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern + " " + random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
easyAns = str(input("What was the pattern?: "))
if easyAns == pattern:
n = n + 1
print("That's correct!")
score = score + 5 # so when we change score in here, it changes the global variable score
else:
print("Sorry, that's incorrect.")
break
An alternative would be to use the score as a local variable, and return it when done. This would however not negate the need for a global score variable in some capacity.
Here's some more info from Stack:
Using global variables in a function
Happy coding!
add a variable to storing the score, then after the loop, save the last pattern and the score to a csv file
import random
import string
import csv
def easyLevel():
n = 2
score = 0
last_pattern = None
# start game
while n <= 7:
# make new pattern
pattern = random.choice(string.ascii_lowercase)
for i in range(n-1):
pattern = pattern + " " + random.choice(string.ascii_lowercase)
print("The pattern is: ")
print(pattern)
# get input
easyAns = input("What was the pattern?: ")
if easyAns == pattern:
n += 1
score += 5
print("That's correct!")
# update last pattern
last_pattern = pattern
else:
print("Sorry, that's incorrect.")
break
return last_pattern, score
game = easyLevel() # returns last_pattern and score
last_pattern, score = game
# show result
print("Last pattern :", last_pattern, ", Score :", score)
# save score and last pattern in file
with open('data.csv', 'a') as file:
csv_wrtier = csv.writer(file)
csv_wrtier.writerow([last_pattern, score])
I am looking to ask the user to pick from the items list. I figured I could ask the user a designated amount of questions ("Enter your Items: ") and add all of the questions up (like q1, q2, q3, etc.).
But I would rather allow the user to pick an indefinite amount of items until they hit Enter and break the loop. THEN add all of the prices from their entry, as long as it matches the fmPrices dict.
import math
dollar = "$"
items = ["Eggs","Milk","Chips","Butter","Grapes","Salsa","Beer"]
items.sort()
choice = ("Choose from the following items:")
print (choice)
print (items)
fmPrices = {
"Eggs" : 2.99,
"Milk": 3.99,
"Chips": 4.29,
"Butter": 3.29,
"Grapes": 3.49,
"Salsa": 40.99,
"Beer": 1.99
}
while True:
q1 = input("Enter your item: ")
if q1 == '':
break
else:
input("Enter your item: ")
print ("Your estimated cost is: ")
total = round(fmPrices[q1],2)
print ("{}""{}" .format(dollar, total))
mylist = []
total = 0
while True:
q1 = input("Enter your item: ")
if q1 == '':
break
if q1 not in fmPrices:
print("Item is not in the list")
else:
mylist.append(q1)
total += fmPrices[q1]
print ("Your estimated cost is: ")
print( "$", round(total,2) )
For example
cost = 0
while True:
q1 = input("Enter your item: ")
if q1 == '':
break
price = fmPrices.get(q1)
if price == None:
print("Item not available")
else:
cost += price
total = round(cost,2)
print(f"Your estimated cost is: {dollar}{total}")
from random import*
from time import*
print("1. Addition \n2. Subtraction \n3. Multiplication \n4. Division")
count = int(input("How many question do you want? : "))
question = input("What kind of questions do you want? (Type 1/2/3/4) :")
mark = 0
if question == "1":
for x in range(count) :
a = randint(1,100)
b = randint(1,500)
question = input("What is the value of {} + {} : ".format(a,b))
if int(question) == (a + b):
print("You are correct")
mark = mark+1
else:
print("Your answer is wrong")
print("The correct answer is {}".format(a+b))
if question == "2":
for x in range(count) :
a = randint(1,100)
b = randint(1,500)
if b > a:
a,b = b,a
question = input("What is the value of {} - {} : ".format(a,b))
if int(question) == (a - b):
print("You are correct")
mark = mark + 1
elif int(question) != (a - b):
print("Your answer is wrong")
print("The correct answer is {}".format(a-b))
mark = mark + 0
elif question == "3":
for m in range(count) :
a = randint(1,100)
b = randint(1,500)
question = input("What is the value of {} ⨯ {} : ".format(a,b))
if int(question) == (a * b):
print("You are correct")
mark = mark + 1
elif int(question) != (a*b):
print("Your answer is wrong")
print("The correct answer is {}".format(a*b))
mark = mark + 0
elif question == "4":
for m in range(count) :
a = randint(1,100)
b = randint(1,500)
if b > a:
a,b = b,a
question = input("What is the value of {} ÷ {} in integer: ".format(a,b))
if int(question) == (a // b):
print("You are correct")
elif int(question) != (a//b):
print("Your answer is wrong")
print("The correct answer is {}".format(a//b))
sleep(2)
print("\nYour final mark is {}".format(mark))
How to randomly select one of the four operations and change it for every question? It is not necessary to change it but I don't want to display the same type of operation every time.
To clear something, question = input("What kind of questions do you want? (Type 1/2/3/4) :")
I write the line just to test if my code is working or not.
You can use random.randint.
import random
question = random.randint(1, 4) # Returns an integer value between 1 and 4
if question == 1:
# Do Something
elif question == 2:
# Do Something, etc.
You can use the random library and pass a list. It will output a random item from the list.
import random
random.choice([1,2,3,4])
This question already has answers here:
How to sort a list of strings?
(11 answers)
Closed 3 years ago.
I am developing a game and i need to add a leader board to it. I have coded one which allows the user to add high scores, view high scores and erase all high score. Now I need to sort all the scores in order of highest to lowest. Here's my code currently [NOTE: I'm aware that this isn't the best menu but I will change that later on]:
choice = input(str("Would you like to add a high score to the leader board?: "))
if choice == "y":
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = user1 + ": " + hs1
data2 = user2 + ": " + hs2
with open("leaderboard.txt","a") as file:
file.write(data1)
file.write("\n")
file.write(data2)
file.write("\n")
print("Data added.")
elif choice == "n":
final_list = []
with open("leaderboard.txt","r") as file:
first_list = file.readlines()
for i in first_list:
final_list.append(i.strip())
print("Leader board")
print("-------------")
for count in range(0,len(final_list)):
print(final_list[count])
else:
with open("leaderboard.txt","w") as file:
file.write(" ")
print("leader board cleared.")
I would like the leader board to be displayed once ordered something like this:
1. James F: 32
2. Harris W: 18
3. Courtney J: 12
Thank you for reading!
I found that i can restructure how the data is saved to the text file using numerical data first like this:
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = hs1 + " - " + user1
data2 = hs2 + " - " + user2
Now the data starts with a number, i can simply use .sort on my list to sort them, however they will be sorted lowest to biggest so i had to use .reverse() to flip the list around.
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 7 years ago.
Improve this question
is there a way to add a second loop to a code. So the question says to create a quiz which I've done however, for the last hour I've being trying to add a second loop so the quiz does it three times:
import random
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
classno = input("What class are you in?")
while classno not in classnumber:
print(
"Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?")
while questions < 10:
for i in range(10):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
if op == "-":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" - "+str(number2)+"=")
if uinput == str(subtract):
score += 1
print("Correct, your score is: ", score,)
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
if op == "+":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" + "+str(number2)+"=")
if uinput == str(addition):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
if op == "*":
print("Please enter your answer.")
questions += 1
print(" Question", questions, "/10")
uinput = input(str(number1)+" * "+str(number2)+"=")
if uinput == str(multiply):
score += 1
print(" Correct, your score is: ", score,)
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
First, please consider using functions in your code. Functions make everything neater and functions help make code reusable.
Second, there are a lot of areas where the code is superfluous. It is performing unnecessary checks in spots and several sections of the code could be rearranged to reduce the overall length and increase readability.
Nonetheless, here's a revised version of your code with some of those suggestions implemented:
import random
def RunQuiz():
name = input("Enter Your Username: ")
print("Hello, " + name + ". Welcome to the Arithmetic Quiz")
score = 0
questions = 0
loop = 0
classnumber = ("1", "2", "3")
classno = input("What class are you in?")
while classno not in classnumber:
print("Enter a valid class. The classes you could be in are 1, 2 or 3.")
classno = input("What class are you in?\n>>> ")
# End while input
# Run the 10 question quiz
for questions in range(1,11):
number1 = random.randint(1, 10)
number2 = random.randint(1, 10)
op = random.choice("*-+")
multiply = number1*number2
subtract = number1-number2
addition = number1+number2
print("Please enter your answer.")
print(" Question" + str(questions) "/10")
if( op == "-"):
# Subtraction
uinput = input(str(number1)+" - "+str(number2)+"=")
# Make it an int for proper comparison
uinput = int(uinput)
if uinput == subtract:
score += 1
print("Correct, your score is: %d" %(score,))
else:
print("Incorrect, the answer is: " + str(subtract))
score += 0
elif( op == "+"):
# Addition
uinput = input(str(number1)+" + "+str(number2)+"=")
uinput = int(uinput)
if uinput == addition:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(addition))
score += 0
elif( op == "*" ):
# Multiplication
uinput = input(str(number1)+" * "+str(number2)+"=")
uinput = int(uinput)
if uinput == multiply:
score += 1
print(" Correct, your score is: %d" % (score,))
else:
print(" Incorrect, the answer is: " + str(multiply))
score += 0
# End if( op )
# End For 10 questions
print("\nFinal Score: %d/10" % (score,))
# End RunQuiz()
def main():
# Run the quiz 10 times
for RunCount in range(3):
print("Running quiz #%d\n" % (RunCount,))
RunQuiz()
# End For
# End main
# Call main on script execution
main()
Obviously you can rearrange the code to suit your needs. (For example, I did not know if you want the name & class number to be entered every time).
If you want the whole thing to run 3 times then put for i in xrange(3): above the first lines of the quiz then indent the rest of the code to the loop. If that is what you actually want. Good luck!