I have made a program based on a maths quiz and have saved the data of the files to a .txt file. If I wanted to save the files in a .csv file would i just chnage .txt to .csv? Here is my code :
import time
import math
import random#I am using this to allow me to randomly pick the symbol operation and to randomly generate numbers
print("Title:Arithmetic Quiz")#Tells the user what the program is.
print("*************************************************************")#This is a line to make the presentation clearer to the user.
#The code below shows the user an introduction of what the program is about.
print("This program will ask you to complete the arithmetic quiz.")
print("The program has 10 questions. You will recieve feedback after.")
print("____________________________________________________________")
#The line above prints a line across the page.
while True:#This creates an infinity loop
UserName = input("What is your name?:")#Ask the user for there name.
if not UserName.isalpha():#This is used to check if the user name is anything else apart from alphabetical letters.
print("Error!Please enter your name using letters. ") #warning if wrong if wrong input given
continue#Continues with the code when correct input given.
else:#It breaks out of the while loop and proceeds with the quiz
break
ClassSelection= input("Please enter what Class you are in?:1, 2 or 3")
ClassChosen=0
while ClassChosen==0:
if ClassSelection=="1":
ClassChosen=1
elif ClassSelection=="2":
ClassChosen=1
elif ClassSelection=="3":
ClassChosen=1
else:
print("You must write 1, 2, or 3.")
ClassSelection=input("Enter the class you are in")
print(UserName," welcome to the Arithmetic Quiz.")#Welcomes the user to the quiz.
print("____________________________________________")
print("The quiz will begin in 3 seconds")
time.sleep(2)
for i in range(0,3):# range between
print (3 - i)#counts down by one
time.sleep(1)#Delays for 1 second
print("Begin!")
print("*****************************************")
RecentStudent= [0,0,0]#This is a list with dummy values. The use of this is to save the last three score of the user.
def MathsQuiz():#I have used a function to make my code more efficient.
score=0#No questions have been answered correctly yet so score is set to zero
for questionNum in range(10):#I have used this to allow me to set my Parameters.
Num1= random.randint (1, 10)#Generates a random number between 1 and 10 for Num1.
Num2= random.randint (1, 10)#Generates a random number between 1 and 10 for Num2
Symbol = ["+","-","*"]#These are my operators used for the arithmetic of Num1 and Num2.
Operation = random.choice(Symbol)#This will randomly choose a operating symbol for a question
RealAnswer= int(eval(str(Num1)+Operation+str(Num2)))#This is used to work out the answer for the question.The evaluate is used to interpret the code as a str and calculate an answer.
#It will store the value of the Answer and call it when it is needed.
print("Please give an answer for:", Num1, Operation, Num2)#This is what makes the question and outputs it to the user by using the random functions.
UserAnswer = int(input("Enter your answer here:"))#This asks the user to enter their anser to the question.
if UserAnswer == RealAnswer:#This checks if the answer from the user is the same as the real answer.
score = score + 1#If the user gets the question right 1 should be added to the score.
print("You are correct! :D")#The program will congratulate the user.
print("_______________________________________________")
else:#If the users answer is not the same as the real answer then it will print a wrong message.
print("You are incorrect! :( ")#This tells the user that they got the question incorrect and tells the user the real answer.
print("The answer was", RealAnswer)
print("________________________________________________")#This will be used to split the quiz.
print()#This is used to format the quiz.
print("__________________________________________________")
print("Thank you for completing the quiz!")
print("Your Score is loading")
import time
time.sleep(2)
print(UserName,"In this test you achieved",score,"/10")#This tells the user the score they achieved in the maths test.
print()#This is used to format the code
del RecentStudent[0]
RecentStudent.append(score)
print("Your three most recent scores are:",RecentStudent)
print("********************************************************")
def Resit1():#This function is used to easily call place of the program such as in this case when resitting.
Resit1=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit1== "Yes" or Resit1=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
#It tells the user that they are finished
def Resit2():#This function is used to easily call place of the program such as in this case when resitting.
Resit2=input("Do you want to resit the test? Yes or No?:")#Asks the user if they would like to resit
#The variable will let user input whether they want to do the quiz again.
if Resit2== "Yes" or Resit2=="yes":# Checks the input of the user to the resit question
MathsQuiz()#This is used to call the quiz which will restart the quiz and allow them to retake the quiz.
print("Quiz Finished")#It tells the user that they are finished
MathsQuiz()#This will call the first function that has been set in the program.
Resit1()#This will call the Resit1 function when it is needed by the program.
Resit2()#This will call the Resit2 function when it is needed by the program.
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class1Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class1))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
elif ClassSelection=="2":#used to identify whether the ClassSelection is equal to 1.
Class2=[]#classA list is created and is empty.
Class2.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class2.append(UserName)#The name variable is appended as the second item.
Class2.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class2.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class2Scores.txt", 'a')#File opened called classAScores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class2))#Allows me to write the classA list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
elif ClassSelection==3:
Class3 = []#classA list is created and is empty.
Class3.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class3.append(UserName)#The name variable is appended as the second item.
Class3.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class3.append(RecentStudent)#The score variable is appended as the last item.
file = open("Class3Scores.txt", 'a')#File opened called class3Scores.
#It is a text file because I added ".txt"
#I used the mode 'a' because this allows me to append things to the file.
file.write(str(Class3))#Allows me to write the class3 list onto the file.
#Because the mode is append, it enables me to append a whole list to the file.
#the str() makes sure the list is interpreted as code as code can be appended.
#The list in its raw form will not append to the file.
file.write("\n")#Ensures the next pupils data is recorded on the row below.
file.close()#Closes the file so everything is saved.
This is my code would I need to change the bottom of the code to save the files in a .csv file. I tried doing a different method, but never got anywhere .
I suggest using the csv module. I've adapted your code to use it (there are a lot of ways you could make your life easier with your code, but let's focus on one issue at a time):
import csv
if ClassSelection=="1":#used to identify whether the ClassSelection is equal to 1.
Class1 = []#class1 list is created and is empty.
Class1.append("Student: ")#This text is added as the first item of the list.
#The text helps with presentation and makes the data more clear.
Class1.append(UserName)#The name variable is appended as the second item.
Class1.append("Latest 3 Scores: ")#This text is added so user knows the next item is score.
Class1.append(RecentStudent)#The score variable is appended as the last item.
with open('Class1Scores.csv', 'wb') as file:
writer = csv.writer(file)
writer.writerow(str(Class1))
writer.writerow("\n")
Gentle into to the csv module
Because we're using the with keyword, there is no need to call file.close()
For a more advanced way of doing this, you could use pandas to_csv
Looks like your Class1 is simply a list. Then you can say file.write(",".join(Class1)). But a more robust method is to use the csv module - https://docs.python.org/2/library/csv.html
Related
please can you tell me what is wrong with my code?
I have been trying to make this work it's not happening.
In python, I created a function that I want to search for students by their ID,
I need to make it specific and if it's not int like (str) I want it to show an error message.
I used while true, but it's not working, as it goes to the end of the function without checking the if condition.
Here is the code:
#open the file as student file (variable)
with open("studentfile.txt","r") as studentfile:
#call upon our reader (this allows us to work with our file)
studentfileReader=csv.reader(studentfile)
while True:
try:
idnumber=int(input("Please enter student ID :"))
break
except ValueError:
print("Invalid Input")
#for each row that is read by the Reader
for row in studentfileReader:
#and for each field in that row (this does it automatically for us)
for field in row:
#if the field is equal to the id number that is being searched for
if field ==idnumber:
#print the row corresponding to that ID number
print(row)
#Return to main menu for further options or to quit the program
menu()
Maybe there are other ways,
but if I put if statement without while true,
it's not going to show error message for the user inside the program
*I'm a newbie to python, I'm currently trying to create some random programs. I came accross this challenge. Would love to see how it can be solved, unfortunately I couldn't make this program.
I understand that we should use the random module and also the file handling functions in python.
If any detail is unclear I can re explain it
Write a program, which will help the user to generate exam tickets.
there are 2 files given . 1) with the exercises(exercises.txt):
it contains 30 exercises, each are already written on a new line.
2) we are given the students.txt file. Each line has a full name of a student. The program should allow the user to input the number of exercises which should be generated for the student. The new created ticket should have the students name with .txt file extension. The number must not exceed 30 exercises, if it does we should give them a new try to input the correct number. The exercises should be shuffled(randomized) .
import random
def logic():
number_input = int(input('sheiyvanet cifri'))
students_file = open('students.txt', 'r', encoding='utf8')
exercises_file = open('exercises.txt', 'r', encoding='utf8')
new_ticket_file = open('newTicket.txt', 'w')
while True:
if(number_input < 30):
new_ticket_file.write(str(random.shuffle(exercises_file.readlines())))
new_ticket_file.close()
break
else :
continue
logic()
Please do not simply provide a question and ask for it to be solved. Instead, show your current work and specify what is wrong with it.
Show examples of the text files, as in a few lines from each so that all viewers can properly understand it.
A good starting step is to write a piece of code that does only one thing. Eg:
Input a number.
The number must not exceed 30 exercises, if it does we should give them a new try to input the correct number.
Then write one that achieves a different part of your question. Try connecting these pieces. If it blows up or you really can't work it out, post a new question with the stuff you made and ask for help.
I have to code for a trouble shooting system, which uses keywords in the user input to provide a solution from a text file. I have a list of If statements, which directs the program to read specific lines from a textile and present them as solutions according to the specific Keywords present in the user input.
However, whatever the user input is, the program seems to display the first two lines in the text file (the program seems to be stuck on the first if statement).
Keywords = ['screen', 'display', 'audio', 'sound',]
Keywords2 = ['cracked', 'broken', 'water', 'frozen', 'unresponsive']
# Collecting the user's problem using user input
problem = input(str("Please enter your problem:")).split()# Assigns the user input to the variable 'progarm' and converts the user input into a string
# Presenting solutions to user if corresponding Keywords are present in the users input 'problem'
if any(i in Keywords or Keywords2 for i in problem): # This while loop checks that any of the keywords (i) in the lists (Keyword or Keywords2) are present in the user's input (problem), which has been splitted into individual words (indicated by spacing - i)
if Keywords[0] or Keywords[1] and Keywords2[0] or Keywords2[1] in problem:
read(0)
read(1)
elif Keywords[0] or Keywords[1] and Keywords2[3] or Keywords2[4] in problem:
read(3)
elif Keywords2[2] in problem:
read(2)
elif Keywords[2] or Keywords[3] and Keywords2[5] or Keywords2[6] in problem:
read(4)
read(0)
When I enter 'the phone fell in water', it should detect the Keyword 'water', which is Keywords2[2], and read the second line in the text file. Instead, it reads the lines directed in the first if statement.
Please enter your problem:My phone fell into water
Get it repaired at a reliable repair shop
You will need to buy a new screen and a new screen protector
Any suggestions to improve the code and make it work would be much appreciated!
I think the problem might be with the improper usage of in.
You may want to do something like this:
any(i in Keywords or i in Keywords2 for i in problem)
instead of
any(i in Keywords or Keywords2 for i in problem)
Similarly, for the inner if and elif statements.
For example:
if (Keywords[0] in problem or Keywords[1] in problem) and (Keywords2[0] in problem or Keywords2[1] in problem):
instead of
if Keywords[0] or Keywords[1] and Keywords2[0] or Keywords2[1] in problem:
OK, so what my program is all about is that the user has to solve a coded puzzle which gets read in from an external file. The user then guesses what letter matches up with the symbol in the coded puzzle and they can then add this to a list of clues.
One of the options in my program allows the user to check whether the clues they have entered are correct with the solved version. The solved version is read in from an external file and this is what needs to get checked with the list of clues.
So far I have a basic piece of code but what keeps on happening is that the output I get is that " You scored 0 out of 10" even though some of the pairings I have entered are correct.
My code so far for this section of code is this...
def check_clues():
count = 0
# TRIES TO OPEN FILE SOLVED.TXT
try:
with open('solved.txt') as r:
# READS THROUGH ALL THE LINES IN SOLVED.TXT
solved = r.readlines()
# WILL DISPLAY AN ERROR MESSAGE IF SOLVED.TXT IS NOT FOUND
except:
print("Error finding file")
# WILL TRY AND OPEN THE FILE 'clues.txt'
try:
with open('clues.txt') as r:
clues = r.readlines()
except:
print("Error finding ")
# GOES THROUGH BOTH THE USERS CLUES AND SOLVED.TXT TO SEE HOW MANY CLUES ARE THE SAME
for clue in clues:
if clue in solved:
count += 1
# Prints the amount of clues the user got right out of 10
print('You got:', count, 'correct!')
Below is what is in the solved.txt file:
ACQUIRED
ALMANAC
INSULT
JOKE
HYMN
GAZELLE
AMAZON
EYEBROWS
AFFIX
VELLUM
Below is what is in clues.txt
A#
M*
N%
However please note clues.txt is the list which the user can add to. So if the user decides to enter S and &, this will add to the clues.txt as S&
Below is the file words.txt which contains the list of coded words the user has to solve...
#+/084&"
#3*#%#+
8%203:
,1$&
!-*%
.#7&33&
#*#71%
&-&641'2
#))85
9&330*
I had a hand at this, using what you're provided. I believe this is what you're looking for provided you have all the files you listed. Basically I used the words.txt and solved.txt files and created a dictionary mapping all the symbols to their correct letters. Then I used that dictionary to compare each clue to see if they match. This would increment the count and you would get your correct output.
The problem with your original code is that you're simply searching if the clue is inside of the solved text file. For example, you search if your first clue A* is inside of the words text file. Obviously it isn't because there isn't a * in that file. So you need something to baseline/compare it to. Which is why in this case I created a dictionary. I also removed your try/except loops since your program should technically never run if a file is missing. In which case your exceptions will allow the program to keep running even if a file is missing producing multiple error outputs. It should stop if no files are found or be handled specifically, not allow it to keep running as it normally would. If you go that route, I'd also advise only using except WindowsError to avoid catching any other potential exceptions.
def check_clues():
# Dictionary to hold all of the symbol/letter combos
coded_dict = {}
# Go through each symbol/letter combination together
with open("words.txt") as fw, open("solved.txt") as fs:
for fw_line, fs_line in zip(fw, fs):
for fw_symbol, fs_letter in zip(fw_line.strip(), fs_line.strip()):
# Add the symbol/letter combination to the dictionary
coded_dict[fw_symbol] = fs_letter
correct_clues = []
with open("clues.txt") as fc:
for fc_line in fc:
# If the symbol is in the dictionary and the letter matches the symbol
if fc_line[1] in coded_dict and coded_dict[fc_line[1]] == fc_line[0]:
# Add a correct clue to your list
correct_clues.append(fc_line.strip())
print("You got a total of {0} correct: {1}".format(len(correct_clues), ", ".join(correct_clues)))
if __name__ == "__main__":
check_clues()
If you need me to elaborate on anything let me know.
ok so.. i'm trying to write a program that creates a dictionary of son:father entries and another dictionary that contains father:son entries. The program must present the user a menu with five options.
text file is this: john:fred, fred:bill, sam:tony, jim:william, william:mark, krager:holdyn, danny:brett, danny:issak, danny:jack, blasaen:zade, david:dieter, adamLseth, seth:enos
Problem Statement:
Write a program that creates a dictionary of son:father entries and another dictionary that contains father:son entries. Your program must present the user a menu with five options. The following is an example only:
Father/Son Finder
0 – Quit
1 – Find a Father
2 – Find a Grandfather
3 – Find a Son
4 – Find a Grandson
Option 0 ends the program.
Option 1 prompts the user for the name of a son. If the dictionary contains the son:father pair, the program displays the father. Otherwise, the program should tell the user it does not know who the father is.
Option 2 prompts the user for the name of a grandson. If the dictionary contains enough information, the program displays the grandfather. Otherwise, the program should tell the user it does not know who the grandfather is.
Option 3 prompts the user for the name of a father. If the dictionary contains the son:father pair, the program displays the son. Otherwise, the program should tell the user it does not know who the son is.
Option 4 prompts the user for the name of a grandfather. If the dictionary contains enough information, the program displays the grandson. Otherwise, the program should tell the user it does not know who the grandson is.
The program must create the dictionary structure and populate it from data contained in a file provided to you. In addition, the program must continue to ask the user for a menu choice until the user chooses to quit.
I have this thus far. I haven't gotten very far in it...
sons_fathers = {}
fathers_sons = {}
#open filename: names.dat
fo = open("names.dat", "r")
data = fo.read()
print (data)
for line in fo:
here is the flow chart: ![Flow chart][1]
https://jsu.blackboard.com/bbcswebdav/pid-2384378-dt-content-rid-3427920_1/xid-3427920_1
Thanks for the help. I need it lol.
Let's hope nobody give you an exact solution to this homework.
Here some hints, you need to know what you can do with string, string.split() will help you a lot. Also, read about what you can do with dictionary. You will also need the raw_input function
The rest is simple programming. Good luck.
How you describe your solution, I don't think a dictionary is what you want for this.
The keys must be unique.
# wont work, keys aren't unique
father_son = {'danny':'brett', 'danny':'issak', 'danny':'jack'}
You could however try a dictionary with a list as the value:
father_son = {'danny':['brett','issak', 'jack']}
if 'danny' in father_son.keys() and 'brett' in father_son['danny']:
#do something
Or you could use a list of 2-tuples that stores the pairs:
father_son = [('danny', 'brett'), ('danny', 'issak'), ('danny', 'jack')]
if ('danny', 'brett') in father_son:
#do something
sons_fathers = {} # one father per son
fathers_sons = {} # one or many sons per father, use list or
# set for the values
with open("names.dat", "r") as fo: # use context manager to close file automatically
for line in fo: # ?? is there only one line, or one pair per line??
# do something with line
# assume you extracted "son" and "father"
sons_fathers[son] = father
if father in fathers_sons:
fathers_sons[father].add(son)
else:
fathers_sons[father] = {son}