background

Today we are going to do a Python exercise.

Procedure 1: receive user input name and result, the result is 1-100, at most two decimal places. Press Q to end the input and write the legally entered data to a file. Program two: read the program a output of the file, and then calculate the average score, and output the highest score and the lowest score value and name.

Implementation analysis

This example uses the knowledge point:

  1. File operation, requiredtry-except-finally, handle file exceptions;
  2. Regular for judging grades:^ [0-9] {1, 2} (\. [0-9] {1, 2})? $, the result can be two decimal places;
  3. whileThe loop condition, the Python logic operation isand / or / notSuch as keywords, rather than logical operation symbols;
  4. usepd.read_csvConvert the CVS file toDataFrameData set;
  5. useDataFrameMax, min, AVG, IDMAX, IDminAnd so on.

Achievement Information Collection

Write a script file called score_writer.py with the following contents:

import re

try:
	# define file reader
	f1 = open('E:/score.log'.'w',encoding='utf-8')
	f1.write('name,score\r\n')
	# a pattern check score input
	pattern = "^ [0-9] {1, 2} (\. [0-9] {1, 2})? $"
	print('Please enter your name and score, ending with Q. Score range [1-100], up to two decimal places allowed. ')

	# receive name
	name = input("Name:")
	whilename ! ='Q'and name ! ='q' :
		score = input("Performance.").strip()
		whilere.match(pattern,score)==None and score ! ='100':
			score = input("Score is not valid, please re-enter :").strip()

		print(name,':',score)
		f1.write(name+', '+score+'\r\n')
		name = input("Name:")
	print('Enter finished, store data')
except IOError:
	 print("Abnormal operation")
finally:
	f1.close()
Copy the code

Running results:

Performance data calculation

Write a script file called score_reader.py that looks like this:

from pandas import DataFrame
import pandas as pd

# array to load score
try:
	# define file reader
	data = pd.read_csv('E:/score.log')
	print(data)
	print('Average',data['score'].mean(axis = 0))
	print(data['name'][data['score'].idxmax()],'Highest score:',data['score'].max(axis = 0))
	print(data['name'][data['score'].idxmin()],'Lowest score:',data['score'].min(axis = 0))
except IOError:
	 print("File does not exist")
Copy the code

Because the CVS file is stored, the title is name,scroe, after converting to DataFrame, calculate the most valuable index subscript and take the corresponding element of the name column to output the most valuable name.

Replace a file path that does not exist

Apocalypse of Programming

Python is a neat way to read and write files. Two lines of code is the opposite of dozens of lines in Java. Remember to see a language comparison chart two days ago:

language Implement way The running speed Lines of code
C compile Very fast less
Java compile fast Very much
Python explain slow There is very little