A python written test question

巴扎黑
Release: 2020-09-03 15:34:54
Original
3578 people have browsed it

A python written test question

The following code:

# name, age, score
tom, 12, 86
Lee, 15, 99
Lucy, 11, 58
Joseph, 19, 56
Copy after login

The first column is name, the second column is age, and the third column is score

Now, write a Python program,

1 ) Read the file

2) Print the following results:

Who has a score below 60?

Whose name starts with L?

What is the total score of everyone?

3) The first letter of the name needs to be capitalized. Does the record.txt meet this requirement? How to correct the mistakes?

#read lines from file
fobj = open('record.txt', 'r+')
print 'opened file: ', fobj.name
all_lines = fobj.readlines()
fobj.close()
lines = [l[:-1].split(', ') for l in all_lines if not l.startswith('#') and l.strip()]
#list person who's score less than 60
print [s[0] for s in lines if int(s[2]) < 60]
#list person who&#39;s name starts with &#39;L&#39;
print [s[0] for s in lines if s[0].startswith(&#39;L&#39;)]
#compute the score of all person
print sum([int(s[2]) for s in lines])
#write new lines contains capitalize name into file
fobj = open(&#39;record2.txt&#39;, &#39;w+&#39;)
print &#39;opend file: &#39;, fobj.name
newlines = []
for line in all_lines:
    if line[0].islower():
        line = line.capitalize()
    newlines.append(line)
print newlines
if newlines:
    fobj.writelines(newlines)
fobj.close()
Copy after login

Recommended related articles: "2020 python interview questions summary (latest)"

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template