I am trying to get my program to output two variables to a text file after it finishes running something but all I get is the folder and no text files inside of it. Here is the code in question:
I have edited to include the entire program.
import random #needed for the random question creation
import os #needed for when the scores will be appended to a text file
#import csv #work in progress
answer = 0 #just to ensure a strage error isn't created by the input validation (since converting to a global variable isn't really needed)
global questionnumber #sets the question number to be a global variable so that
questionnumber = 0
global score
score = 0
global name
name = "a"
def check_input(user_input): #used to verify that input by user is a valid number
try: #the condition that does the checking
answer = int (user_input)
except ValueError: #what to do if the number isn't actually a number
return fail() #calls the failure message
return answer #sends the answer back to the rest of the program
def fail(): #the failure message procedure defined
print("That isn't a whole number! Try again with a different question") #tells the user what's going on
global questionnumber #calls the global variable for this procedure
questionnumber = questionnumber - 1 #allows the user, who made a mistake, a second chance to get it right
def questions(): #the question procedure defined
global name
name=input("Enter your name: ") #gets the user's name for logging and also outputting messages to them
print("Hello there",name,"! Please answer 10 random maths questions for this test!") #outputs welcome message to the user
ClassOfStudent=input("Which class are you in?") #gets the user's class for logging
finish = False
while finish == False: #only occurs if "finish" isn't set to true so that the questions asked don't exceed ten
global questionnumber #calls the global variable
global score
choice = random.choice("+-x") #uses the random function to choose the operator
if questionnumber < 10 | questionnumber >= 0: #validation to ensure the question number is within ten
number1 = random.randrange(1,12) #uses random numbers from the random function, above 1 and below 12
number2 = random.randrange(1,12) #same as the abovem for the second number
print((number1),(choice),(number2)) #outputs the sum for the student to answer
answer=check_input((input("What is the answer?"))) #asks for the student's answer
questionnumber = questionnumber + 1 #adds one to the numebvr of questions asked
if choice==("+"): #if the ramdomly generated operator was plus
correctanswer = number1+number2 #operator is used with the numbers to work out the right answer
if answer==correctanswer: #checks the studen't answer is right
print("That's the correct answer") #if it is, it tells the student
score = score + 1 #adds one to the score that the user has
else:
print("Wrong answer, the answer was",correctanswer,"!") #if the answer is wrong, it tells the student and doesn't add one to the score
if choice==("x"): #essentially the same as the addition, but with a multiplicatin operator instead
correctanswer = number1*number2
if answer==correctanswer:
print("That's the correct answer")
score = score + 1
else:
print("Wrong answer, the answer was",correctanswer,"!")
elif choice==("-"): #essentially the same as the addition, but with a subtraction operator instead
correctanswer = number1-number2
if answer==correctanswer:
print("That's the correct answer")
score = score + 1
else:
print("Wrong answer, the answer was",correctanswer,"!")
else: #if the number of questions asked is ten, it goes on to end the program
finish = True
else:
print("Good job",name,"! You have finished the quiz") #outputs a message to the user to tell them that they've finished the quiz
print("You scored " + str(score) + "/10 questions.") #ouputs the user's score to let them know how well they've done
#all below here is a work in progress
#Create a new directory for the scores to go in, if it is not there already.
if os.path.exists("Scores") == False:
os.mkdir("Scores")
os.chdir("Scores")
if ClassOfStudent==1: #write scores to class 1 text
file_var = open("Class 1.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==2: #write score to class 2 text
file_var = open("Class 2.txt",'w+')
file_var.write(name, score)
file_var.close()
if ClassOfStudent==3: #write score to class 3 text
file_var = open("Class 3.txt",'w+')
file_var.write(name, score)
file_var.close()
questions()
ClassOfStudent is a string rather than a number, so none of the code that writes to the file will get executed. You can easily verify that by adding a print statement under each if so you can see if that code is being executed.
The solution is to compare to strings, or convert ClassOfStudent to an i teger.
Use print(repr(ClassOfStudent)) to show the value and type:
>>> ClassOfStudent = input("Which class are you in?")
Which class are you in?2
>>> print(repr(ClassOfStudent))
'2'
Using input() in Python 3 will read the value in as a string. You need to either convert it to an int or do the comparison against a string.
ClassOfStudent = int(input("Which class are you in?")
should fix your problem.
first you have a problem with the "". you have to correct the following:
if ClassOfStudent==2: #write scores to class 1 text
file_var = open("Class 2.txt",'w+')
file_var.write("name, score")
file_var.close()
if ClassOfStudent==3: #write scores to class 1 text
file_var = open("Class 3.txt",'w+')
file_var.write("name, score")
file_var.close()
notice that I added the "" inside the write.
In any case, I think what you want is something like:
file_var.write("name %s, score %s"%(name,score)). This should be more appropriate.
Related
I'm trying to make a guessing game with three questions and three guesses total but I can't get the value from the inputs so I can't progress any further. Rough draft for my code
guesses = 3
def guess():
if guesses >= 0:
alive = True
else:
print("You Failed")
Q1 = "What is 1+1"
Q2 = ""
Q3 = ""
def retry():
input("Wrong Answer Try Again")
def questions():
Q1 = input("What is 1+1")
def answer():
if Q1 == "2":
print("Q2")
else:
retry()
if retry() == 2:
print("Q2")
questions()
answer()
I've tried using lists functions if statements but I can't get the value of the inputs no matter what as its always a local variable.
Here's a simple approach to this problem.
The crucial part is the list of 2-tuples. Each tuple maintains a question and the correct answer to that question. By adding more questions and answers to the list your program can become more elaborate without having to change anything else in the code.
Something like this:
Questions = [("What is 1+1", "2"), ("What is 2+2", "4"), ("What is 3+3", "6")]
score = 0
TRIES = 3
for q, a in Questions:
for _ in range(TRIES): # number of tries allowed
if input(f'{q}? ').lower() == a.lower() :
score += 1
print('Correct')
break
else:
print("Incorrect please try again")
else:
print('Maximum tries exceeded')
print(f'Your final score is {score}')
I'm working on a project/exercise where I need to use OOP in Python to create a Grade Book. I've been learning Python and working with 3.8.3 for about 6 weeks now, so I'm still fairly new. The grade book has a basic menu where you can add an assignment, quiz, and final exam grades. I must use a class with an empty list for both the quiz and assignment grades. I did a rough draft of the code after reading a bit on OOP, and managed to get the class to function without using attributes and only one method as below:
class GradeBook:
def main_function():
quiz_scores = []
assignment_scores = []
while True:
try:
quiz_grade = float(input('Please enter a grade for the quiz, or press Enter to stop adding grades: '))
quiz_scores.append(quiz_grade)
except:
break
while True:
try:
assignment_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
assignment_scores.append(assignment_grade)
except:
break
print (quiz_scores)
print (assignment_scores)
print ('time for totals and averages')
quiz_total = sum(quiz_scores)
assignment_total = sum(assignment_scores)
print ('quiz total ' + str(quiz_total))
print ('assign total ' + str(assignment_total))
if len(quiz_scores) > 0:
quizScoreAverage = sum(quiz_scores)// len(quiz_scores)
else:
quizScoreAverage = 0
if len(assignment_scores) > 0:
assignmentScoreAverage = sum(assignment_scores) // len(assignment_scores)
else:
assignmentScoreAverage = 0
print ('quiz average ' + str(quizScoreAverage))
print ('assign average ' + str(assignmentScoreAverage))
GradeBook.main_function()
Here is where I am running into my issues. I need to split the code up into several methods/functions, one for quiz scores, one for assignment scores, one that will store the final exam score and do nothing more, and one for getting the current grade/average. I've been searching and searching but have hit a wall. The code works up until I attempt to append the user's input to the list in the class. Again this is just a rough draft of the code as follows:
class GradeBook:
# Need this at attribute level for all instances to acccess as there will be an instance the pulls the list to calculate overall grade
assignment_scores = []
# quiz_scores = [] ### - This is the other list that will also be used for the grade
def assignGrade(self, score):
self.score = score
self.assignment_scores.append(score)
#####################################################
'''
This will be a duplicate of the above code but will use values to store quiz grades instead
def quizGrade(self, score):
self.score = score
self.quiz_scores.append(score)
'''
#####################################################
while True:
try:
assignment_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
# Program works just fine up until this point. My issue is here. Trying to feed the user input into the class instance
# to update the class list that is stored as an attribute. Instead of appending it seems to throw an error,
# because it doesn't continue the try loop for input and after the break when the list is printed, no values are shown
assignment_grade = GradeBook.assignGrade(assignment_grade) # <------- THIS IS THE PROBLEM CHILD OF MY CODING
except:
break
#####################################################
''' This block will be used to get input for the quiz grade to append to quiz scores list
while True:
try:
quiz_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
quiz_grade = GradeBook.quizGrade(quiz_grade) #not sure if this is right?
except:
break
'''
#####################################################
I guess I'm just not getting a good grasp on the whole idea of sending information from one instance to another. Any input is greatly appreciated. My plan is once it all gets figured out I just need to plug in the code to my final draft here:
class GradeBook:
# Initializes empty list to store quiz and assignment grades
quiz_scores = []
assignment_scores = []
#####################################################
def quizScore(self, score)
# lines of code to append user input to quiz list for reference in class
#####################################################
def assignScore(self, score)
# lines of code to append user input to assignment list for reference in class
#####################################################
def finalScore(self, score)
# line of code to store the final exam grade for reference in the class
#####################################################
def currentAverage(self)
if len(self.assignment_scores) > 0:
assignmentScoreAverage = sum(self.assignment_scores) // len(self.assignment_scores)
else:
assignmentScoreAverage = 0
if len(self.quiz_scores) > 0:
quizScoreAverage = sum(self.quiz_scores) // len(self.quiz_scores)
else:
quizScoreAverage = 0
currentGrade = (0.4 * self.final_grade) + (0.3 * quizScoreAverage) + (0.3 * assignmentScoreAverage)
return currentGrade
#####################################################
print('''
Grade Book
0: Exit
1: Enter assignment grade
2: Enter quiz grade
3: Enter final exam grade
4: Display current grade
''')
while True:
try:
selection = int(input('Please enter a choice: '))
if selection == 0:
quit
elif selection == 1:
while True:
try:
assignment_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
GradeBook.assignScore(assignment_grade)
except:
break
elif selection == 2:
while True:
try:
quiz_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
GradeBook.quizScore(quiz_grade)
except:
break
elif selection == 3:
while True:
try:
final_grade = float(input('Please enter a grade for the assignment, or press Enter to stop adding grades: '))
GradeBook.finalScore(final_grade)
except:
break
elif selection == 3:
final_grade = float(input('Please enter a grade for the final exam: '))
if isdigit(final_grade)
GradeBook.finalScore(final_grade)
else:
print('Please check your input and try again.')
elif selection == 4:
print(GradeBook.currentAverage())
else:
print('Please check your input and try again.')
continue
(Please, use snake case for all your code, including methods. Camel case should only be used for classes) In python I would recommend creating a module(file) without class for your main function. You are using the assignGrade method as a class method. Actually, you never even created an instance of your class! To create an instance, you should call the class as follows:
my_grades = GradeBook()
Now, my_grades is "a variable"(an instance) that contains all the properties(attributes) you defined for your class. You can access them as follows:
my_grades.assignment_scores
Your loop will fail because you have not passed the self argument to the function you pointed as the problem. In python, all instance methods start with the self argument, but it will be the variable(instance) before the dot. So, you should call it from an instance of your class and not from the class itself. Using the one I created from the first example, you can change the line to:
my_grades.assignGrade(assignment_grade)
That should do.
Instead of creating and calling a main_function, in the module add the following:
if __name__ == '__main__':
... # Create your instances and manipulate them here
So following the guidelines that were provided to us, as well as the example inputs, I have the program working as intended. Since this was just an introduction class, we didn't get into using methods in separate files, so I did not use:
if __name__ == '__main__':
However, I would like any comments on it like readability and other coding practices. Working code below:
# Programmed by thelastesquire92
# Programming Assignment 7 - Grade Book App
# SEC290.B2.32789
'''
Program that focuses on Object Oriented Programming.
The user is presented with simple text menu, and following
input prompts they are allowed to enter grades for quizzes,
assignments, and a final exam. The program then calculates
the average grade based off of these inputs.
'''
class GradeBook:
# Initializes empty list for quiz and assignment grades, sets default final score to 0
quiz_scores = []
assignment_scores = []
final_exam_score = 0
#####################################################
# Adds grade input to list of quiz scores
def quiz_score(self, score):
self.quiz_scores.append(score)
#####################################################
# Adds grade input to list of assignment scores
def assignment_score(self, score):
self.assignment_scores.append(score)
#####################################################
# Updates value of final exam score
def final_score(self, score):
GradeBook.final_exam_score = score
#####################################################
# Calculates current grade average
def current_average(self):
if len(GradeBook.assignment_scores) > 0:
assignment_score_average = sum(GradeBook.assignment_scores)\
// len(GradeBook.assignment_scores)
else:
assignment_score_average = 0
if len(GradeBook.quiz_scores) > 0:
quiz_score_average = sum(GradeBook.quiz_scores)\
// len(GradeBook.quiz_scores)
else:
quiz_score_average = 0
current_grade = (0.4 * GradeBook.final_exam_score)\
+ (0.3 * quiz_score_average)\
+ (0.3 * assignment_score_average)
return current_grade
#####################################################
# Prints out the menu for user
menu = ('''
Grade Book
0: Exit
1: Enter assignment grade
2: Enter quiz grade
3: Enter final exam grade
4: Display current grade
''')
print(menu)
#####################################################
# Main body of program that loops until user selects option to exit
while True:
# Creates instance of GradeBook
my_grades = GradeBook()
try:
selection = int(input('\nPlease enter a choice: '))
#####################################################
# Option 0 that exits the program
if selection == 0:
break
#####################################################
# Option 1 that allows input for assignment grades
elif selection == 1:
while True:
try:
assignment_grade = float(input('\nPlease enter a grade for the assignment: '))
my_grades.assignment_score(assignment_grade)
break
except:
print('\nPlease check your input and try again.')
continue
#####################################################
# Option 2 that allows input for quiz grades
elif selection == 2:
while True:
try:
quiz_grade = float(input('\nPlease enter a grade for the quiz: '))
my_grades.quiz_score(quiz_grade)
break
except:
print('\nPlease check your input and try again.')
continue
#####################################################
# Option 3 that allows input for final exam grade
elif selection == 3:
while True:
try:
final_grade = float(input('\nPlease enter a grade for the final exam: '))
my_grades.final_score(final_grade)
break
except:
print('\nPlease check your input and try again.')
continue
#####################################################
# Option 4 that displays current grade average
elif selection == 4:
average = my_grades.current_average()
print('\nYour current grade average is: ' + str(average))
else:
print('\nPlease check your input and try again.')
continue
except:
print('\nPlease check your input and try again.')
print(menu)
continue
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.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am creating an arithmetic quiz, but my code isn't writing the scores to a csv file in excel. Can you help me? What do I need to fix?
I have 3 blank csv files, but there is not data in them.
Here's my code...
import random#this imports random numbers
import csv#this imports a csv
score=0#this sets the score to be 0 at the start
answer=0#this sets the answer to be 0, before it is formatted with the different questions
operators=("+","-","*")#this gives three options to select from for a random operation in each question
valid=('gold','platinum','diamond')
#_______________________________________________________________________________________________________________________________
def main():
global student_name
global class_name
print("ARITHMETIC QUIZ")#this prints the title "ARITHMETIC QUIZ"
student_name=input("\nWhat is your name? ")#this asks the user to input their name
#it stores the student's name in the variable 'student_name'
class_name=input("What class are you in? ")#this asks the user to input their class name
#it also stores the class name in the variable 'class_name'
if class_name=="gold":
quitting()
elif class_name=="platinum":
quitting()
elif class_name=="diamond":
quitting()
else:
print("That is not a valid class name")
print("Please choose from 'gold', 'platinum' or 'diamond'")
class_name=input("Please enter your correct class name below: \n")
#_______________________________________________________________________________________________________________________________
def quitting():
quitting=input("\nDo you want to exit the quiz? (enter 'yes' or 'no') ")
#this asks the users if they want to exit the program.
quitting = quitting.lower().replace(' ', '')
#this converts all the characters to lower case, and it also removes and spaces
if quitting=='yes':#this checks if they wrote 'yes'
print("The program will end.")
#if they did write yes, the above line of text will be printed
exit()#and then the program will end.
else:
quiz()
#_______________________________________________________________________________________________________________________________
def quiz():
global score
for i in range(10):
#this creates a forLoop that will repeat X times, depending on the number inside the brackets
#in this case, it will repeat the following function 10 times
num1=random.randint(1,20)#this chooses a random number for the variable num1
num2=random.randint(1,20)#this chooses a random number for the variable num2
operator=random.choice(operators)#this chooses a random operation from the options of '+','-' and '*'.
if operator=="+":
answer=num1+num2#if the operator was '+', the answer would be the sum of num1 and num2
elif operator=="-":
num1,num2 = max(num1,num2), min(num1,num2)#this makes num1 larger than num2 to make subtraction easier
answer=num1-num2#else if the operator was '-', the answer would be num1 takeaway num2
elif operator=="*":
answer=num1*num2#else if the operator was a '*', the answer would be the product of num1 and num2
try:
temp=int(input("\nWhat is " + str(num1) + operator + str(num2) + "? "))#the variable temp changes for each inputted answer
#this converts the integers 'num1' and 'num2' into strings
#because integers and strings can't be in the same line of code
#this asks the user the question
if temp==answer:#this cheks if the answer is correct
print("Well Done " + student_name + "! The answer is correct.")
score=score+1
#if it is correct, it will print "Well Done! The answer is correct".
#it will also add 1 to the score
else:
print("Incorrect. The answer was " + str(answer))#this converts the variable 'answer' into a string
score=score#this makes sure that the score remains the same as last time
#if the answer is not correct, it will print "Incorrect" and output the correct answer
except ValueError:
print("Invalid answer. Please use integers only!")
#this will be printed if the user inputted anything other than an integer, like a string
print("\nThank you " + student_name + "! You scored " + str(score) + " out of 10 in this quiz.")
#this converts the variable 'score' into a string
#and this prints thank you and the student's score out of ten
#_______________________________________________________________________________________________________________________________
def find_user_in_class():
if class_name == 'gold': #if what the user's input for the class name was 'gold'...
appendFile = open('goldclassscores.csv', 'a') #it opens the csv file, named 'goldclassscores'
elif class_name == 'platinum':#if what the user's input for the class name was 'platinum'...
appendFile = open('platinumclassscores.csv', 'a')#it opens the csv file, named 'platinumclassscores'
elif class_name == 'diamond':#if what the user's input for the class name was 'diamond'...
appendFile = open('diamondclassscores.csv', 'a')#it opens the csv file, named 'diamondclassscores'
for line in appendFile: #looks through each column of the csv
user = {}
(user['student_name']) = line.split
if student_name == user['student_name']:
appendFile.close()
return (user)
appendFile.close()
return({})
#_______________________________________________________________________________________________________________________________
def write_to_csv():
if class_name == 'gold':
goldcsv = open('goldclassscores.csv', 'a')
goldcsv.write('\n')
goldcsv.write(student_name)
goldcsv.write(str(score))
goldcsv.close()
print('Your score has been saved.')
elif class_name == 'platinum':
platinumcsv = open('platinumclassscores.csv', 'a')
platinumcsv.write('\n')
platinumcsv.write(student_name)
platinumcsv.write(str(score))
platinumcsv.close()
print('Your score has been saved.')
elif class_name == 'diamond':
diamondcsv = open('diamondclassscores.csv', 'a')
diamondcsv.write('\n')
diamondcsv.write(student_name)
diamondcsv.write(str(score))
diamondcsv.close()
print('Your score has been saved.')
#_______________________________________________________________________________________________________________________________
if __name__=="__main__": main()
Please help me!!
You are not calling your write_to_csv() function anywhere. Try calling it when the quiz is done.
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()