# Basic learning notes and after class exercises of MOOCPython language programming in University of China Week 7 (Nanjing University of Posts and Telecommunications)

Posted by JohnMC on Wed, 09 Feb 2022 05:46:14 +0100

# Week 7 exception handling and file operation

code:

```try:
a,b=input("Please enter the divisor and divisor, separated by spaces:").split()
a=eval(a)
b=eval(b)
print("{}/{}={}".format(a,b,a/b))
except ZeroDivisionError:
print("Sorry, there is an error in the program! Error reason: divisor cannot be 0!")
except ValueError:
print("Sorry, there is an error in the program! The error reason is: not enough parameters are entered!")
finally:
print("The procedures contained here will be responsible for the aftermath.")
```
```import turtle
def drawstar(x,y,color):
turtle.up()
turtle.goto(x,y)
turtle.down()
turtle.color(color)
for i in [0,1,2,3,4]:
turtle.right(144)
turtle.forward(100)

#Please enter the little turtle and set the shape and color of the little turtle
from fivestar import drawstar
import turtle
turtle.shape("turtle")
turtle.color("red")

#Draw the first Pentagram
drawstar(-200,200,"blue")
#Draw the second pentagram
drawstar(300,200,"green")
#Continue to set the position and orientation of the little turtle, and draw the third and fourth five pointed stars
drawstar(-200,-200,"red")
drawstar(300,-200,"yellow")
#Take the little turtle home
turtle.up()
turtle.home()
```

Use of else:

Two sorting methods: sorted does not change the original value, but sort does

## Unit work

### 1. There are two disk files A.txt and B.txt, each storing a line of characters (please put A.txt and B.txt in the same folder as the program and add a line of characters). It is required to merge the information in the two files (rearrange them alphabetically, ignoring case) and output them to a new file C.txt.

```#Exception handling module
try:
#Open file
with open('A.txt','r') as file:
lst1=[]
#Except for non alphabetic content, this exercise is only sorted by English letters by default
for i in text1:
if 'a'<=i<='z' or 'A'<=i<='Z':
lst1.append(i)
with open('B.txt', 'r') as file:
lst2 = []
# Except for non alphabetic content, this exercise is only sorted by English letters by default
for i in text2:
if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
lst2.append(i)
#Merge the information in the two files
textC=lst1+lst2
#Rearrange alphabetically, ignoring case
textC=sorted(textC,key=lambda x:x.lower())
textC=''.join(textC)
#Save to C.txt file
with open('C.txt','w') as fout:
fout.write(textC)
except:
print('Unable to open file.')
```

### 2. The attachment contains an English short passage. Please write a program to count the number of occurrences of each English letter in this short passage and add the number of occurrences of each letter to the end of the text.

```#2. The attachment contains an English short passage. Please write a program to count the number of occurrences of each English letter in this short passage and add the number of occurrences of each letter to the end of the text.
try:
with open('Beauty.txt','r') as fin:
#Count the times and save to the end of the file
result={}
#Traverse each character of the text and save the count of times as the value in the dictionary
for i in file:
if 'A'<=i.upper()<='Z':
#Use the get method to avoid error reporting. The second parameter indicates that the key does not exist
result[i.upper()]=result.get(i.upper(),0)+1
#The sorting method I wrote
'''
lst=list(result.items())
lst.sort(key=lambda x:x[1])
for key,item in lst:
print(key,':',item)

#The teacher's ranking method is more concise
for key in sorted(result.keys()):
print(key,':',result[key])
'''
with open('Beauty.txt','a') as fin:
# for key in sorted(result.keys()):
#     #print(key, 'number of occurrences:', result[key])
#     fin.write('\n'+key + 'Occurrences:' + str(result[key]))
#Or write
for key in sorted(result.keys()):
fin.write('\n{}The number of occurrences is:{}'.format(key,(result[key])))
except Exception as e:
print(e)
```

# Week 7 experimental week

Reference to how to use strings in Python:
https://www.runoob.com/python/python-strings.html
Reference to how to use lists in Python:
https://www.runoob.com/python/python-lists.html
Reference to the usage of tuples in Python:
https://www.runoob.com/python/python-tuples.html
Reference to how to use dictionaries in Python:
https://www.runoob.com/python/python-dictionary.html
Reference to how to use collections in Python:
https://jingyan.baidu.com/article/1974b2896ba089f4b1f774a4.html
Reference to how to use files in Python:
https://www.yiibai.com/python3/python_files_io.html

## 1. Please write a Python program to complete the following requirements: there is a file named class in the current working directory_ score. TXT text file, which stores the names of students in a class (column 1), mathematics grades (column 2) and Chinese grades (column 3). Each column of data is separated by tab (\ t).

My code:

```# -*- coding: utf-8-*-
#Function 1:
#Calculate the average score of mathematics and Chinese in this class (keep 1 decimal place) and output it
def average_Info(count):
Math_sum=0
Chinese_sum=0
for i in count:
Math_sum+=int(count[i][0])
Chinese_sum+=int(count[i][1])
Math_average =Math_sum/len(count)
Chinese_average =Chinese_sum/len(count)
return 'Math_average:%.1f,Chinese_average:%.1f'%(Math_average,Chinese_average)

#Function 2:
#Find out the students who failed in both courses (< 60) and output their names and grades in each subject
for i in count:
if int(count[i][0])<60 and int(count[i][1])<60:

#Function 3:
#Find out the students with an average score of more than 90 in the two courses and output their student number and grades in each subject. Since the student number is not given in this question, output their name and grades in each subject according to the practice in the previous question,
#You can also re-establish the dictionary. The key is the student number and the value is the name and grade.
def func(count):
#Average score of two courses
for i in count:

if __name__=='__main__':
#Read the contents of the file and put them into the dictionary
with open('class_score.txt','r',encoding='utf-8') as file:
count={}
for line in t:
line.replace('\t',"")
line=line.split()
count[line[0]]=(line[1],line[2])
print('number1:',average_Info(count))
print('number2:')
print('number3:')
func(count)
```

Output result:
number1: Math_average:80.8,Chinese_average:76.0
number2: