基础语法

读文件

1
2
3
4
5
6
7
8
9
append_text='\nThis is appended file.'
my_file=open('my file.txt','a')
my_file.write(append_text)
my_file.close()

file=open('my file.txt','r')
content=file.readlines() //一行一行读存到列表里面
file.close()
print(content)

简易计算器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Calculator:
name='Good calculator'
price=18
def __init__(self,name,price,hight,width,weight):
self.name=name
self.price=price
self.h=hight
self.wi=width
self.we=weight
def add(self,x,y):
print(self.name)
result=x+y
print(result)
def sub(self,x,y):
result=x-y
print(result)
def mul(self,x,y):
result=x*y
print(result)
def divide(self,x,y):
result=x/y
print(result)
calcul=Calculator('bad calculator',12,13,14,15)
print(calcul.name)
print(calcul.we)

输入:

1
2
3
4
5
6
7
a_input=int(input('Please input a number:'))
if a_input == 1:
print("This is a good number")
elif a_input == 2:
print("See you next time")
else:
print("Good luck")

列表的使用

1
2
3
4
5
6
7
a_input=int(input('Please input a number:'))
if a_input == 1:
print("This is a good number")
elif a_input == 2:
print("See you next time")
else:
print("Good luck")

一些操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
a=[1,2,3,4,2,3,1,1]
a.append(0)
print(a)
a.remove(2) #把第一个2移出去
print(a)
print(a[-1])
print(a[0:3])
print(a[-3:])
print(a.index(2))
print(a.count(1))
a.sort()
print(a)
a.sort(reverse=True)
print(a)

try错误处理

1
2
3
4
5
6
7
8
9
10
11
12
try:
file=open('eeee.txt','r+')
except Exception as e:
print('there is no file named as eeee')
response = input('do you want to create a new file:')
if response == 'y':
file = open('eeee','w')
else:
pass
else:
file.write('ssss')
file.close()

zip和map

1
2
3
4
5
6
7
8
9
10
a=[1,2,3]
b=[4,5,6]
print(list(zip(a,b)))
for i,j in zip(a,b):
print(i/2,j*2)
print(list(zip(a,a,b)))
fun2=lambda x,y:x+y
print(fun2(2,3))
print(list(map(fun2,[1],[2])))
print(list(map(fun2,[1,3],[2,5])))

pickle存放数据

1
2
3
4
5
6
7
8
9
10
import pickle
a_dict = {'da':111,2:[23,1,4],'23':{1:2,'d':'sad'}}
# file=open('pickle_example.pickle','wb')
# pickle.dump(a_dict,file)
# file.close()
with open('pickle_example.pickle','rb') as file:
file=open('pickle_example.pickle','rb')
a_dict1=pickle.load(file)
file.close()
print(a_dict1)