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.
Related
This question already has answers here:
Simple while loop until break in Python
(3 answers)
Closed 3 years ago.
The idea of the program is as follows;
1) Users are asked to select either 1 or 2
2) If one is selected, the user is prompted to enter the score. If 2 is selected the user should be able to view the scores.
3) After the user has entered or viewed a score they should be able to add another score or view scores. Typing Y should bring them back to the beginning of the program. N Should say they can close the program, or close it.
At the moment, the number selections work for the score entry but I'm not sure how to make it so that the program restarts is the user wishes to add or view more scores.
Here's the program in its current state;
print ("Type 1 to a add a score.")
print ("Type 2 to view scores.")
action = input("Please type a number: ")
if action == "1":
print ("Enter a score?")
eventscore = int(input ("Please type their score: ")
score = eventscore
f = open("scores.txt", "a")
f.write(eventscore)
f.write("\n")
f.close()
print("The score for" , score, "has been saved.")
elif action == "2":
print ("Type 1 to view all scores.")
print ("Type 2 to view scores for a specific team.")
scorecheck = input("Please type a number: ")
if scorecheck == "1":
f = open("scores.txt", "r")
for line in f:
allscores = f.readlines()
print(allscores)
f.close
elif scorecheck == "2":
teamcheck= input ("Please enter the team name: ")
while True:
while True:
answer = input('Want to add a new score or view existing scores? (Y/N): ')
if answer in ('Y', 'N'):
break
print ("Please enter 'Y' or 'N'.")
if answer == 'y':
continue
else:
print ("You can now close the program.")
break
Currently the program is able to start, ask the user to pick if they want to add or view scores and then ask if they want to add/view more or close the program. If the user enters 'Y' the program should completely restart, but it still needs to have the loops for adding/viewing. If they type N the program should close.
Any help would be greatly appreciated as I don't know how to get a loop on the overall program when it already contains multiple loops.
while True:
ans = input("Enter option (y, Y):")
if ans == "":
print("finished - exit program")
break
if ans in ['y', 'Y']:
askQuestion()
def askQuestion():
...top bit of your code
On my mobile so just peudocode provided. There's likley a better way than this. As said in chess if you find a good move look for a better one.
Also its canonical to write opening a file inside a with context managerlike so:
with open('filename.txt', 'a') as f:
f.write..etc
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
My code is supposed to only accept letters (for example Jack would be accepted, and jack1 would not be accepted).
It prompts the user for their first and last name then stores them. Once I had written the code for the first name, I tested it to see if I had written the code correctly for the first name, but it kept giving me this error .
In the answers can you please show how to make this work with only numbers being allowed?
Code
import random
operators = ["+", "-", "*"]
def greeting(first_name, last_name):
print ("Hello", first_name + " " + last_name)
Play = input('Are you ready to begin?')
if Play == 'yes':
print("Great", first_name + ", lets begin")
else:
greeting(first_name, last_name)
def Players_input():
print ("Welcome to the Arithmetic Quiz")
first_name = input("Please enter your first name: ")
if all(x.isalpha() or x.isspace() for x in first_name):
last_name = input("Please enter your last name: ")
greeting(first_name, last_name)
else:
print("Only alphabetical letters and spaces: no")
Players_input()
score = 0
for i in range(10):
first_number = random.randint(1,12)
second_number = random.randint(1,12)
op = random.choice(operators)
print (first_number, op, second_number, " = ?")
users_answer = int(input())
if op == "+":
right_answer = first_number + second_number
elif op == "-":
right_answer = first_number - second_number
elif op == "*":
right_answer = first_number * second_number
if users_answer == right_answer:
print("Well Done!")
score += 1
else:
print ("Sorry but thats the wrong answer, the right answer is: " + str(right_answer) + ". Better luck next time")
print (first_name, "Your final score in the Arithmetic Quiz is", str(score), "out of 10")
The answer for the first problem:
You never defined first_name outside of Players_input. This value is just stored inside the function, and get's deleted afterwards. (more about this in the link added by gjttt1)
There are two ways to solve this:
You could make first_name global. But this is a bad style, so I wouldn't use this option. You would add global first_name at some point in Players_input, before it is written to (so either before or directly after the first print call)
You could return first_name, this is the preferred way. Add a return first_name at the end of Players_input, and replace Players_input() with first_name = Players_input().
The answer to the second problem:
Just use this function instead of int(input()) (replace this line with int_input()):
def int_input(prompt="", error_message="You didn't enter an integer!"):
while True: # repeat this until the function returns
inp = input(prompt) # get the input after autputting the prompt.
try: # Try to...
return int(inp) # turn it into an integer. If it works, return it.
except ValueError: # If it didn't work, it raised a ValueError. In this case...
if error_message: # print the error_message if it is not "", false or None.
print(error_message)
Then you have a third problem: You should just use lowercase letters in function names, to distinguish them from classes. This is just about your style, but it'll certainly help to develop a good, clear coding style.
I hope I could help,
CodenameLambda
The first_name variable is out of scope when you are trying to use it. It belongs to the Players_input() function.
Read this article on scoping to get more of an idea of what is happening
Look at the error. It's telling you that the first_name variable is not defined. This is because it is a local variable in the Players_input function and cannot be used elsewhere. Variables that are defined inside a function are put on the stack in memory and are destroyed when that stack frame is pushed off the stack. You call this 'going out of scope'.
I recommend that you look up information about the scope of variables.
you can declare first_name=('hi') earlier in the code and then when you call it in as an input function you can write it like:
first_name=str(input('Please enter your first name: '))
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.
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)
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()