Python基础语法了解一下(三)

2019-05-18  本文已影响0人  有理酱_Yuri_Wg

条件循环语句 Conditional Loop Statement
迭代循环语句 Iterative Loop Statement
循环控制 Loop Control
Dispaly & Input
整数序列
容器的通用操作
数组的操作
字典的操作
集的操作
函数定义
功能调用
字符串操作
格式化
文件操作

条件循环语句 Conditional Loop Statement

#当条件为真时,执行语句块  
i=1
s=0
while i<=100:
    s+=i**2
    i+=1
print("sum:",s)
sum: 338350

迭代循环语句 Iterative Loop Statement

#对容器/迭代器中的每个项目执行语句块
#Go over sequence's values
s="this is a sequence"
cnt=0
for c in s:
    if c=="e":
        cnt+=1
print("found",cnt,"'e'")
found 3 'e'
#Go over sequence's index
lst=[1,2,3,4,5,6]
lost=[]
for idx in range(len(lst)):
    val=lst[idx]
    if val>3:
        lost.append(val)
        lst[idx]=15
print("modif:",lst,"-lost",lost)
modif: [1, 2, 3, 15, 15, 15] -lost [4, 5, 6]
#同时遍历序列索引和值
for idx,val in enumerate(lst):

循环控制 Loop Control

break
continue
else

Dispaly & Input

x=1
y=2
print("v=",3,"cm :",x,",",y+4, sep='_',end='\t')
print("结尾跳到下个tab位")

print("v=",3,"cm :",x,",",y+4, sep='_',end='\n')
print("结尾换行")
v=_3_cm :_1_,_6 aaa
v=_3_cm :_1_,_6
bbb
s=input("try:")
try: 123

整数序列

list(range(5))
[0, 1, 2, 3, 4]
list(range(3,8))
[3, 4, 5, 6, 7]
list(range(20,5,-5))
[20, 15, 10]
seq="have a try!"
list(range(len(seq)))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

容器的通用操作

数组的操作

lst=[1,2,3,4,5]
lst.append(6)
lst
[1, 2, 3, 4, 5, 6]
lst.extend([7,8,9])
lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
lst.insert(3,"Alien")
lst
[1, 2, 3, 'Alien', 4, 5, 6, 7, 8, 9]
lst.remove("Alien")
lst
[1, 2, 3, 4, 5, 6, 7, 8, 9]
lst.pop(3)
4
#排序/反向排序
lst.sort()
lst.reverse()
lst
[9, 8, 7, 6, 5, 3, 2, 1]

字典的操作

dct=dict(apple=1,pear=5,orange=9,grape=3)
dct
{'apple': 1, 'pear': 5, 'orange': 9, 'grape': 3}
dct["pear"]
5
dct2=dict(plum=7)
dct.update(dct2)
dct
{'apple': 1, 'pear': 5, 'orange': 9, 'grape': 3, 'plum': 7}
dct.keys()
dict_keys(['apple', 'pear', 'orange', 'grape', 'plum'])
dct.values()
dict_values([1, 5, 9, 3, 7])
dct.items()
dict_items([('apple', 1), ('pear', 5), ('orange', 9), ('grape', 3), ('plum', 7)])
dct.pop("orange")
dct
{'apple': 1, 'pear': 5, 'grape': 3, 'plum': 7}
dct.popitem()
('plum', 7)
dct.get("apple")
1
dct.setdefault("aaa",3)
dct
{'apple': 1, 'pear': 5, 'grape': 3, 'plum': None, 'orange': None, 'aaa': 3}
del dct["aaa"]
dct.clear()
dct
{}

集的操作

函数定义&功能调用

字符串操作&格式化

文件操作

上一篇下一篇

猜你喜欢

热点阅读