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 = False
    else:
        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':
        break
    else:
        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 += 1
    if current_number % 2 == 0:
        continue
    else:
        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.


  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python学习笔记PDF是一种学习Python编程语言的资料形式,它包含了Python的基本语法、数据类型、流程控制、函数、模块、面向对象编程、异常处理等相关内容。以下是关于Python学习笔记PDF的详细内容说明: 1. 基本语法:Python学习笔记PDF中,首先介绍了Python的基本语法,例如如何定义变量、数据类型的使用(包括整数、浮点数、字符串、列表、元组、字典等),以及如何进行算术运算、比较运算和逻辑运算。 2. 流程控制:Python学习笔记PDF中,进一步介绍了流程控制的知识,包括条件判断和循环控制。条件判断主要是通过if语句进行判断执行不同的代码块,而循环控制则通过while循环和for循环来实现重复执行一段代码。 3. 函数:Python学习笔记PDF中,对函数的概念和使用进行了详细的解释。函数是代码的封装和组织方式,通过定义函数可以提高代码的重用性和可读性。学习者将了解到如何定义函数、调用函数、函数参数的传递以及函数返回值的使用。 4. 模块:Python学习笔记PDF中,介绍了Python中的模块和包的概念。模块是一组函数、类或变量的集合,以.py文件的形式存在,可以被其他程序调用和使用。学习者将学习如何导入模块、使用模块中的函数和变量。 5. 面向对象编程:Python学习笔记PDF中,对面向对象编程进行了系统的讲解。面向对象编程是一种以对象为基本单位的编程思想,通过定义类和对象,可以更好地组织和管理代码。学习者将了解如何定义类、创建对象、封装、继承和多态的使用。 6. 异常处理Python学习笔记PDF中,对异常处理进行了介绍。异常是程序在运行过程中出现的错误,通过捕获和处理异常,可以更好地控制程序的执行流程并提高程序的健壮性。学习者将了解到如何使用try-except语句来捕获和处理异常。 总之,Python学习笔记PDF是一份全面而详细的学习Python编程语言的资料,通过学习该资料,学习者将获得扎实的Python编程基础,并能够运用Python进行简单的程序开发

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值