python学习笔记-基础语法每条if语句的核心都是一个值为True或False的表达式,我来为大家科普一下关于常用的基础语法?以下内容希望对你有帮助!

常用的基础语法(2022年5月18日学习笔记-基础语法)

常用的基础语法

python学习笔记-基础语法

第五章 if语句 第六章 字典一、条件测试

每条if语句的核心都是一个值为True或False的表达式。

如果条件测试的值为True,Python就执行紧跟在if语句后面的代码;如果为False,Python就忽略这些代码。

方法

描述

==

判断是否相等

!=

判断是否不等

<=

小于等于

>=

大于等于

and

检查两个条件是否都满足

or

检查两个条件是否至少有一个满足

in

检查特定值是否包含在列表中

not in

检查特定值是否不包含在列表中

布尔表达式

记录条件

>>> 1 == 1 True >>> 1 != 1 False >>> 1 <= 1 True >>> 1 >= 2 False >>> 1 >= 0 and 2 >= 1 True >>> cars = ['bmw','audi','toyota','byd'] >>> ('bmw' in cars) or ('subaru' in cars) #使用括号更为简洁 True >>> 'subaru' not in cars True

二、if语句

age = 19 if age < 2: print('你是一个婴儿!') elif age < 4: print('你正蹒跚学步!') elif age < 13: print('你是儿童!') elif age < 20: print('你是青少年!') elif age < 65: print('你是成年人!') else: print('你是老年人!') favorite_fruits = ['banlala','watermelon','strawberry'] if 'apple' in favorite_fruits : print('You really like apples!') if 'banlala' in favorite_fruits : print('You really like banlalas!') 输出结果为: 你是青少年! You really like banlalas!

三、使用if语句处理列表

1、检查特殊元素

request_toppings = ['mushrooms','green peppers','extra cheese'] for request_topping in request_toppings: if request_topping == 'green peppers': print('Sorry! The green peppers is out now!') else: print('Adding' request_topping '.') print('\nFinished making your pizza!') 输出结果为: Addingmushrooms. Sorry! The green peppers is out now! Addingextra cheese. Finished making your pizza!

2、确定列表不是空的

request_toppings = [] if request_toppings: #显然此处等价于if False: for request_topping in request_toppings: print('Adding' request_topping '.') else: print('Are you sure to buy a plain pizza?') 输出结果为: Are you sure to buy a plain pizza?

3、使用多个列表

requested_toppings = ['mushrooms','french fries','extra cheese'] avalible_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'] for requested_topping in requested_toppings: if requested_topping in avalible_toppings: print('Adding' requested_topping '.') else: print("Sorry, we dont't have " requested_topping '.') 输出结果为: Addingmushrooms. Sorry, we dont't have french fries. Addingextra cheese.

四、使用字典

1、访问字典中的值

>>> alien_0 ={'color':'green','points':5} >>> new_points = alien_0['points'] >>> print("You just earned " str(new_points) "points!") You just earned 5points! >>> print("You just earned " str(new_points) " points!") You just earned 5 points! >>> alien_0["color"] #不区分单双引号 'green' >>> alien_0[0] #不可使用索引 Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> alien_0[0] KeyError: 0

2、添加键-值对、创建空字典要添加键-值对,可依次指定字典名、用方括号括起的键和相关联的值。

>>> alien_0 = {} #直接创建一个空字典 >>> alien_0['x_position'] = 0 >>> alien_0['y_position'] = 25 >>> print(alien_0) {'x_position': 0, 'y_position': 25}

3、修改字典中的值要修改字典中的值,可依次指定字典名、用方括号括起的键以及与该键相关联的新值。类比列表修改元素。

alien_0 = {'x_position' : 0,'y_position' : 25,'speed': 'medium'} print('Original x_position: ' str(alien_0['x_position'])) if alien_0['speed'] == 'slow': x_increment = 1 elif alien_0['speed'] == 'medium': x_increment = 2 else: #一定很快 x_increment = 3 alien_0['x_position'] = alien_0['x_position'] x_increment print('New x_position: ' str(alien_0['x_position'])) 输出结果为: Original x_position: 0 New x_position: 2

4、删除键-值对

alien_0 ={'color':'green','points':5} print(alien_0) del alien_0['color'] print(alien_0) 输出结果为: {'color': 'green', 'points': 5} {'points': 5}

5、由类似对象组成的字典

favorite_language = { 'jen':'Python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } print("Sarah's favorite language is " favorite_language['sarah'] '.') #回车以保持美观 输出结果为: Sarah's favorite language is C.

五、遍历字典

遍历字典时,键-值对的返回顺序与存储顺序未必保持一致。 示例1: user_0 = { 'username':'efermi', 'first':'enrico', 'last':'fermi', } for key, value in user_0.items(): print('\nkey: ' key) print('value: ' value) 输出结果为: key: username value: efermi key: first value: enrico key: last value: fermi

示例2: favorite_languages = { 'jen':'python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } for name, language in favorite_languages.items(): print(name.title() "'s favorite language is" " " language ".") 输出结果为: Jen's favorite language is python. Sarah's favorite language is C. Edward's favorite language is ruby. Phil's favorite language is python.

2、遍历字典中的所有键方法:.keys()或者直接使用字典名称for name in favorite_languages.keys():等价于for name in favorite_languages:

favorite_languages = { 'jen':'python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } friends = ['phil','sarah'] for name in favorite_languages.keys(): print(name.title()) if name in friends: print("Hi " name.title() ", I see your favorite language is " favorite_languages[name].title() "!\n") if 'erin' not in favorite_languages: print('Erin, please take our poll!') 输出结果为: Jen Sarah Hi Sarah, I see your favorite language is C! Edward Phil Hi Phil, I see your favorite language is Python! Erin, please take our poll!

3、按顺序遍历字典中的所有键方法:sorted()函数按字母排序

favorite_languages = { 'jen':'python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } for name in sorted(favorite_languages.keys()): print(name.title() ", thank you for takeing the poll.") 输出结果为: Edward, thank you for takeing the poll. Jen, thank you for takeing the poll. Phil, thank you for takeing the poll. Sarah, thank you for takeing the poll.

4、遍历字典中的所有值方法:.values()

favorite_languages = { 'jen':'python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } for value in set(favorite_languages.values()): print(value.title()) 输出结果为: C Ruby Python #重复的值被省去了

5、按顺序遍历字典中的所有值同按顺序遍历字典中的所有键一样,使用sorted()函数即可

favorite_languages = { 'jen':'python', 'sarah':'C', 'edward':'ruby', 'phil':'python', } for value in sorted(set(favorite_languages.values())): print(value.title()) 输出结果为: C Python Ruby

六、嵌套

1、字典列表将一些列字典储存在列表中

#创建一个空的机器人列表 aliens = [] #生成30个机器人并存储于列表中 for alien in range(30): new_alien = {'color':'green','points':5,'speed':'slow'} aliens.append(new_alien) for alien in aliens[0:3]: if alien["color"] == 'green': alien["color"] = 'yellow' alien["points"] = 10 alien["speed"] = 'medium' for alien in aliens[0:5]: print(alien) print("...") print('Total number of aliens: ' str(len(aliens))) 输出结果为: {'color': 'yellow', 'points': 10, 'speed': 'medium'} {'color': 'yellow', 'points': 10, 'speed': 'medium'} {'color': 'yellow', 'points': 10, 'speed': 'medium'} {'color': 'green', 'points': 5, 'speed': 'slow'} {'color': 'green', 'points': 5, 'speed': 'slow'} ... Total number of aliens: 30

2、在字典中存储列表

favorite_laguages = { 'jen':['python','ruby'], 'sarah':['c'], 'edward':['ruby','go'], 'phil':['python','Haskell'], } for name, languages in favorite_laguages.items(): if len(languages) == 1: print("\n" name.title() "'s favorite language is " languages[0].title()) else: print("\n" name.title() "'s favorite language are: ") for language in languages: print(language.title()) 输出结果为: Jen's favorite language are: Python Ruby Sarah's favorite language is C Edward's favorite language are: Ruby Go Phil's favorite language are: Python Haskell

3、在字典中储存字典

users = { 'aeinstein':{ 'first_name':'albert', 'last_name':'einstein', 'location':'princeton', }, 'mcurie':{ 'first_name':'marie', 'last_name':'cruie', 'location':'paris', }, } for name, info in users.items(): print("\nUsername: " name.title()) print("\tFull name: " (info['first_name']).title() " " (info['last_name']).title()) 输出结果为: Username: Aeinstein Full name: Albert Einstein Username: Mcurie Full name: Marie Cruie

注:

,