1.导入模块
模块就是别人写的程序。
不仅可以导入,还可以选择导入哪一部分。
不仅导入别人的,还可以自己取名字。
import time
print(time.localtime())
import time as t
print(t.localtime())
# from a.b.c import d
from time import time
print(time())
from time import *
print(localtime())
2.异常处理
try试试,不成功也要有执行方法。
try:
file = open('1.py', 'r+')
except Exception as e:
print('there is no file named as eeeee')
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()
3.字符串操作
改变大小写,插入制表符,清理空间,改变变量类型。
string=" test " # 1. re 2. text processing
number=1
print("Change the Upper/Lower case")
print(string.upper())
print(string.lower())
print("\n")
print("Insert the Tab")
print("\t"+string)
print("\n")
print("Clear the space")
print(string.rstrip())
print(string.lstrip())
print(string.strip())
print("\n")
print("Change the variable type")
print(str(number))
4.列表操作
插入元素在尾部、特定位置,删除元素,输出长度。
listT1=['a','b','c','d','e','f']
list = []
dic = {"name":"harry"}
listT1.append('g') # at the end of the list
print("1st")
print(listT1)
listT1=['a','b','c','d','e','f']
listT1.insert(0,'0') # at the particular position
print("2nd")
print(listT1)
listT1=['a','b','c','d','e','f']
print("3rd")
del listT1[0]
print(listT1)
listT1=['a','b','c','d','e','f']
print("5th")
listT1.remove('b')
print(listT1)
print("6th Length of the list:")
print(len(listT1))
5.元组
不可变列表。
tupleT1=(0,1,2,3,4,'Apple')
print(tupleT1[5])
6.列表选择元素的快速操作和切片。
listT1=['apple','banana','cake','dog']
for x in listT1:
print(x)
for y in range(1,5):
print(y)
for z in range(1,11,2):
listT1.append(z**2)
print(listT1)
listT2=[w**2 for w in range(1,5)]
print(listT2)
print(listT2[:])
print(listT2[:3])
print(listT2[1:])
print(listT2[1:3])
print(listT2[-3:])
7.循环语句
num1=0
while num1<=50:
print("\t"+str(num1))
num1+=1
if num1==5:
print("break")
break
else:
print("continue")
continue
8.分支语句
x=5
if (x==3):
print("x=3")
elif x==4:
print("x=4")
elif x==5:
print("x=5")
else:
print("x!=3v4v5")
9.函数的返回值与调用
def sayhello(user_name='Default name'):
return ("Hello! "+user_name)
def sayhello2(a,user_name='Default name'):
return ("Hello! "+a)
print(sayhello())
print(sayhello('1'))
test = sayhello()
print(test)
def team(a,*b):
print(a+" : "+str(b))
team("1","2")
team("1","2","3","4")
10.文件路径和读写
Dc2='1.txt'
with open(Dc2) as FileTP2:
contents = FileTP2.read()
print(contents.rstrip())
11.类的定义
一堆有共同特征的函数,需要init函数的共性,参数传递方式要注意。
class Team():
def __init__(self, name):
self.name = name
def ReportName(self):
print(self.name)
AlphaTeam = Team('Sarah')
AlphaTeam.ReportName()