Python - Sorting file highest to lowest and alphabetically - python

I have created an arithmetic code, that asks the user 10 questions, and then stores their name and score in a database e.g. C:\class1.txt and I'm now at the stage, where I should be able to sort the file containing the name and the score of multiple pupils from each individual class, in both highest to lowest (scores) and alphabetically. The program should ask a question at the end of the code, asking the teacher if they want it sorted alphabetically or highest to lowest by score. They should also be able to pick the class they want sorted, and it should be printed.
I am asking for guidance on this, I do not want to cheat, I am just now clueless at this stage; with a teacher that is useless.
Thanks in advance
import random
USER_SCORE = 0
questions = 0
classnumber = ("1","2","3")
name1= input("Enter Your Username: ")
print("Hello, " + name1)
print(" Welcome to the Arithmetic Quiz")
classno = input("What class are you in?")
while classno not in classnumber:
print("Enter a valid class")
print("ENTER ONLY THE NUMBER n\ 1 n\ 2 n\3")
classno=input("What class are you in?")
while questions <10:
for i in range(10):
num1=random.randint(1,10)
num2=random.randint(1,10)
on=random.choice("*-+")
multiply=num1*num2
subtract=num1-num2
addition=num1+num2
if on == "-": #If "-" or subtract is randomly picked.
print("MAKE SURE YOU ENTER A NUMBER OTHERWISE YOU WILL BE MARKED DOWN")
questions+=1
print(" Question" ,questions, "/10")
uinput=input(str(num1)+" - "+str(num2))
if uinput == str(subtract):
USER_SCORE+=1
print(" Correct, your USER_SCORE is: " ,USER_SCORE,)
else:
print (" Incorrect, the answer is: " +str(subtract))
USER_SCORE+=0
if on == "+":
print("MAKE SURE YOU ENTER A NUMBER OTHERWISE YOU WILL BE MARKED DOWN")
questions+=1
print(" Question",questions, "/10")
uinput=input(str(num1)+" + "+str(num2))
if uinput == str(addition):
USER_SCORE+=1
print(" Correct, your USER_SCORE is: ",USER_SCORE,)
else:
print(" Incorrect, the answer is: " +str(addition))
USER_SCORE+=0
if on == "*":
print("MAKE SURE YOU ENTER A NUMBER OTHERWISE YOU WILL BE MARKED DOWN")
questions+=1
print(" Question",questions, "/10")
uinput=input(str(num1)+" * "+str(num2))
if uinput == str(multiply):
USER_SCORE+=1
print(" Correct, your USER_SCORE is: " ,USER_SCORE,)
else:
print(" Incorrect, the answer is: " +str(multiply))
USER_SCORE+=0
if USER_SCORE >9:
print("Well done," ,name1, "your score is" ,USER_SCORE, "/10")
else:
print(name1," your score is " ,USER_SCORE, "/10")
def no1():
with open("no1.txt", 'a')as file:
file.write(str(name1)+" achieved a score of: "+str(USER_SCORE)+"/10 \n")
def no2():
with open("no2.txt", 'a')as file:
file.write(str(name1)+" achieved a score of "+str(USER_SCORE)+"/10 \n")
def no3():
with open("no3.txt", 'a')as file:
file.write(str(name1)+" achieved a score of "+str(USER_SCORE)+"/10 \n")
if classno=="1":
no1()
if classno=="2":
no2()
if classno=="3":
no3()

#crclayton
I found this for alphabetical sorting, however, I still don't know how to sort the file from highest to lowest
viewclass= input("choose a class number and either alphabetically, average or highest?")
if viewclass=='1 alphabetically':
with open('class1.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
elif viewclass=='2 alphabetically':
with open('class2.txt', 'r') as r:
for line in sorted(r):
print(line, end='')
elif viewclass=='3 alphabetically':
with open('class3.txt', 'r') as r:
for line in sorted(r):
print(line, end='')

As I said in the comment, in order to code you need to be able to break your problem into smaller components. Each of those smaller problems should be their own function. It'll be easier to keep track of things and solve smaller problems.
Here are some examples of the sort of functions you should make. I can't stress enough that your questions on S.O. should be about those individual problems, not wanting to know generally how to do things.
Try to fill in the blanks of this structure.
import random
def get_score():
# here do your code to calculate the score
score = random.randint(0,10)
return score
def write_list_to_file():
# for each item in list, write that to a file
pass
def sort_list_alphabetically(unsorted_list):
# figure out how to sort a list one way
return sorted_list
def sort_list_numerically(unsorted_list):
# figure out how to sort a list the other way
return sorted_list
def get_sort_method_from_user():
# get input however you want
if soandso:
return "Alphabetical"
else:
return "Numerical"
def get_user_name():
# do your stuff
return name;
questions = 0
list_of_scores = []
while questions < 10:
name = get_user_name();
user_score = get_score();
output_line = name + " got a score of " + user_score
list_of_scores.append(output_line)
sort_method = get_sort_method_from_user();
if sort_method == "Alphabetical":
new_list = sort_list_alphabetically(list_of_scores)
else:
new_list = sort_list_numerically(list_of_scores)
write_list_to_file(list_of_scores)

Related

Trying to add an external Score File to a Python Guessing Game

I'm creating a Python guessing game for school.
The game its self works fine, but I need to add an external score file (.txt)
I've tried a lot of different ways to implement this but where I'm having trouble is;
If the userName is existing in the file, how do I update that userName's score line.
The last method (in the code) was just a test to have a new userName added to the file if it was not found. This seemed to have over written the file, without adding the new userName.
# Import random library
import random
import os
# Welcome User to the game
print("Welcome to the game")
# Collect user details
userName = input("Please enter your Name: ")
# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)
# Random picks the number to guess
number = random.randint(1,99)
guesses = 0
win = 0
lose = 0
# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
guess = int(input("Enter a number from 0 to 99: "))
guesses += 1
print("This is guess %d " %guesses)
if guess > 100:
print("Number out of range. Lose a turn")
if guess < number:
print("You guessed to low")
elif guess > number:
print("you guessed to high")
elif guess == number:
guesses = str(guesses)
print("You Win! you guessed the right number in",guesses + " turns")
win = +1
break
# If the user cannot guess the number in time, they receive a message
if guess !=number:
number = str(number)
print("You Lose. The number was: ",number)
lose = +1
with open('scoreList.txt', 'r') as scoreRead:
with open('scoreList.txt', 'w') as scoreWrite:
data = scoreRead.readlines()
for line in data:
if userName not in line:
scoreWrite.write(userName + "\n")
scoreRead.close()
scoreWrite.close()
It doesn't matter so much what the formatting of the score file looks like, as long as I can edit existing scores when they enter their name at the start of the game. Add a new user if it doesn't exist. Then print the scores at the end of each game.
I'm at a complete loss.
You have multiple mistakes in your final block. You open scoreList.txt but do the write operations outside of the with .. as block. Outside this block, the file is closed. Also because you are using with .. as, you don't have to close the files manually in the end.
And then, you iterate over all lines and would write the name for each line, that does not contain it, so potentially many times. And you open the file with 'w', telling it to overwrite. If you want to append, use 'a'.
Try it like this:
with open('scoreList.txt', 'r') as scoreRead:
data = scoreRead.readlines()
with open('scoreList.txt', 'a') as scoreWrite:
if userName + "\n" not in data:
scoreWrite.write(userName + "\n")
Also note, that you are currently writing each name into the score list and not only those, that won the game.
I believe you can accomplish this using the json module, as it will allow the use of data from a dictionary in the JSON file format.
A dictionary would be the superior method to storing users and associated scores, because it is easier to access these values in python, if using an associated text file.
I have updated your code with a working solution:
#! usr/bin/python
# Import random library
import random
import os
import json
# Welcome User to the game
print("Welcome to the game")
# Collect user details
userName = input("Please enter your Name: ")
#Added section
current_player = {"name": userName,
"wins": 0,
"losses": 0,
}
try:
with open('scores.json', 'r') as f:
data = json.load(f)
for i in data['players']:
if i["name"] == current_player["name"]:
current_player["wins"] = i["wins"]
current_player["losses"] = i["losses"]
except:
pass
print(current_player)
#end added section
"""begin game"""
# Roll the die for the number of guesses
print("Rolling the Dice!")
diceRoll = random.randint(1,6)
print("You have %d Guesses: " %diceRoll)
# Random picks the number to guess
number = random.randint(1,99)
guesses = 0
win = 0
lose = 0
# Loop checks the users input against the randint and supplies a hint, or breaks if correct
while guesses < diceRoll:
guess = int(input("Enter a number from 0 to 99: "))
guesses += 1
print("This is guess %d " %guesses)
if guess > 100:
print("Number out of range. Lose a turn")
if guess < number:
print("You guessed to low")
elif guess > number:
print("you guessed to high")
elif guess == number:
guesses = str(guesses)
print("You Win! you guessed the right number in", guesses + " turns")
win = +1
break
# If the user cannot guess the number in time, they receive a message
if guess !=number:
number = str(number)
print("You Lose. The number was: ", number)
lose = +1
"""end game"""
#added section
current_player["wins"] += win
current_player["losses"] += lose
try:
for i in data['players']:
if current_player["name"] == i["name"]:
i["wins"] = current_player["wins"]
i["losses"] = current_player["losses"]
if current_player not in data['players']:
data['players'].append(current_player)
print("Current Scores:\n")
for i in data['players']:
print(i["name"], ": wins", i["wins"], " losses: ", i["losses"])
with open('scores.json', 'w') as f:
f.write(json.dumps(data))
except:
start_dict = {"players":[current_player]}
with open('scores.json', 'w') as f:
f.write(json.dumps(start_dict))
print("Current Scores:\n")
for i in start_dict['players']:
print(i["name"], ": wins", i["wins"], " losses: ", i["losses"])
#end added section
This will check if the current player exists in the JSON file, then add their scores to the current player dictionary.
At the end of the game, it will check to see if:
The file scores.json exists, and will create it if it doesn't.
The current player exists in the scores.JSON file, and will update their score if they do. If they don't it will add a new user to the JSON file.
Then will print the score list accordingly.
Careful though, if a username is misspelt in any way, a new user will be created.
You can also manually update the scores in the .json file, if desired.

Why is the correct answer printing both score = 3 and score = 1?

When you enter the correct answer ("Bad Guy"), it prints score = 3 and score = 1 at the same time? How do I prevent this so after getting it right in one attempt, it displays (and saves) score = 3, and after getting it right on the second attempt, it displays (and saves) the score as 1? By the way, if the player guesses correctly the first time, they gain 3 points.If they get it wrong, they try again. If they guess correctly the second time, they only gain 1 point. If they still get it wrong, the game ends. Please explain what's wrong and try to fix this problem please.
Here's the code I'm using for this:
score = 0
print("Round 1:")
with open('songs.txt') as songs_list:
song_name = songs_list.readline()
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score+=3
print("Correct! Score = 3")
else:
print("Incorrect! Try again.")
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score +=1
print("Correct! Score = 1")
else:
print("Incorrect! Unlucky, you lost. I hope you enjoyed playing!")
import sys
sys.exit()
You should indent the second set of if-else statements. This means the second set will only occur if the first answer is wrong.
score = 0
print("Round 1:")
with open('songs.txt') as songs_list:
song_name = songs_list.readline()
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score+=3
print("Correct! Score = 3")
else:
print("Incorrect! Try again.")
answer = input("What is the song name? " + song_name)
if answer == "Bad Guy":
score +=1
print("Correct! Score = 1")
else:
print("Incorrect! Unlucky, you lost. I hope you enjoyed playing!")
import sys
sys.exit()
Your most immediate problem is that you never print score. Your only reports to the user are the literal strings Score = 3 and Score = 1. You'll need something like
print("you got 3 more points; new score =", score)

reading quiz text file no longer working

I am trying to ask the user to pick a quiz, read the relevant questions from a txt file, ask for user answers, validate and check they are correct then add up to scores. I am completely self taught so have picked this code up from various sites but as I have adapted it it no longer works - what have I done wrong? I know its probably something really obvious so please be gentle with me!
getting the message global name the_file not defined
import time
def welcome():
print ("Welcome to Mrs Askew's GCSE ICT Quiz")
print()
def get_name():
firstname = input("What is your first name?:")
secondname = input("What is your second name?:")
print ("Good luck", firstname,", lets begin")
return firstname
return secondname
def displaymenu():
print("-------------------------------------------------------")
print("Menu")
print()
print("1. Input and Output Devices")
print("2. Collaborative working")
print("3. quiz3")
print("4. quiz4")
print("5. view scores")
print("6. Exit")
print()
print("-------------------------------------------------------")
def getchoice():
while True:
print("enter number 1 to 6")
quizchoice = input()
print("You have chosen number "+quizchoice)
print()
if quizchoice >='1' and quizchoice <='6':
print("that is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print ("please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct=correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Couple of things I noticed. You haven't provided the error you are getting (/ problems you are having) so these are the things I noticed in my quick look:
First: enter code hereimport time should be import time
Second: All function definitions (def func():) should have the code in them indented e.g.
def get_name():
firstname = input("What is your first name: ")
Third: print () should be print()
Fourth: Multiline strings do exist
"""
Look at me mum!
WOWWWW!
"""
Fifth: It looks like a lot of this has been copied from elsewhere, if you are learning, I suggest you don't copy, but try to understand what things are doing and then hand write it
Sixth: There are a lot of bugs. I think I got most of them, but you should really change something in the way you're working. It really does fail in so many places
Seventh: Here is your code with some improvements:
import time
def welcome():
print("Welcome to Mrs Askew's GCSE ICT Quiz\n")
def get_name():
firstname = input("What is your first name: ")
secondname = input("What is your second name: ")
print("Good luck" + firstname + ", lets begin") # or print("Good luck {}, lets begin".format(firstname))
return firstname, secondname
def displaymenu():
print("""-------------------------------------------------------
Menu
1. Input and Output Devices
2. Collaborative working
3. quiz3
4. quiz4
5. view scores
6. Exit
-------------------------------------------------------""")
def getchoice():
while True:
quizchoice = input("Enter number 1 to 6: ")
print("You have chosen number " + quizchoice "\n")
if quizchoice >= "1" and quizchoice <= "6":
print("That is a valid entry")
break
else:
print("invalid entry")
return quizchoice
def main():
welcome()
get_name()
while True:
displaymenu()
quizchoice = getchoice()
print("Please chooses from the options above: ")
if quizchoice == ("1"):
the_file = open("questions.txt", "r")
startquiz()
elif quizchoice == ("2"):
collaborativeworking()
startquiz()
else:
break
def collborativeworking():
the_file = open("Collaborative working.txt", "r")
return the_file
def next_line(the_file):
line = the_file.readline()
line = line.replace("/", "\n")
return line
def next_block(the_file):
category = next_line(the_file)
question = next_line(the_file)
answers = []
for i in range(4):
answers.append(next_line(the_file))
correct = next_line(the_file)
if correct:
correct = correct[0]
explanation = next_line(the_file)
time.sleep(2)
return category, question, answers, correct, explanation
def startquiz():
title = next_line(the_file)
score = 0
category, question, answers, correct, explanation = next_block(the_file)
while category:
# ask a question
print(category)
print(question)
for i in range(4):
print("\t", i + 1, "-", answers[i])
# get answer and validate
while True:
answer =(input("What's your answer?: "))
if answer >= '1' and answer <='4':
break
else:
print ("the number needs to be between 1 and 4, try again ")
# check answer
answer=str(answer)
if answer == correct:
print("\nRight!", end=" ")
return score
main()
Eighth: Please take time to make an answer before you post. People here want to answer questions, and try to answer them with the most effort they can put in, so we expect questioners to put in the same effort, to spend time on their questions (basically pretend you are asking the person you respect most in your life this question, then behave appropriately e.g. Dear your royal highness, beloved master and benefactor, who I so dearly love, please, oh please, do me the great kindness to answer my humble question that I have taken 2 days to write properly so you wouldn't be offended and have to waste as little time as possible with such a small thing as me...)
Ninth: There are much better ways to do what you want.
I suggest you:
Try perfecting parts of your program, before writing 108 lines
Try not having so many functions
Try to decrease the length of your code, make it not so verbose, but succinct
Use consistent formatting (e.g. only one type of quotes; only, spaces or tabs)
Also read up on some basic python (learn python the hard way is good)
I also highly recommend PEP (Python Enhancement Proposals) 8 and the other PEP's
Look at test-driven development in python

How to save the users name and last 3 scores to a text file?

I need to write the last three scores of students and their names into a text file for the teacher's program to read and sort later.
I still don't know how to save the last 3 scores
I have tried this so far:
#Task 2
import random
name_score = []
myclass1= open("class1.txt","a")#Opens the text files
myclass2= open("class2.txt","a")#Opens the text files
myclass3= open ("class3.txt","a")#Opens the text files
def main():
name=input("Please enter your name:")#asks the user for their name and then stores it in the variable name
if name==(""):#checks if the name entered is blank
print ("please enter a valid name")#prints an error mesage if the user did not enter their name
main()#branches back to the main fuction (the beggining of the program), so the user will be asked to enter their name again
class_name(name)#branches to the class name function where the rest of the program will run
def class_name(yourName):
try:#This function will try to run the following but will ignore any errors
class_no=int(input("Please enter your class - 1,2 or 3:"))#Asks the user for an input
if class_no not in range(1, 3):
print("Please enter the correct class - either 1,2 or 3!")
class_name(yourName)
except:
print("Please enter the correct class - either 1,2 or 3!")#asks the user to enter the right class
class_name(yourName)#Branches back to the class choice
score=0#sets the score to zero
#add in class no. checking
for count in range (1,11):#Starts the loop
numbers=[random.randint (1,11),
random.randint (1,11)]#generates the random numbers for the program
operator=random.choice(["x","-","+"])#generates the random operator
if operator=="x":#checks if the generated is an "x"
solution =numbers[0]*numbers[1]#the program works out the answer
question="{0} * {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="+":#checks if the generated operator is an "+"
solution=numbers[0]+numbers[1]#the program works out the answer
question="{0} + {1}=".format(numbers[0], numbers [1])#outputs the question to the user
elif operator=="-":
solution=numbers[0]-numbers[1]#the program works out the answer
question="{0} - {1}=".format(numbers[0], numbers [1])#outputs the question to the user
try:
answer = int(input(question))
if answer == solution:#checks if the users answer equals the correct answer
score += 1 #if the answer is correct the program adds one to the score
print("Correct! Your score is, {0}".format(score))#the program outputs correct to the user and then outputs the users score
else:
print("Your answer is not correct")# fail safe - if try / else statment fails program will display error message
except:
print("Your answer is not correct")#if anything else is inputted output the following
if score >=5:
print("Congratulations {0} you have finished your ten questions your total score is {1} which is over half.".format(yourName,score))#when the user has finished there ten quetions the program outputs their final score
else:
print("Better luck next time {0}, your score is {1} which is lower than half".format(yourName,score))
name_score.append(yourName)
name_score.append(score)
if class_no ==1:
myclass1.write("{0}\n".format(name_score))
if class_no ==2:
myclass2.write("{0}\n".format(name_score))
if class_no ==3:
myclass3.write("{0}\n".format(name_score))
myclass1.close()
myclass2.close()
myclass3.close()
Your program seems to be working just fine now.
I've re-factored your code to follow the PEP8 guidelines, you should really try to make it more clear to read.
Removed the try/except blocks, not needed here. Don't use try/except without a exception(ValueError, KeyError...). Also, use with open(...) as ... instead of open/close, it will close the file for you.
# Task 2
import random
def main():
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")
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%s.txt" % class_no, "a") as my_class:
my_class.write("{0}\n".format([your_name, score]))
main()

My programme enteres a blank row before entering data to CSV file how to delete the row or stop it from adding the row?

This is my code and when I enter the programme and try to find the records and get them sorted it shows up list index out of range and when I take the quiz it shows up everything all right but when I enter the CSV file there is an empty row between the input and the beginning of the file I tried deleting the empty rows and the programme works sorts the data and prints it but with the empty rows it just shows up the error mentioned above.
a=True
b=True
c=True
import random #Here i imported a random module
import csv
import operator
score=0 #I made a variable called score and set it to 0
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
if menu1 == ("s"):
menu2=input("How do you want it sorted? alpabetically(a) acording to score highest to lowest(s) or according to average score highest to lowest(a) ")
if menu2 == ("a"):
menu3=input("Which class are you in a b or c ")
if menu3 == ("a"):
sample = open("ClassA.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
if menu3 == ("b"):
sample = open("ClassB.csv","r")
csv1 = csv.reader(sample,delimiter=",")
sort=sorted(csv1,key=operator.itemgetter(0))
for eachline in sort:
print(eachline)
menu4=input("Do you want to take the quiz now? ")
if menu4 == ("no"):
print("Thank you for Looking At the scores!")
if menu4 == ("yes"):
menu1=input("What do you want to do? Take Quiz(t) See Scores(s) ")
elif menu1 == ("t"):
while a == True: #Opens a loop called a
name=input("What is your name? ") #I asked the user their name here if name == (""):
if name.isdigit() or name == (""): #If the user enters a number or nothing something will happen
print("Incorrect Name") #This is the message that appears when the the name is a number or is nothing is incorrect
else:
a=False #Here i closed a loop
print("Welcome To my quiz " +str(name))#This is the welcoming message
while b == True:
group=input("What Class Are you A,B,C ") #Asks The User their class
if group == ("a") or group == ("b") or group == ("c") or group == ("A") or group == ("B") or group == ("C"):
break
else:
print("No such class!")
def addition(): #Here i define a function called addition
score=0 #Here the score shows score
first_number_a=random.randint(1,10) #The program gets a random number
second_number_a=random.randint(1,10) #The program gets another random number
question1=int(input("What is " +str(first_number_a)+ "+" +str(second_number_a)+ " ")) #Here the program asks the user a question
total_a=(first_number_a+second_number_a) #The answer to the question above
if question1 == total_a: #If answer is equal to the new variable c which is the answer to the question
print("Correct!") #This tells the user they got it correct
score=score+1 #This adds a point to the score
else: # if answer is not the variable
print("Incorrect!") #Here the program will print that the user is incorrect
print(total_a) #Here the program prints the correct answer if they got the question wrong
return score #This keeps the score safe
def multiplication():
score=0
first_number_m=random.randint(1,10)
second_number_m=random.randint(1,10)
question2=int(input("What is " +str(first_number_m)+ "*" +str(second_number_m)+ " "))
total_m=(first_number_m*second_number_m)
if question2 == total_m:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_m)
return score
def subtraction():
score=0
first_number_s=random.randint(1,10)
second_number_s=random.randint(1,10)
question3=int(input("What is " +str(first_number_s)+ "-" +str(second_number_s)+ " "))
total_s=(first_number_s-second_number_s)
if question3 == total_s:
print("Correct!")
score=score+1
else:
print("Incorrect!")
print(total_s)
return score
qw=["a" , "b" , "c"] #List Of Letters that will be randomly selected to then start a function
for i in range(0,10): #Thsi willrepeat the process listed below however many times in this example 10 times
random_Letter=random.choice(qw) #Selets a random letter
if random_Letter == "a": #If the random letter is a
score += addition() #It will use the function addition
elif random_Letter == "b":
score += multiplication()
elif random_Letter == "c":
score += subtraction()
print("your score is " +str(score)+ " Out of 10")#Tells the user their final score
if group == ("a") or group == ("A"): # If users input is as specified
f=open("ClassA.csv","a")#This opens a file
c = csv.writer(f)
c.writerow([name,score]) #Writes To A file
f.close() #This closes the file saving anything the user wrote to it
elif group == ("b") or group == ("B"):
f=open("ClassB.csv","a")
c = csv.writer(f)
c.writerow([name,score])
f.close()
elif group == ("c") or group == ("C"):
f=open("ClassC.csv","a")
f.write(name)
f.write(str(score)+ "\n")
f.close()

Categories