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}")
Related
This question already has answers here:
Does "IndexError: list index out of range" when trying to access the N'th item mean that my list has less than N items?
(7 answers)
Closed 1 year ago.
ItemNumber = []
ItemDescription = []
ItemReserveprice = []
ItemBids = []
Item = 0
Buyerno = 1
BuyerNumber = []
sellercount = 0
whoareyou = input("Are you a seller or a buyer? enter s/b ")
if whoareyou == "s":
choice1 = input("Do you want to enter your seller ID?: ")
if choice1 == "yes":
testItemNumber = input("Please enter your seller id in the form 00N: ")
for i in ItemNumber:
if i == testItemNumber:
print("Please enter another seller ID")
ItemNumber.insert(sellercount,int(input("Enter your seller ID again, please make sure it is in the form 00N: ")))
while Item < 11:
ItemDescription.insert(Item,input("Enter your item description: "))
ItemReserveprice.insert(Item,int(input("Enter your reserve price: ")))
ItemBids.insert(Item,0)
Item = Item + 1
if choice1 == "no":
ItemNumber.insert(sellercount,('00' + str(sellercount+1)))
print (ItemNumber[sellercount],"is your seller ID")
while Item < 10:
print ("Now enter Item number",Item+1)
ItemDescription.insert(Item,input("Enter your item description: "))
ItemReserveprice.insert(Item,int(input("Enter your reserve price: ")))
ItemBids.insert(Item,0)
Item = Item + 1
print ("Auction Starts!")
print ("You are now in the buyer screen")
BuyerNumber.insert(Buyerno,('aa' + str(Buyerno)))
print ("Your buyer number is",BuyerNumber)
or i in range (0,10):
print ("The Item number of item number ",i+1,"is",ItemNumber[i],"The Description is",ItemDescription[i],"The reserve price is",ItemReserveprice[i])
choice2 = input("What item do you want to bid for?, enter the item number")
if i try to print any element from the array that is not the first one i get that error. For example if i try to print ItemNumber[2] or anything above so i cant print ItemNumber[i] as when i goes 2 to i get that error. I'm trying a task for an auction specifically the 2019 June Computer science pre release paper.Im a beginner so please dont bash this is my 2nd month. PS: the code is not completed
Because in the code
ItemNumber.insert(sellercount,('00' + str(sellercount+1)))
only 1 record has been added into ItemNumber.
So access ItemNumber[i] when i in (2..10) will cause exception.
I try to modify the code, add the item number into ItemNumber as below:
ItemNumber = []
ItemDescription = []
ItemReserveprice = []
ItemBids = []
Item = 0
Buyerno = 1
BuyerNumber = []
sellercount = 0
# NOTE: use SellerNumber to store the seller number
SellerNumber = []
whoareyou = input("Are you a seller or a buyer? enter s/b ")
if whoareyou == "s":
choice1 = input("Do you want to enter your seller ID?: ")
if choice1 == "yes":
testItemNumber = input("Please enter your seller id in the form 00N: ")
for i in ItemNumber:
if i == testItemNumber:
print("Please enter another seller ID")
ItemNumber.insert(sellercount,int(input("Enter your seller ID again, please make sure it is in the form 00N: ")))
while Item < 11:
ItemDescription.insert(Item,input("Enter your item description: "))
ItemReserveprice.insert(Item,int(input("Enter your reserve price: ")))
ItemBids.insert(Item,0)
Item = Item + 1
if choice1 == "no":
# NOTE: insert the seller number
SellerNumber.insert(sellercount,('00' + str(sellercount+1)))
print (SellerNumber[sellercount],"is your seller ID")
while Item < 10:
print ("Now enter Item number",Item+1)
# NOTE: insert the item number into ItemNumber
ItemNumber.insert(Item, 'ITEM_NUMBER' + str(Item))
ItemDescription.insert(Item,input("Enter your item description: "))
ItemReserveprice.insert(Item,int(input("Enter your reserve price: ")))
ItemBids.insert(Item,0)
Item = Item + 1
print ("Auction Starts!")
print ("You are now in the buyer screen")
BuyerNumber.insert(Buyerno,('aa' + str(Buyerno)))
print ("Your buyer number is",BuyerNumber)
for i in range (0,10):
print ("The Item number of item number ",i+1,"is",ItemNumber[i],"The Description is",ItemDescription[i],"The reserve price is",ItemReserveprice[i])
choice2 = input("What item do you want to bid for?, enter the item number")
And it works:
Need for a user to input bowling scores and store them, to be totaled and averaged later and they can press "q" or "Q" to quit and total/average them. I've tried fumbling around figuring out loops but not sure how to deal with inputting integers and also accepting "Q" to stop loop. Thanks for any help.
nums = []
scores = ""
while scores != 'q'.lower():
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores != 'q':
nums.append(int(scores))
elif scores == 'q'.lower():
print("quitting")
break
scores = int()
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
Getting error:
Traceback (most recent call last):
File "/Users/ryaber/PycharmProjects/pythonProject/main.py", line 11, in
scores = input("Please enter a score (xxx) or 'q' to exit: ")
File "", line 1, in
NameError: name 'q' is not defined
So not sure how to allow it to accept "Q" to stop loop and total/average them.
Remove .lower() in q.lower() and move it and make it to score.lower().
So if user types in q or Q both will be accepted as quit
You do not need average function or while scores != 'q' instead you could change it to something simple
So complete code -
nums = []
scores = ""
while True:
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == 'q':
print("quitting")
break
scores = int()
total = sum(nums)
print(f"The total score is: {total}")
average = total/len(nums)
print("The score average is: ", round(average, 2))
Result:
Please enter a score (xxx) or 'q' to exit: 25
Please enter a score (xxx) or 'q' to exit: 32
Please enter a score (xxx) or 'q' to exit: Q
quitting
The total score is: 57
The score average is: 28.5
Edit -
While this may be complicated, this will solve your problem -
nums = []
scores = ""
while True:
scores = input("Please enter a score (xxx) or 'q' to exit: ")
try: # This will run when scores is a number
scores = int(scores)
if scores.lower() == type(0):
nums.append(int(scores))
except: # Will run when it is a alphabet
if scores.lower() == 'q':
print("quitting")
break
else:
continue
scores = int()
total = sum(nums)
print(f"The total score is: {total}")
average = total/len(nums)
print("The score average is: ", round(average, 2))
break
nums.append(int(scores))
just cast it to an int ...
You only need to convert your input string to an int before storing it:
nums = []
scores = ""
while scores != 'q'.lower():
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores != 'q':
nums.append(int(scores))
elif scores == 'q'.lower():
print("quitting")
break
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
You need to append integral value of score to the list
nums.append(int(scores))
Also, I guess you might want to use a f-string here
print(f"The total score is: {total}")
EDIT :
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == "q":
print("quitting")
break
As pointed out by #PCM, you need to use the .lower() method on the variable
The final working code :
nums = []
scores = ""
while scores != 'q':
scores = input("Please enter a score (xxx) or 'q' to exit: ")
if scores.lower() != 'q':
nums.append(int(scores))
elif scores.lower() == "q":
print("quitting")
break
scores = int()
def Average(nums):
return sum(nums) / len(nums)
total = sum(nums)
print(f"The total score is: {total}")
average = Average(nums)
print("The score average is: ", round(average, 2))
You can read more about f-strings here
I am currently trying to create a code that will help people in shops who need to:
Calculate the item with the best value (out of up to 10 items)
Calculate the sale price
Calculate the discount
Create a shopping cart or a shopping list
Print a receipt (just by simply showing the items, the quantity and the the cost of each products, then showing the total cost at the bottom)
I have only worked on the top four points above, but I have not a single idea on how to create and print a receipt. Here's my code so far:
#This part greets the user, and lets the user know that the application has started
print("Hello there!")
#This starts off the loop, but this variable may be changed later on
cont = "yes"
#This is the actual loop
while cont == "yes" or cont == "Yes" or cont == "YES":
print("Choose an option below:")
#This shows the options
print("1) Calculate the value of different product sizes")
print("2) Calculate the sale price")
print("3) Calculate the discount")
print("4) Create a shopping list")
print("5) Exit")
#This part lets the user choose what they would like to do
option = float(input("Choose an option (1/2/3/4/5): "))
#This is what happens if the user chooses Option 4
if option == 4:
#This is the "Shopping list" part of the application below
import os,sys,time
sl = []
try:
f = open("Your_shopping_list.txt","r")
for line in f:
sl.append(line.strip())
f.close()
except:
pass
def mainScreen():
print("Your list contains",len(sl),"items.")
print("Please choose from the following options:")
print("1) Add to the list")
print("2) Delete from the list")
print("3) View the list")
print("4) Quit the program")
choice = input("Enter your choice here (1/2/3/4): ")
if len(choice) > 0:
if choice == "1":
addScreen()
elif choice == "2":
deleteScreen()
elif choice == "3":
viewScreen()
elif choice == "4":
sys.exit()
else:
mainScreen()
else:
mainScreen()
def addScreen():
print("Please enter the name of the item that you want to add.")
print("Press ENTER to return to the main menu.")
item = input("Item: ")
if len(item) > 0:
sl.append(item)
print("Item added.")
saveList()
time.sleep(1)
addScreen()
else:
mainScreen()
def viewScreen():
for item in sl:
print(item)
print("Press ENTER to return to the main menu")
input()
mainScreen()
def deleteScreen():
global sl
count = 0
for item in sl:
print(count, " - ", item)
count = count + 1
print("Press ENTER to return to the main menu.")
print("Which item do you want to remove?")
choice = input("Enter your choice here: ")
if len(choice) > 0:
try:
del sl[int(choice)]
print("Item deleted...")
saveList()
time.sleep(1)
except:
print("Invalid number")
time.sleep(1)
deleteScreen()
else:
mainScreen()
def saveList():
f = open("Your_shopping_list.txt", "w")
for item in sl:
f.write(item)
f.close()
mainScreen()
#This is what happens if the user chooses Option 1
#This is the part that calculates the value of up to 10 products
if option == 1:
#This notifies the user that there can only be up to 10 product sizes entered
print("Please note: This code can only take up to 10 product sizes.")
#This asks the user how many products there are
products = int(input("How many products are there? "))
#This is just in case the user still types that there are over 10 products
if products > 10:
print("This code can only take up to 10 product sizes.")
print("Please enter only up to 10 product sizes below.")
if products <= 1:
#This tells the user that they must enter at least 2 product sizes to compare them
print("You must enter at least two product sizes to compare.")
if products >= 1:
#This asks for information because the user may just be looking for the $/g.
cost1 = float(input("Cost of first product($): "))
mass1 = float(input("Mass of first product(g): "))
ans1 = cost1/mass1
a = ans1
#This part substitutes undefined variables with a blank
#This is in case the number of sizes being compared doesn't reach 2 to 10
ans2 = ""
ans3 = ""
ans4 = ""
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are two or more product sizes
if products >= 2:
cost2 = float(input("Cost of second product($): "))
mass2 = float(input("Mass of second product(g): "))
ans2 = cost2/mass2
if a > ans2:
a = ans2
#This is for when there are three or more product sizes
if products >= 3:
cost3 = float(input("Cost of third product($): "))
mass3 = float(input("Mass of third product(g): "))
ans3 = cost3/mass3
if a > ans3:
a = ans3
ans4 = ""
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are four or more product sizes
if products >= 4:
cost4 = float(input("Cost of fourth product($): "))
mass4 = float(input("Mass of fourth product(g): "))
ans4 = cost4/mass4
if a > ans4:
a = ans4
ans5 = ""
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are five or more product sizes
if products >= 5:
cost5 = float(input("Cost of fifth product($): "))
mass5 = float(input("Mass of fifth product(g): "))
ans5 = cost5/mass5
if a > ans5:
a = ans5
ans6 = ""
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are six or more product sizes
if products >= 6:
cost6 = float(input("Cost of sixth product($): "))
mass6 = float(input("Mass of sixth product(g): "))
ans6 = cost6/mass6
if a > ans6:
a = ans6
ans7 = ""
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are seven or more product sizes
if products >= 7:
cost7 = float(input("Cost of seventh product($): "))
mass7 = float(input("Mass of seventh product(g): "))
ans7 = cost7/mass7
if a > ans7:
a = ans7
ans8 = ""
ans9 = ""
ans10 = ""
#This is for when there are eight or more product sizes
if products >= 8:
cost8 = float(input("Cost of eighth product($): "))
mass8 = float(input("Mass of eighth product(g): "))
ans8 = cost8/mass8
if a > ans8:
a = ans8
ans9 = ""
ans10 = ""
#This is for when there are nine or more product sizes
if products >= 9:
cost9 = float(input("Cost of ninth product($): "))
mass9 = float(input("Mass of ninth product(g): "))
ans9 = cost9/mass9
if a > ans9:
a = ans9
ans10 = ""
#This is for when there are ten or more product sizes
if products >= 10:
cost10 = float(input("Cost of tenth product($): "))
mass10 = float(input("Mass of tenth product(g): "))
ans10 = cost10/mass10
if a > ans10:
a = ans10
#There's nothing for 10+ sizes for there is no loop for it'll make the code too long
#This tells the user the which product size(s) is/are the ones with the best value
#This tells the user the final result
if products >= 1:
print("The product(s) with the best value is/are the below product number(s):")
if ans1 == a:
print(1)
if ans2 == a:
print(2)
if ans3 == a:
print(3)
if ans4 == a:
print(4)
if ans5 == a:
print(5)
if ans6 == a:
print(6)
if ans7 == a:
print(7)
if ans8 == a:
print(8)
if ans9 == a:
print(9)
if ans10 == a:
print(10)
#This tells the user the cost per gram of the product(s) with the best value is/are
print("The cost per gram is $", a, "/ g")
#This tells the user to pick the size with best quality if multiple are above
#Sometimes, items with the best value may not have the best quality.
print("If there are multiple options above, choose the one with best quality.")
#This is what happens if the user chooses Option 2
#This calculates the price after a discount
if option == 2:
#This asks for the ticket (original) price of a specific product
p = float(input('The ticket (original) price($): '))
#This asks for the discount (in percentage) of a specific product
d = float(input('The discount(%): '))
#This then puts the information together and calculates the discount...
s = (d*0.01)
ps = (p*s)
answer = (p - ps)
answer2 = str(round(answer, 2))
print('The discount is $', ps)
#... and also the final discounted price.
#Finally, it tells the user the result
print('The final price is $', answer2)
#This is what happens if the user chooses Option 3
#This calculates the discount (in percentage)
if option == 3:
#This collects information about what the ticket (original) price was
o = float(input('The ticket (original) price($): '))
#This asks what the price of the product after the discount is
#Then it takes all the information, puts them together and calculates the discount(%)
d = float(input('Price after the discount($): '))
p = 100/(o/d)
p = str(round(p, 2))
#Finally, it tells the user the result
print('The percentage discount is', p,'%')
#This is the final option, which is for the user to quit using this application
if option == 5:
#This asks the user one last time in case they accidentally pressed 5.
exit = input("Are you sure you want to exit? (Yes/No): ")
#There are three versions of "Yes" to make the application more user-friendly
if exit == "yes":
#"Thank you and goodbye" thanks the user for using this application
#Then, it says goodbye and ends the application
print("Thank you and goodbye!")
cont = 'no'
if exit == "Yes":
print("Thank you and goodbye!")
cont = 'no'
if exit == "YES":
print("Thank you and goodbye!")
cont = 'no'
#But if exit doesn't equal "Yes" or "yes" or "YES", then cont still equals "yes".
#And if cont = "yes", then the loop restarts.
#This is if the user doesn't choose any of the above and enters an invalid input
elif option != 1:
if option != 2:
if option != 3:
if option != 4:
if option != 5:
print('Invalid input')
#This asks if the user would like to continue or quit
cont = input('Continue? (Yes/No): ')
#To make the application more user-friendly, there are again three versions of "No"
if cont == 'No':
#"Thank you and goodbye" thanks the user for using this application
#Then, it says goodbye and ends the application
print("Thank you and goodbye!")
if cont == 'no':
print("Thank you and goodbye!")
if cont == 'NO':
print("Thank you and goodbye!")
Here are some improvements:
1.Use a class instead to store different related things
class Ingredient():
def __init__(self, name):
self.name = name
self.cost = float(input(f"Cost of {self.name}($): "))
self.mass = float(input(f"Mass of {self.name}(g): "))
self.ans = cost6 / mass6
2.Then you don't need ten answer variables. You can use a list
wrong:
ans2 = ""
ans3 = ""
...
option1 = input()
option2 = input()
...
right:
ingredients = []
for i in range(0, products):
ing = Ingredient("Product " + str(i + 1))
ingredients.append(ing)
3.Use lists to compare different options
elif option != 1:
if option != 2:
if option != 3:
if option != 4:
if option != 5:
can be replaced by
if option not in [1, 2, 3, 4, 5]:
and
if exit == "yes":
print("Thank you and goodbye!")
...
could be
if exit in ["yes", "YES", "Yes"]:
print("Thank you and goodbye!")
cont = 'no'
same for cont == No
Then showing a receipt will be easy
totalCost = 0
for item in ingredients:
print(item.name, str(item.cost), str(item.mass))
totalCost += item.cost
print(totalCost + "$")
Here is a solution (I hope this answers your question):
print ('How many items are you planning to buy?')
times = int(input('>> '))
def question(times):
grocery_list = {}
print ('Enter grocery item and price.')
for i in range(times):
key = input('Item %d Name: ' % int(i+1))
value = input('Item %d Price: $' % int(i+1))
grocery_list[key] = value
print(grocery_list)
totalPrice = sum([float(grocery_list[item]) for item in grocery_list])
print('Total: ${:.2f}'.format(totalPrice))
question(times)
print('< >')
Maybe consider using this as a solution, as it is an improved version of user13329487 's code:
def inputGroceries():
groceries = list()
while True:
try:
i = len(groceries)
name = input('Item #{} name: '.format(i))
if name == '':
break
price = float(input('Item #{} price: $'.format(i)))
quantity = int(input('Item #{} quantity: '.format(i)))
except ValueError:
print('Error: invalid input..')
continue
groceries.append((name, price, quantity))
return groceries
print("Enter items, price and quantity (end list by entering empty name):")
groceries = inputGroceries()
for item in groceries:
print('{} x {} (${:.2f} PP)'.format(item[2], item[0], item[1]))
totalPrice = sum([item[1] * item[2] for item in groceries])
print(30*'-')
print('Total: ${:>22.2f}'.format(totalPrice))
I am trying to create code to pull from a data sheet. My goal is to find the longest song, songs by year, and songs by an artist. Problem is, that when I run what I currently have I get a value returned of 0. Obviously this is not correct. What ways can I do to solve this? I have linked the data sheet here. Click here!
def longest_song():
pass
def songs_by_year(year):
total=0
with open('music.csv', 'r') as f:
for line in f:
time = line.split(",")
song = time[34]
if song == year:
total = total + 1
return total
def all_songs_by_artist(artist):
total = int(0)
data = open("music.csv", "r")
for line in data:
name = line.split(",")
song = name[2]
if song == artist:
total = total + 1
return total
# --------------------------------------
def menu():
print()
print("1. Identify longest song.")
print("2. Identify number of songs in a given year.")
print("3. Identify all songs by a given artist.")
print("4. You choose something that is interesting and non-trivial.")
print("5. Quit.")
# --------------------------------------
def main():
choice = 0
while (choice != 5):
menu()
choice = int(input("Enter your choice: "))
if (choice == 1):
longest_song()
elif (choice == 2):
year = int(input("Enter desired year: "))
number = songs_by_year(year)
## print("The number of songs from", "{:,d}".format(number))
print(number)
elif (choice == 3):
artist = input("Enter name of artist: ").lower()
all_songs_by_artist(artist)
number = all_songs_by_artist(artist)
print("There are", "{:,d}".format(number))
elif (choice == 4):
pass
elif (choice != 5):
print("That is not a valid option. Please try again.")
# --------------------------------------
main()
You are converting input artist to lowercase but Not changing the artist from the file to lower case, thus no matches.
You are converting the Year to an int but not doing so to the year from the file.
It is difficult to tell if there are other issues, as your code sample is not indented properly.
I'm guessing but I suppose that it should look something like this.
def longest_song(): pass
def songs_by_year(year):
total=0
with open('music.csv', 'r') as f:
for line in f:
time = line.split(",")
song = time[34]
try:
if int(song) == year:
total = total + 1
except:
pass
return total
def all_songs_by_artist(artist):
total = int(0)
with open("music.csv", "r") as data:
for line in data:
name = line.split(",")
song = name[2].lower()
if song == artist:
total = total + 1
return total
# --------------------------------------
def menu():
print()
print("1. Identify longest song.")
print("2. Identify number of songs in a given year.")
print("3. Identify all songs by a given artist.")
print("4. You choose something that is interesting and non-trivial.")
print("5. Quit.")
# --------------------------------------
def main():
choice = 0
while (choice != 5):
menu()
choice = int(input("Enter your choice: "))
if (choice == 1):
longest_song()
elif (choice == 2):
year = int(input("Enter desired year: "))
number = songs_by_year(year)
## print("The number of songs from", "{:,d}".format(number))
print(number)
elif (choice == 3):
artist = input("Enter name of artist: ").lower()
all_songs_by_artist(artist)
number = all_songs_by_artist(artist)
print("There are", "{:,d}".format(number))
elif (choice == 4):
pass
elif (choice != 5):
print("That is not a valid option. Please try again.")
# --------------------------------------
main()
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.