python基础入门
数值类型与基本操作
2**5
1.3e5 1.3e-5
0xFF
type(a)
a = int(input('请输入数据'))
abs(5.2)
round(5.2)
min(2,3,4)
max(2,3,4)
基本数据结构
字符串 str
st = 'jupyter ' + 'python'
st = 'jupyter ' * 3
len(st)
st = 'Gin Vodka Vermouth Bourbon'
st.split()
st.split('Vodka')
li = ['Gin','Vodka','Vermouth','Bourbon']
st = '\\'
st.join(li)
st = 'Gin Vodka Vermouth Bourbon'
st.replace('Bourbon','Zero')
st = 'Vermouth'
st.lower()
st.upper()
st.strip()
st.lstrip()
st.rstrip()
'{} and {} are black'.format('Gin','Vodka')
'{2} and {1} are black'.format('Gin','Vodka')
'{a} and {b} are black'.format(a='Gin',b='Vodka')
列表 list
有序,可以混合存放任意类型数据,可嵌套,通过索引访问
li = [1,2] + [3,4]
li = [1,2] * 3
len(li)
del li[3:]
tmp in li
li.count(tmp)
li.index(tmp)
li.append(tmp)
li.insert(ind,tmp)
li.remove(tmp)
li.pop()
li.pop(ind)
li.sort()
li.sort(reverse=1)
li_sort = sorted(li)
li.reverse()
for i in range(len(li)):
print(li[i])
for t in li:
print(t)
索引
用于有序数据结构,如字符串和列表,不用于字典和集合
st = '01234567'
st[0]
st[-1]
st[0:4]
st[4:]
st[:4]
st[-2:]
st[::3]
字典 dict
基本结构:key-value 无序,使用key访问value,不可使用索引
di = {'Gin':'black','Bourbon':'red'}
di['Gin']
di = dict([('amy',89), ('tom',90)])
di.get('amy')
di.get('sam')
di.get('sam','none')
di.pop('amy')
di['tom'] +=10
del di['tom']
di = {'Gin':'black','Bourbon':'red'}
di.update({'Gin':'black','Vodka':'black'})
'Gin' in di
di.keys()
di.values()
tang.items()
for key in di.keys():
print(di[key])
集合 set
集合内元素不重复,无序,可以进行一些集合间的数学运算/判断
li = [1,1,2,3,5,8]
se = set(li)
li = list(se)
a = {1,2,3,4}
b = {2,3,4}
a | b
a & b
a - b
b <= a
a <= a
a.update([4,5,6])
a.remove(1)
a.pop()
逻辑结构
判断结构
通过and/or 连接多个判断条件
三个及以上判断结果用elif 表示
使用: 和缩进表示逻辑从属
a = 90
if a > 100 and a <= 200:
print('if')
elif a == 50 or a == 90:
print('elif1')
elif (a <10 and a > 0) or a > 200:
print('elif2')
else:
print('else')
循环结构
while 循环
a = 0
while a < 5:
print(a)
a += 1
se = {'Gin','Vodka','Bourbon'}
while se:
print(se.pop())
for循环
for i in range(1,5):
print(i)
di = {'Gin':'black','Vodka':'black','Bourbon':'red'}
for key in di.keys():
print(di[key])
函数
参数和返回值根据需要设定,通过def 关键字、: 和缩进表示逻辑从属
def print_value(a):
print('The value of a is ',a)
def add_value(a=1,b=2):
print('a+b is ',a+b)
def add_number(a,*args):
b = 0
for i in args:
a += i
b += a
return a,b
a,b = add_number(1,2,3)
print (a,b)
def add_2(a,**kwargs):
for arg,value in kwargs.items():
print(arg,value)
add_2(1,x=2,y=3)
包
%%writefile test.py
value = 10010
def test_function():
print('success')
import test as te
print(te.value)
te.test_function()
from test import value,test_function
print(value)
te.test_function()
from test import *
print(te.value)
te.test_function()
类
class people:
'帮助信息:这是一个帮助信息'
location = 'earth'
def __init__(self,name,age):
self.name = name
self.age = age
def show_name(self):
print(self.name)
per1 = people('Vodka',40)
per1.name = 'Gin'
per2.show_name()
del per1.name
hasattr(per1,'age')
hasattr(per1,'name')
getattr(per1,'age')
setattr(per1,'name','Gin')
setattr(per1,'sex','male')
delattr(per1,'sex')
print(peolpe.__doc__)
print (people.__name__)
print (people.__module__)
print (people.__bases__)
print (people.__dict__)
class Dad:
def __init__(self):
print ('父类构造函数')
def dadFunction(self):
print ('父类方法')
def sameName(self):
print ('来自dad')
class son(Dad):
def __init__(self):
print ('子类构造函数')
def sonFunction(self):
print ('子类方法')
def sameName(self):
print ('来自子类')
child = son()
child.dadFunction()
child.sonFunction()
child.sameName()
基础操作
异常处理
用以防止报错导致的程序中断
li = [1,0]
for tmp in li:
try:
print('front')
print(1/tmp)
print('last')
except ZeroDivisionError:
print('不可以除0')
import math
for i in range(10):
try:
input_number = input('write a number')
if input_number == 'q':
break
result = 1/math.log(float(input_number))
print (result)
except ValueError:
print ('ValueError: input must > 0')
except ZeroDivisionError:
print ('log(value) must != 0')
except Exception:
print ('unknow error')
try:
1 / 0
except:
print('不可以除0')
finally:
print('finally')
class NumNotInList(ValueError):
pass
li = [1,2,3]
while True:
num = int(input('input a number: '))
if num not in li:
raise NumNotInList('数字{}不在列表中'.format(num))
文件处理
txt = open('./test.txt')
txt_str = txt.read()
txt_lines = txt.readlines()
txt.close()
txt = open('test.txt','w')
txt.write('123')
txt.close()
txt = open('test.txt','a')
txt.write('\n321')
txt.close()
txt = open('test.txt','r')
print (txt.read())
txt.close()
with open('test.txt','w') as f:
f.write('123\n321')
系统时间
所在包:time.py
import time
print(time.time())
print (time.localtime(time.time()))
print (time.asctime(time.localtime(time.time())))
print (time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))
time.sleep(10)
|