Python 学习笔记[2]
五、if语句
==
两边值相等返回True,不等False
!=
两边值不等返回True,相等False
and
每个条件都满足才可返回true
or
至少一个条件满足就可返回true
in
检查特定值是否包含在列表中
not in
检查特定值是否包含在列表中
>>> list = ['a','b','c']
>>> 'a' in list
True
>>> 2 in list
False
- if结构
- if-else 结构
- if-elif-else 结构(可省略else,可增加elif)
如果只想执行一个代码块,就使用if-elif-else结构;如果要执行多个代码块,就使用一系列独立的if语句。
If+列表名 列表不空时返回true,否则返回false。
age = 17
# if结构
if age < 18:print(f'yes {age}.')
# if-else 结构
if age > 18:print(f'yes {age}.')
else:print(f'no {age}.')
# if-elif-else 结构(可省略else,可增加elif)
if age < 10:print('free')
elif age < 20:print('10$')
else:print('15$')
yes 17.
no 17.
10$
六、字典
在python中,字典是一系列键值对。每一个键都与一个值相关联,可使用键来访问相关联的值。与键相关联的值可以是数、字符串、列表乃至字典。
键值对是两个相关联的的值,键与值之间用冒号分隔,而键值对之间用逗号分开。
aline_0 = {'color':'green','points':5}
1.访问字典中的值
1.1字典名+[ 键 ]
aline_0 = {'color':'green','points':5}
print(aline_0['color'])
green
1.2使用get()
来访问值
使用放在方括号的键访问字典中的值可能会引发问题:如果指定的键不存在就会出错。
aline_0 = {'color':'green','points':5}
print(aline_0['speed'])
这将导致python显示tarceback,指出存在键值错误(KeyError):
Traceback (most recent call last): File "D:\work_python\……", line 2, in <module> print(aline_0['speed'])
KeyError: 'speed'
就字典而言,可使用方法get()
在指定键不存在时返回一个默认值,从而避免错误。
方法get()
的第一个参数用于指定键,是必不可少的;第二个参数为指定的键不存在时要返回的值,是可选的。(如果没有指定第二个参数且指定的键不存在,python将返回值None)
aline_0 = {'color':'green','points':5}
print(aline_0.get('speed','no speed key'))
no speed key
2.添加键值对
依次指定字典名、用方括号括起的键和相关联的值。
aline_0 = {'color':'green','points':5}
aline_0['x_position'] = 0
aline_0['y_position'] = 10
print(aline_0)
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 10}
3.修改字典中的值
指定字典名、用方括号括起的键,以及该键相关联的新值。
aline_0 = {'color':'green','points':5}
aline_0['color'] = 'yellow'
print(aline_0)
{‘color’: ‘yellow’, ‘points’: 5}
4.删除键值对
使用del语句,指定字典名和要删除的键(永远消失)
aline_0 = {'color':'green','points':5}
del aline_0['color']
print(aline_0)
{‘points’: 5}
5.遍历字典
5.1遍历所有键值对
for
循环遍历字典,声明两个变量,用于存储键值对中的键和值。
方法items()
,它返回一个键值对列表
favorite_languages = {'jen':'python','sarah':'c','edward':'ruby','phil':'java',
}
for name,language in favorite_languages.items():print(f'{name.title()} : {language}')
Jen : python
Sarah : c
Edward : ruby
Phil : java
5.2遍历字典中的所有键
使用方法keys()
进行遍历
方法keys()
并非只能用于遍历:实际上,它返回一个列表,其中包含字典中的所有键。因此,可以判断一个键是否在字典中
favorite_languages = {'jen':'python','sarah':'c','edward':'ruby','phil':'java',
}
for name in favorite_languages.keys(): # 遍历 print(name.title())if 'jone' not in favorite_languages.keys(): # 判断print('NO')
Jen
Sarah
Edward
Phil
NO
遍历字典时,会默认遍历所有键,因此
for name in favorite_languages.keys():
可替换为
for name in favorite_languages:
5.3遍历字典中的所有值
使用方法values()
返回一个值列表,不包含任何键
favorite_languages = {'jen':'python','sarah':'c','edward':'ruby','phil':'java','jone':'python'
}
for language in favorite_languages.values():print(language.title())
Python
C
Ruby
Java
Python
这种做法提取字典中的所有值,没有考虑是否重复。如果为了剔除重复项,可使用集合(set),集合中的每一个元素都必须是独一无二的。
通过对包含重复元素的列表调用set()
,可让python找出列表中独一无二的元素,并使用这些元素来创建一个集合。
# 这里使用的是上一个例子的字典
for language in set(favorite_languages.values()): print(language.title())print(set(favorite_languages.values())) # 输出整个集合
Ruby
Java
C
Python
{‘ruby’, ‘java’, ‘c’, ‘python’}
5.4按特定顺序遍历字典
一种方法是在for循环中对返回后的键进行排序。为此,可使用函数sorted()
来获得特定顺序排列的键列表的副本。
favorite_languages = {'jen':'python','sarah':'c','edward':'ruby','phil':'java','jone':'python'
}
for name in sorted(favorite_languages.keys()):print(name.title(),':',favorite_languages[name])# 输出键以及对应值
Edward : ruby
Jen : python
Jone : python
Phil : java
Sarah : c
6.嵌套
6.1字典列表
aline_0 = {'color':'green','points':5}
aline_1 = {'color':'yellow','points':10}
aline_2 = {'color':'red','points':15}
alines = [aline_0,aline_1,aline_2]
for aline in alines:print(aline)
{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}
6.2在字典中存储列表
favorite_languages = {'jen':['python','c++'],'sarah':['c'],'edward':['ruby','go'],'phil':['java','c'],'jone':['python','haskell'],
}
for name,languages in favorite_languages.items(): print(f'{name.title()}:')for language in languages:print('\t',language)
Jen:
python
c++
Sarah:
c
Edward:
ruby
go
Phil:
java
c
Jone:
python
haskell
6.3在字典中存储字典
users = {'aeinstein':{'frist':'albert','last':'einstein','location':'princetion',},'mcurie':{'frist':'marie','last':'curie','location':'paris',},
}
for username,user_info in users.items():#两个变量分别用于存放用户名和用户信息print(f'\nUsername:{username}')fullname = f"{user_info['frist']} {user_info['last']}"location = user_info['location']print(f'\tFullname:{fullname}')print(f'\tLocation:{location}')
Username:aeinstein
Fullname:albert einstein
Location:princetion
Username:mcurie
Fullname:marie curie
Location:paris
七、用户输入和while
循环
1.函数input()
使用(用户输入)
函数input()
让程序暂停运行,等待用户输入一些文本。
函数input()
接受一个参数——要向用户显示的提示或说明,让用户知道如何操作。
message = input("Tell me something:")
print(message)
Tell me something:666
666
有时候,提示可能超过一行,以下是过长字符串和多行字符串创建方式
使用使用运算符+=
使用反斜杠
使用三引号’‘’ ‘’’
# 第一种使用运算符+=
prompt = "If you tell us who you are, we can personalize the message you see."
prompt += "\nWhat is your first name?"# 第二种使用反斜杠\
prompt = "If you tell us who you are, we can personalize the message you see.\
\nWhat is your first name?"# 第三种使用三引号''' '''
prompt = '''If you tell us who you are, we can personalize the message you see.
What is your first name?'''message = input(prompt)
print(f'Hello, {message}!')
If you tell us who you are, we can personalize the message you see.
What is your first name?Eirc
Hello, Eirc!
使用函数input()
时,python将用户输入解读为字符串。要将数的字符串转化为数值表示,可使用函数int()
。
age = input("How old are you?")
print(age == '20')
age = int(age) # 转化
print(age == 20)
How old are you?20
True
True
2.while
循环
2.1使用while
循环
注意冒号
current_number = 1
while current_number <= 5:print(current_number)current_number += 1
1
2
3
4
5
2.2使用标志
在要求很多条件都满足才继续运行的程序中,可定义一个变量,用于判断整个程序是否处于活动状态。这个变量称为标志( flag ),充当程序的交通信号灯。让程序在标志为 True 时继续运行,并在任何事件导致标志的值为 False 时让程序停止运行。
prompt = "Tell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program."flag = True
while flag:message = input(prompt)if message == 'quit':flag = Falseelse:print(message)
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program.Hello
Hello
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program.yes
yes
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program.quit
2.3使用break
退出循环
要立即退出while
循环,不在运行循环中余下的代码,也不管条件测试的结果如何,可使用break
语句。
prompt = "Please enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.)"while True:city = input(prompt)if city == 'quit':breakelse:print(f"I'd love to go to {city}!")
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.)Beijing
I’d love to go to Beijing!
Please enter the name of a city you have visited:
(Enter ‘quit’ when you are finished.)quit
在任何python循环中都可以使用 break 语句。
2.4在循环中使用contine
要返回循环开头,并根据条件测试结果决定是否继续执行循环,可使用 continue 语句。
# 从一数到十只打印奇数
current_number = 0
while current_number < 10:current_number += 1if current_number % 2 == 0:continueelse:print(current_number)
1
3
5
7
9
3.使用 while 循环处理列表和字典
for 循环是一种遍历列表的有效方式,但不应在 for 循环中修改列表,否则会导致python难以跟踪其中的元素。要在遍历列表的同时对其进行修改,可使用 while 循环。
3.1在列表之间移动元素
# 首先,创建一个待验证用户列表,和一个用于存储已验证用户空列表
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []while unconfirmed_users: # 列表不为空是循环user = unconfirmed_users.pop() # 从列表末尾删除一个元素print(f"Verifying user: {user.title()}")confirmed_users.append(user) # 插入 unconfirmed_users 中拿出的元素print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:print(confirmed_user)
Verifying user: Candace
Verifying user: Brian
Verifying user: Alice
The following users have been confirmed:
candace
brian
alice
3.2删除列表中的所有特定值
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)while 'cat' in pets: # 'cat' 在列表中循环进行pets.remove('cat')print(pets)
[‘dog’, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]
[‘dog’, ‘dog’, ‘goldfish’, ‘rabbit’]
3.3使用用户输入来填充字典
responses = {} # 创建空字典
flag = True # 设置标志while flag:name = input("\nWhat is your name?") # 输入名字和回答response = input("Which mountain would you like to climb someday?")responses[name] = response # 将回答存入字典# 看看是否还有人参与调查repeat = input("Would you like to let another person respond?(yes/no)")if repeat == 'no':flag = False# 调查结束,显示结果
print("\n--- Poll Results ---")
for name, response in responses.items():print(f"{name} would like to climb {response}. ")
What is your name?Eric
Which mountain would you like to climb someday?Denali
Would you like to let another person respond?(yes/no)yes
What is your name?Lynn
Which mountain would you like to climb someday?Devil’s Thumb
Would you like to let another person respond?(yes/no)no
--- Poll Results ---
Eric would like to climb Denali.
Lynn would like to climb Devil’s Thumb.
Python 学习笔记[2]相关推荐
- [python教程入门学习]python学习笔记(CMD执行文件并传入参数)
本文章向大家介绍python学习笔记(CMD执行文件并传入参数),主要包括python学习笔记(CMD执行文件并传入参数)使用实例.应用技巧.基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋 ...
- python学习笔记之编写readConfig读写配置文件
python学习笔记之编写readConfig读写配置文件_weixin_34055910的博客-CSDN博客
- Python学习笔记(十一)
Python学习笔记(十一): 生成器,迭代器回顾 模块 作业-计算器 1. 生成器,迭代器回顾 1. 列表生成式:[x for x in range(10)] 2. 生成器 (generator o ...
- Python学习笔记一简介及安装配置
Python学习笔记一 参考教程:廖雪峰官网https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e54 ...
- python学习笔记目录
人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...
- Python学习笔记(二):标准流与重定向
Python学习笔记(二):标准流与重定向 - SamWei - 博客园 Python学习笔记(二):标准流与重定向 Posted on 2012-02-19 22:36 SamWei 阅读(176) ...
- python 学习笔记 12 -- 写一个脚本获取城市天气信息
近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...
- python基本语法语句-python学习笔记:基本语法
原标题:python学习笔记:基本语法 缩进:必须使用4个空格来表示每级缩进,支持Tab字符 if语句,经常与else, elif(相当于else if) 配合使用. for语句,迭代器,依次处理迭代 ...
- 廖Python学习笔记一
1. 廖Python学习笔记 大的分类 如函数 用二级标题,下面的用三级 如输入输出 1.1.1. 输入输出 1.1.1.1. 输出 用 print() 在括号里加上字符串,就可以向屏幕上输出指定的文 ...
- Python学习笔记(六)
1. IO编程 1.1 文件读写 1.2 StringIO和BytesIO 1.3 操作文件和目录 1.4 序列化 2. 进程和线程 2.1 多进程 2.2 多线程 2.3 ThreadLocal 2 ...
最新文章
- 再读《精通css》03:引入和注释
- 在字符串末尾添加字符使其成为回文串
- ExecutorService- Future - Java多线程编程
- 历经32载,域名仍是少年,更何况不足2岁的.xin?
- DevExpress控件之GridControl控件
- 使用MySQL的存储过程
- QT 线程池 + TCP 小试(一)线程池的简单实现
- 常用MySQ调优策略及相关分享:学习随记
- Java解决循环注入问题
- 【大学物理】设计性实验报告
- 游戏开发学习路线——游戏引擎原理
- 【转】局域网速度测试 三款软件轻松搞定
- Nature:分离到一种位于原核生物-真核生物“交界”的古菌
- 7-86 分支结构——大小写字母判断
- 5日均线在c语言中的写法,一文学会正确运用5日均线!(图解)
- MYSQL JDBC图书管理系统
- Verilog学习笔记HDLBits——Finite State Machines(1)
- Oracle实现金额小写转大写函数
- xml文件加密和解密
- Python爬虫入门(一)火车票余票实时提醒
热门文章
- 世界级标杆项目!联合利华全国首个全品类生产和营销基地落户广州;菲仕兰中国首家体验店在上海黄浦正式启用 | 美通社头条...
- 软考计算机专业英语,软考计算机专业英语常用词汇(首字母I-O)
- 【CH559L单片机】串口下载程序说明
- 人工智能的前沿信息获取之使用谷歌学术搜索
- MySQL数据库(13):列属性(字段属性)
- 【R语言】数据清理利器:dplyr库六函数:filter select arange mutate summarize
- form标签的action怎么用
- 《灰色系统理论及应用》第8章 离散灰色预测模型 例8.1.1
- JavaWeb(上)
- c语言黑匡程序,2020年新版C语言实用程序设计100例流程图.docx