My goal is to have two programs. One will ask the user to input a test name and then a test score repeatedly until the user hits enter. This information will be stored in a .txt file. The second program will pull the information from the .txt file and print it into a format like something below with the test scores and a final average:
Reading six tests and scores
TEST SCORE
objects 88
loops 95
selections 86
variables 82
Average Test Score is
So far I have this for the first program to generate the txt document:
def main():
myfile = open('test.txt', 'w')
test = input('Please enter test name or enter to quit ')
while test != '':
score = int(input('Enter % score on this test '))
myfile.write(test + '\n')
myfile.write(str(score) + '\n')
test = input('Please enter test name or enter to quit ')
myfile.close()
print('File was created successfully')
main()
The second program looks like this and is in rough shape:
def main():
f = open('test.txt', 'r');
text = f.read();
f.close()
Main()
Any suggestions or examples? I’m really struggling.
First program / write
I recommend using \t between name and score instead of \n.
like this...
name1 100
name2 75
name3 10
...
It will help you when you read a file.
name, score = file.readline().split('\t')
Additionally, How about check input validation? whether input value in the valid range.
Second program / read
Using format is a nice way.
total, count = 0, 0
fmt = "{name:<16}\t{score:<5}"
header = fmt.format(name="TEST", score="SCORE")
print(header)
while ( ... ):
total += score
count += 1
... # read file
row = fmt.format(name=name, score=score)
print(row)
print("Average Test Score is ", total/count)
Related
I'm new to python and i have several questionable things that are happening. I am trying to figure out what i'm doing wrong with this problem:
This exercise assumes you have completed Programming Exercise 7, Random Number File
Writer. Write another program that reads the random numbers from the file, display the
numbers, and then display the following data:
• The total of the numbers
• The number of random numbers read from the file
Writing the file:
import random
def main():
randomcount = int(input('How many numbers should i generate?'))
randomfile = open('randomnumber.txt', 'w')
total = 0
for numbers in range(randomcount):
number = random.randint(1,100)
total+= number
randomfile.write((str(number)) + '\n')
randomfile.write((str(total)) + '\n')
randomfile.close()
print('File updated')
main()
output:
How many numbers should i generate?5 (enter)
file updated - **Question 1**
file updated | ---- this is new.. while doing
file updated - trial and error this started
repeating. First 2 times then
after awhile 3 times.
Refreshed kernel and outputs
still does this
reading the file: <-- #main issue
def main():
randomfile = open('randomnumber.txt','r')
contents = randomfile.readline()
while randomfile !='':
total = randomfile.readline()
contents = contents.rstrip('\n')
total = total.rstrip('\n')
print(contents)
contents = randomfile.readline()
print('total: ',total)
randomfile.close()
main()
output:
90 -
22 |
17 |--- Randomly generated
2 |
75 -
**Question 2**
<--- print('total: ', total) not showing up
-
|
|
|
. **Question 3**
. <--------- Space goes on forever like if its printing
. space. so much that theres a scroll bar just
. for empty space. if i try to scroll all the
| way to the bottom so that i can see if maybe
| its printing at the end i never reach the end
| of it because for some reason the program
- keeps adding more and more space.
The problem is that the line that writes the total is being execute each iteration. That's why there are double the number of lines as there are generated numbers.
The solution is unindenting that line, which I did here:
import random
def main():
randomcount = int(input('How many numbers should i generate?'))
randomfile = open('randomnumber.txt', 'w')
total = 0
for numbers in range(randomcount):
number = random.randint(1,100)
total+= number
randomfile.write((str(number)) + '\n')
randomfile.write((str(total)) + '\n') # <<<<<<<<<<<<<<This line was indented, it is fixed now.
randomfile.close()
print('File updated')
main()
EDIT: Fixing the read function:
def main():
randomfile = open('randomnumber.txt', 'r')
lines = randomfile.readlines()
total = 0
for line in lines:
if line is lines[-1]:
print(f"Total: {line.replace('\n', '')}") #Since the write function includes the total as the last line, you don't need to calculate here.
else:
print(line.replace('\n', ''))
main()
change readline to readlines hopefully, that should work
Clearly the issue is that in your first line you opened with a single quote ' and closed with a double quote ". Change:
def main():
randomcount = int(input('How many numbers should i generate?"))
to:
def main():
randomcount = int(input('How many numbers should i generate?'))
I restructured my code and made it a for loop instead of a while loop. You don't need to rstrip numbers that are being converted to int. Put the accumulator in the input file portion instead of the output file portion. Mae the code cleaner and it works!
import random
def main():
randomcount = int(input('How many numbers should i generate?'))
randomfile = open('randomnumber.txt', 'w')
for numbers in range(1,randomcount + 1):
numbers = random.randint(1,100)
randomfile.write(str(numbers) + '\n')
randomfile.close()
randomfile = open('randomnumber.txt','r')
total = 0
for numbers in randomfile:
numbers = int(numbers)
total+= numbers
print(numbers)
print('total',total)
main()
The following is the problem and i have written the code.Can someone have the answer code shortened?
Suppose the file studentdata.txt contains information on grades students earned on various
assignments. Each line has the last name of a student (which you can assume is one word) and
the numeric grade that student received. All grades are out of 100 points. Students can appear
multiple times in the file.
Here’s a sample file:
Arnold 90
Brown 84
Arnold 80
Cocher 77
Cocher 100
Write a function that reads the data from the file into a dictionary. Then continue prompting the
user for names of students. For each student, it should print the average of that student’s grades.
Stop prompting when the user enters the name of a student not in the dictionary.
A sample run for the given file:
Enter name: Arnold
The average for Arnold is: 85.0
Enter name: Brown
The average for Brown is: 84.0
Enter name: Cocher
The average for Cocher is: 88.5
Enter name: Doherty
Goodbye!
Here is my code :
import os
PATH="C:/Users/user/Desktop/studentdata.txt"
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
d=fd.read()
p1=r"\b[A-za-z]+\b"
p2=r"\b[0-9]+\b"
l1=re.findall(p1,d)
fd=open("C:/Users/user/Desktop/studentdata.txt","r")
l2=re.findall(p2,d)
d={}
for key,val in list(zip(l1,l2)):
if key not in d:
d[str(key)]=int(val)
else:
d[str(key)]+=int(val)
for key in d:
d[key]=d[key]/l1.count(key)
while True:
key=input("Enter name:")
if key not in d:
print("Goodbye!")
break
print("the average for "+key+" is: "+str(d[key]))
PATH = "C:/Users/user/Desktop/"
FILE = "studentdata.txt"
with open(PATH + FILE, 'r') as fp:
lines = fp.readlines()
notes_with_students = {}
for line in lines:
student = line.split()[0]
note = line.split()[1]
if student not in notes_with_students:
notes_with_students.setdefault(student, [int(note), 1])
else:
notes_with_students[student][0] += int(note)
notes_with_students[student][1] += 1
while True:
student = input("Enter name: ")
if student not in notes_with_students:
print("Goodbye!")
break
print("The average for {} is: {}".format(student, notes_with_students[student][0]/notes_with_students[student][1]))
This can be useful.
Context: I have written a program that asks the user to enter the name and score (integer) for a user-defined quantity of players. The program then formats, slices and stores the values in a file named golf.dat
Issue: I am trying to expand my program to allow it to identify the player with the lowest score and print the name and score of the lowest scorer.
My code:
def playerDataInput(playerQuantity):
outputFile = open("golf.dat", "w")
for currentPlayer in range (1, playerQuantity + 1):
playerName = (input("Please enter player " + format(currentPlayer, "d",)+"'s name: "))
playerScore = (input("Please enter player " + format(currentPlayer, "d",)+"'s score: "))
outputFile.write(playerName + "\n")
outputFile.write(str(playerScore) + "\n")
outputFile.close()
def playerDataOutput():
inputFile = open("golf.dat", "r")
playerName = inputFile.readline()
while playerName != "":
playerScore = inputFile.readline()
playerName = playerName.rstrip("\n")
playerScore = playerScore.rstrip("\n")
print(playerName + ("'s score was:"), playerScore)
playerName = inputFile.readline()
inputFile.close()
def lowestScorer():
integers = open("golf.dat", "r")
lowestScore = 0
for score in integers:
if lowestScore >= int(score.strip()):
lowestScore = int(score.strip())
integers.close()
print("The lowest score was: ", lowestScore)
I've tried: I have tried (in vein) to write a function (lowestScorer) to extract and display the lowest value, but it didn't occur to me at first, but this is obviously going to fail, based on the way my data is stored.
Where you can help: suggest if there is any Pythonic way of adapting my code (rather than re-writing), to allow my program to identify and display the name and scorer of the lowest scorer / integer, saved in my golf.dat file?
My suspicion is that I should have written this program with two lists that hold names and scores respective and then written these to golf.dat (for easy extraction and analysis) or created these two lists (as sublists, thus holding names and integer score values separately) but gone a step further and saved them within a master list.
I need my output to look nice, and it looks very sloppy.
--------Current output---------
Below are the players and their scores
John Doe 120
Sally Smooth 115
----------End current output----------
My desired output follows
-------Desired output-----------------
Below are the players and their scores
John Doe 120
Sally Smooth 115
--------End desired output-------------
my current code follows;
def main():
# opens the "golf.txt" file created in the Golf Player Input python
# in read-only mode
infile = open('golf.txt', 'r')
print("Below are the players and their scores")
print()
# reads the player array from the file
name = infile.readline()
while name != '':
# reads the score array from the file
score = infile.readline()
# strip newline from field
name = name.rstrip('\n')
score = score.rstrip('\n')
# prints the names and scores
print(name + " " + score)
# read the name field of next record
name = infile.readline()
# closes the file
infile.close()
main()
Try using the tab character to format your spaces better.
print(name + "\t" + score)
This should give you something closer to your desired output. But you may need to use two if some names are long.
You can add the names and the scores to a list and then print it as a table as
import numpy as np
name_list = ['jane doe' ,'sally smooth']
score = np.array([[102,],[106,]]) #make a numpy array
row_format ="{:>15}" * (len(name_list))
for name, row in zip(name_list, score):
print(row_format.format(name, *row))
Note: This depends on str.format()
This code will output:
jane doe 102
sally smooth 106
I'm brand new to both Python and StackOverflow, and I have a problem that has been stumping me for the past couple of hours.
I am making a peer-evaluation script for my high-school class. When you run the script, you input your classmate's name, then you rate them 1-10 on effort, accountability, and participation. These 3 values are then averaged. This average is assigned to the variable "grade". Since each classmate is going to get multiple grades, I need to have the "grade" variable export to another Python document where I can average every grade for each respective classmate.
So far, I have the script create a .txt file with the same name as the evaluated classmate, and the grade integer is stored there. Does anyone know of a way that I can export that integer to a Python file where I can append each successive grade so they can then be averaged?
Thanks
Python peer evaluation script
def script():
classmate = input('Please enter your classmate\'s name: ')
classmateString = str(classmate)
effortString = input('Please enter an integer from 1-10 signifying your classmate\'s overall effort during LLS: ')
effort = int(effortString)
accountabilityString = input('Please enter an integer from 1-10 signifying how accountable your classmate was during LLS: ')
accountability = int(accountabilityString)
participationString = input('Please enter an integer from 1-10 signifying your classmate\'s overall participation: ')
participation = int(participationString)
add = effort + accountability + participation
grade = add / 3
gradeString = str(grade)
print ('Your grade for ', classmate, 'is: ', grade)
print ('Thank you for your participation. Your input will help represent your classmate\'s grade for the LLS event.')
filename = (classmateString)+'.txt'
file = open(filename, 'a+')
file.write(gradeString)
file.close()
print ('Move on to next classmate?')
yes = set(['yes','y','Yes','Y'])
no = set(['no','n','No','n'])
choice = input().lower()
if choice in yes:
script()
elif choice in no:
sys.exit(0)
else:
sys.stdout.write("Please respond with 'yes' or 'no'")
script()
script()
put
import name_of_script_file
at the top of your Python file, assuming they are in the same folder.
Then you can access the variable like:
name_of_script_file.variable_name