python基础语法

python基础语法速记

1.基本操作

>>> lang
' pythpon '
>>> lang.lstrip()   //删掉左边空格
'pythpon '
>>> lang.rstrip()    //删掉右边空格
' pythpon'
>>> lang.strip()     //删掉两端空格
'pythpon'

>>> name='ada lovelace'
>>> name.title()   //单词首字母大写
'Ada Lovelace'
>>> name.upper()    //全大写
'ADA LOVELACE'
>>> name.upper().lower()    //全小写
'ada lovelace'

>>> age=23
>>> message="Happy "+age+"rd Birthday"
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> message="Happy "+str(age)+"rd Birthday"    #需要使用数字转字符函数
>>> print(message)
Happy 23rd Birthday

>>> comment="这是一个注释"   #python注释要用#

2.列表基本操作

>>> fruits=["peach","banana","pear","apple"]
>>> print(fruits)    #打印
['peach', 'banana', 'pear', 'apple']
>>> print(fruits[0])    #下标从0开始 索引放在中括号中
peach
>>> fruits[0]="Peach"    #修改列表元素
>>> fruits
['Peach', 'banana', 'pear', 'apple']
>>> fruits.append("strawberry")    #添加元素(始终末尾)
>>> fruits
['Peach', 'banana', 'pear', 'apple', 'strawberry']
>>> fruits.insert(0,"mango")     #插入元素 (可以任意位置)
>>> fruits
['mango', 'Peach', 'banana', 'pear', 'apple', 'strawberry']
>>> del fruits[0]    #如果知道要删除的元素位置,可以使用del
>>> fruits
['Peach', 'banana', 'pear', 'apple', 'strawberry']
>>> fruits.pop()    #如果要删除最后一个,可以使用pop函数
'strawberry'
>>> fruits
['Peach', 'banana', 'pear', 'apple']
>>> fruits.pop(0)    #pop其实也可以传递参数,删除指定位置的元素
'Peach'
>>> fruits
['banana', 'pear', 'apple']
#前面几种都是根据索引删除,也可以根据值删除
>>> fruits.remove("pear")    #使用remove函数删除元素
>>> fruits
['banana', 'apple']

---
>>> cars=["BMW","Audi","Toyota","Subaru"]
>>> cars.sort()    #sort排序,会修改原列表
>>> cars
['Audi', 'BMW', 'Subaru', 'Toyota']
>>> cars.sort(reverse=True)    #也可以设定reverse参数为True表示逆序
>>> cars
['Toyota', 'Subaru', 'BMW', 'Audi']
#临时性排序,不更改原列表数据
>>> sorted(cars)
['Audi', 'BMW', 'Subaru', 'Toyota']
>>> cars
['Toyota', 'Subaru', 'BMW', 'Audi']    #没有更改原数据
#对于逆序这种常见操作,提供了reverse函数,该函数会永久性修改原列表
>>> cars.reverse()
>>> cars
['Audi', 'BMW', 'Subaru', 'Toyota']
---
>>> len(cars)    #使用len获取列表的长度
4

3.列表解析

# for循环
>>> for car in cars:
...     print(car.title()+" is a good car!")
...
Audi is a good car!
Bmw is a good car!
Subaru is a good car!
Toyota is a good car!

---
>>> for value in range(1,5):    #使用range创建数值列表 创建的是左闭又开
...     print(value)
...
1
2
3
4
>>> numbers=list(range(1,6)) 
>>> numbers
[1, 2, 3, 4, 5]
>>> even_nums=list(range(2,10,2))   #range函数可以 接受第三个参数:指定步长
>>> even_nums
[2, 4, 6, 8]
---
>>> squares=[]
>>> for i in range(1,6):
...     squares.append(i*i)
...
>>> squares
[1, 4, 9, 16, 25]
---
#简单的统计计算
>>> min(squares)    #最小值
1
>>> max(squares)    #最大值
25
>>> sum(squares)    #求和
55
>>> squares=[value**2 for value in range(1,10)]     #列表解析 更快速的方式
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81]
----#切片---
>>> squares[0:3]
[1, 4, 9]
>>> squares[3:]
[16, 25, 36, 49, 64, 81]
>>> squares[:4]
[1, 4, 9, 16]
>>> squares[-3:]     #倒数三个元素
[49, 64, 81]
>>> squares_copy=squares[:]    #复制列表   深拷贝
>>> squares_copy
[1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> temp=squares    #直接复制是浅拷贝
>>> temp.append(0)
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 0]
---
>>> s=tuple(squares)     #列表转化为元组
>>> s
(1, 4, 9, 16, 25, 36, 49, 64, 81, 0)
>>> len(s)     #获取长度
10
>>> s+s   #元组拼接
(1, 4, 9, 16, 25, 36, 49, 64, 81, 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 0)
>>> hi=("hi",)
>>> hi*4    #类似于字符串乘法
('hi', 'hi', 'hi', 'hi')
>>> 5 in s    #判断存在与否
False
>>> for x in s:
...     print(x)
...
1
4
9
16
25
36
49
64
81
0
>>> s[2:5]    #元组也支持切片操作
(9, 16, 25)
>>> min(s)
0
>>> max(s)
81
>>> sum(s)
285

4.if语句

age=18

age==18
Out[2]: True

age<=20
Out[3]: True

age>=21
Out[4]: False

age> 10 and age <20
Out[5]: True

age >20 or age<10
Out[6]: False
names=["Jim","Jhon","Smith"]
user="Andrew"
if user not in names:
        print(user.title()+" ,you are not in the list")      
Andrew ,you are not in the list

if age<4:
    print("you are a kid")
elif age<18:
    print("you are a teenager")
else:
    print("you can enter")
    
you can enter


5.字典

Jim={"age":18,"gender":"male"}
Jim["age"]
Out[14]: 18

Jim["gender"]
Out[15]: 'male'

print(Jim["age"])
18
---添加元素
box={'color':"green",'height':20}

box['x_pos']=0

box['y_pos']=21

box
Out[20]: {'color': 'green', 'height': 20, 'x_pos': 0, 'y_pos': 21}
box['color']="red"     #修改值

box
Out[22]: {'color': 'red', 'height': 20, 'x_pos': 0, 'y_pos': 21}

del box['height']    #删除键值对

box
Out[24]: {'color': 'red', 'x_pos': 0, 'y_pos': 21}
for key,value in box.items():    #遍历字典
    print("\nKey: "+key)
    print("Value: "+str(value))
    

> Key: color Value: red
> 
> Key: x_pos Value: 0
> 
> Key: y_pos Value: 21

for name in box.keys():   #遍历键
    print(name.title())   

> Color X_Pos Y_Pos
for name in sorted(box.keys()):    #顺序遍历
    print(name.title())
> Color Weight X_Pos Y_Pos

box['height']=10

box
Out[38]: {'color': 'red', 'x_pos': 0, 'y_pos': 21, 'weight': 10, 'height': 10}
for name in box.values():     #遍历值
    print(str(name).title())
   
Red
0
21
10
10
#值时有可能重复的,所以如果不想重复打印可以去重
for name in set(box.values()):
    print(str(name).title())
    
Red
0
10
21


6.嵌套

Stus    #列表嵌套字典
Out[50]: 

[{'color': 'pink', 'height': 179},  {'color': 'green', 'height': 144}, {'color': 'yellow', 'height': 151}]

for stu in Stus:
    print(stu)

{'color': 'pink', 'height': 179}
{'color': 'green', 'height': 144}
{'color': 'yellow', 'height': 151}

Jim={}     #字典嵌套 列表

Jim["gender"]="Male"

Jim["address"]="ShenZhen"

Jim["class"]=["history","Mathematic","Computer","Politics"]

Jim
Out[56]: 
{'gender': 'Male',
 'address': 'ShenZhen',
 'class': ['history', 'Mathematic', 'Computer', 'Politics']}
---
#字典嵌套字典
user
Out[58]: 
{'aeinstein': {'first': 'albert', 'last': 'einstein', 'location': 'princeton'},
 'mcurie': {'first': 'marie', 'last': 'curie', 'location': 'paris'}}
for username, userinfo in user.items():
    print("\nUsername: "+username)
    fullname=userinfo['first']+" "+userinfo['last']
    location=userinfo['location']
    print("\tFull name: "+fullname.title())
    print("\tLocation: "+location.title())
    

Username: aeinstein
	Full name: Albert Einstein
	Location: Princeton

Username: mcurie
	Full name: Marie Curie
	Location: Paris


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值