python基础关卡3

本文介绍了Python的基础知识,包括字典的定义、创建、访问、修改和删除,集合的特性和操作,以及判断语句、三目表达式和循环语句的用法。详细阐述了while和for循环,以及break、continue和pass语句的应用。
摘要由CSDN通过智能技术生成

  1. dict字典
    a. 定义
    b. 创建
    c. 字典的方法
  2. 集合
    a… 特性
    b 创建
    c. 方法
  3. 判断语句(要求掌握多条件判断)
  4. 三目表达式
  5. 循环语句

1. dict字典

a 定义

字典是另一种可变容器模型,且可存储任意类型对象。

字典的每个键值(key=>value)对用冒号(:)分割,每个对之间用逗号(,)分割,整个字典包括在花括号({})中 ,格式如下所示:

d = {key1 : value1, key2 : value2 }

键必须是唯一的,但值则不必。

值可以取任何数据类型,但键必须是不可变的,如字符串,数字或元组。

b 创建字典

一个简单的字典实例:

dict = {'Alice': '2341', 'Beth': '9102', 'Cecil': '3258'}

也可如此创建字典:

dict1 = { 'abc': 456 };
dict2 = { 'abc': 123, 98.6: 37 };

c 访问字典里的值

把相应的键放入到方括号中,如下实例:

#!/usr/bin/python3
 
dict = {'Name': 'Doom Patrol', 'Age': 70, 'Class': 'First'}
 
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])

在这里插入图片描述

d 修改字典

向字典添加新内容的方法是增加新的键/值对,修改或删除已有键/值对如下实例:

#!/usr/bin/python3
 
dict = {'Name': 'Starcraft', 'Age': 70, 'Class': 'First'}
 
dict['Age'] = 8;               # 更新 Age
dict['School'] = "菜鸟教程"     # 添加信息
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

以上实例输出结果:

在这里插入图片描述

e 删除字典元素

能删单一的元素也能清空字典,清空只需一项操作。

显示删除一个字典用del命令,如下实例:

#!/usr/bin/python3
 
dict = {'Name': 'Runoob', 'Age': 7, 'Class': 'First'}
 
del dict['Name'] # 删除键 'Name'
dict.clear()     # 清空字典
del dict         # 删除字典
 
print ("dict['Age']: ", dict['Age'])
print ("dict['School']: ", dict['School'])

但这会引发一个异常,因为用执行 del 操作后字典不再存在:

  File "C:/Users/Administrator/.spyder-py3/temp.py", line 38, in <module>
    print ("dict['Age']: ", dict['Age'])

TypeError: 'type' object is not subscriptable

f 字典内置函数&方法

Python字典包含了一下内置函数:
在这里插入图片描述

python字典包含以下内置方法:

在这里插入图片描述

2. 集合

特性

集合(set)是一个无序的不重复元素序列。

可以使用大括号 { } 或者 set() 函数创建集合,注意:创建一个空集合必须用 set() 而不是 { },因为 { } 是用来创建一个空字典。

创建

创建格式:

parame = {value01,value02,...}

或者:

set (value)

实例:

>>>basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
>>> print(basket)                      # 这里演示的是去重功能
{'orange', 'banana', 'pear', 'apple'}
>>> 'orange' in basket                 # 快速判断元素是否在集合内
True
>>> 'crabgrass' in basket
False
 
>>> # 下面展示两个集合间的运算.
...
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  
{'a', 'r', 'b', 'c', 'd'}
>>> a - b                              # 集合a中包含而集合b中不包含的元素
{'r', 'd', 'b'}
>>> a | b                              # 集合a或b中包含的所有元素
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b                              # 集合a和b中都包含了的元素
{'a', 'c'}
>>> a ^ b                              # 不同时包含于a和b的元素
{'r', 'd', 'b', 'm', 'z', 'l'}

类似列表推导式,同样集合支持集合推导式(Set comprehension):

>>>a = {x for x in 'abracadabra' if x not in 'abc'}
>>> a
{'r', 'd'}

集合的基本操作

i 添加元素

s.add (x)

将元素 x 添加到集合 s 中,如果元素已存在,则不进行任何操作。

>>>thisset = set(("Google", "Youtube", "Taobao"))
>>> thisset.add("Facebook")
>>> print(thisset)
{'Taobao', 'Facebook', 'Google', 'Youtube'}

还有一个方法,也可以添加元素,且参数可以是列表,元组,字典等,语法格式如下:

s.update(x)
>>>thisset = set(("Google", "Youtube", "Taobao"))
>>> thisset.update({1,3})
>>> print(thisset)
{1, 3, 'Google', 'Taobao', 'Youtube'}
>>> thisset.update([1,4],[5,6])  
>>> print(thisset)
{1, 3, 4, 5, 6, 'Google', 'Taobao', 'Youtube'}
>>>

ii. 移除元素

s.remove(x)

将元素 x 从集合 s 中移除,如果元素不存在,则会发生错误。

>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.remove("Taobao")
>>> print(thisset)
{'Google', 'Runoob'}
>>> thisset.remove("Facebook")   # 不存在会发生错误
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'Facebook'

此外还有一个方法也是移除集合中的元素,且如果元素不存在,不会发生错误。格式如下所示:

s.discard(x)
>>>thisset = set(("Google", "Runoob", "Taobao"))
>>> thisset.discard("Facebook")  # 不存在不会发生错误
>>> print(thisset)
{'Taobao', 'Google', 'Runoob'}

我们也可以设置随机删除集合中的一个元素,语法格式如下:

s.pop()
thisset = set(("Google", "Runoob", "Taobao", "Facebook"))
x = thisset.pop()
 
print(x)

输出结果:

$ python3 test.py 
Runoob

在这里插入图片描述

3. 判断语句

Python条件语句是通过一条或多条语句的执行结果(True或者False)来决定执行的代码块。
Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。
Python 编程中 if 语句用于控制程序的执行,基本形式为:

if: # 判断条件:
    #执行语句……
else:
    #执行语句……

其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。

else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句,具体例子如下:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 例1if 基本用法
 
flag = False
name = 'luren'
if name == 'python':         	# 判断变量否为'python'
    flag = True           		# 条件成立时设置标志为真
    print 'welcome boss'    	# 并输出欢迎信息
else:
    print name              	# 条件不成立时输出变量名称

输出结果:

luren            # 输出结果

if 语句的判断条件可以用>(大于)、<(小于)、==(等于)、>=(大于等于)、<=(小于等于)来表示其关系。

当判断条件为多个值时,可以使用以下形式:

if 判断条件1:
    执行语句1……
elif 判断条件2:
    执行语句2……
elif 判断条件3:
    执行语句3……
else:
    执行语句4……

实例

#!/usr/bin/python
# -*- coding: UTF-8 -*-
# 例2:elif用法
 
num = 5     
if num == 3:            # 判断num的值
    print ('boss')        
elif num == 2:
    print ('user')
elif num == 1:
    print ('worker')
elif num < 0:           # 值小于零时输出
    print ('error')
else:
    print ('roadman')     # 条件均不成立时输出

输出结果为:

roadman

由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功。
example:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 例3if语句多个条件
 
num = 9
if num >= 0 and num <= 10:    # 判断值是否在0~10之间
    print ('hello')
# 输出结果: hello
 
num = 10
if num < 0 or num > 10:    # 判断值是否在小于0或大于10
    print ('hello')
else:
    print ('undefine')
# 输出结果: undefine
 
num = 8
# 判断值是否在0~5或者10~15之间
if (num >= 0 and num <= 5) or (num >= 10 and num <= 15):    
    print ('hello')
else:
    print ('undefine')
# 输出结果: undefine

当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。

简单语句组

你也可以在同一行的位置上使用if条件判断语句,如下实例:

#!/usr/bin/python 
# -*- coding: UTF-8 -*-
 
var = 100 
 
if ( var  == 100 ) : 
	print "变量 var 的值为100" 
 
print ("Good bye!")

4. 三目表达式

Python 中没有像 C 语言中一样直接使用 x?a:b 这样的三元表达式,但是它有两种替代方法:

方法一:

a if x else b

如果 x 为 True,返回 a;否则返回 b

>>> 'True' if 2 > 1 else 'False'
'True'
>>> 'True' if 2 < 1 else 'False'
'False'

方法二:
利用 and or 短路运算的特点

and 运算时,例如 a and b,如果 a 为 False 就不再判断b的值。

or运算时,例如 a or b,如果 a 为 True 就不再判断 b 的值。

假设表达式为:x and a or b。如果 x 为 True,会接着判断 a,如果 a 等同True,就返回 a 的值。

如果 a 等同 False,就计算 b,返回 b 的值。举个例子:

>>> 2 > 1 and 'True' or 'False'
'True'
>>> 2 < 1 and 'True' or 'False'
'False'

5. 循环语句

Python中的循环语句有 for 和 while。
Python循环语句的控制结构图如下所示:

a. while 循环

while 判断条件:
    语句

while loop 计算 1 到 100 的总和:

#!/usr/bin/env python3
 
n = 100
sum = 0
counter = 1
while counter <= n:
    sum = sum + counter
    counter += 1
 
print("1 到 %d 之和为: %d" % (n,sum))

Result:

1 到 100 之和为: 5050

b. 无限循环

我们可以通过设置条件表达式永远不为 false 来实现无限循环,实例如下:

#!/usr/bin/python3
 
var = 1
while var == 1 :  # 表达式永远为 true
   num = int(input("输入一个数字  :"))
   print ("你输入的数字是: ", num)
 
print ("Good bye!")

Result:

输入一个数字  :5
你输入的数字是:  5
输入一个数字  :

你可以使用 CTRL+C 来退出当前的无限循环。
无限循环在服务器上客户端的实时请求非常有用。

c. while 循环使用 else 语句

在 while … else 在条件语句为 false 时执行 else 的语句块:

#!/usr/bin/python3
 
count = 0
while count < 5:
   print (count, " 小于 5")
   count = count + 1
else:
   print (count, " 大于或等于 5")

Result:

0  小于 5
1  小于 5
2  小于 5
3  小于 5
4  小于 5
5  大于或等于 5

d.简单语句组

类似if语句的语法,如果你的while循环体中只有一条语句,你可以将该语句与while写在同一行中, 如下所示:

#!/usr/bin/python
flag = 1
while (flag): print ('Welcome to the Doom Manor!')
print ("Good bye!")

注意:以上的无限循环你可以使用 CTRL+C 来中断循环。
执行以上脚本,输出结果如下:

Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
Welcome to the Doom Manor!
......

e. for loop

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。
for循环的一般格式如下:

for <variable> in <sequence>:
    <statements>
else:
    <statements>

example:

>>>languages = ["C", "C++", "Perl", "Python"] 
>>> for x in languages:
...     print (x)
... 
C
C++
Perl
Python
>>>

以下 for 实例中使用了 break 语句,break 语句用于跳出当前循环体:

#!/usr/bin/python3
 
sites = ["zerg", "Protoss","Terran"]
for site in sites:
    if site == "zerg":
        print("heart of the swarm")
        break
    print("循环数据 " + site)
else:
    print("没有循环数据!")
print("完成循环!")

执行脚本后,在循环到 "zerg"时会跳出循环体:

循环数据 Zerg
循环数据 Protoss
My life for Auir
完成循环!

Process finished with exit code 0

f. range ()函数

如果你需要遍历数字序列,可以使用内置range()函数。它会生成数列,例如:

>>>for i in range(5):
...     print(i)
...
0
1
2
3
4

可以使用range指定区间的值:

>>>for i in range(5,9) :
    print(i)
5
6
7
8
>>>

可以使range以指定数字开始并指定不同的增量(甚至可以是负数,有时这也叫做’步长’):

>>>for i in range(0, 10, 3) :
    print(i)
 
    
0
3
6
9
>>>

负数:

>>>for i in range(-10, -100, -30) :
    print(i)
-10
-40
-70
>>>

您可以结合range()和len()函数以遍历一个序列的索引,如下所示:

>>>a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ']
>>> for i in range(len(a)):
...     print(i, a[i])
... 
0 Google
1 Baidu
2 Runoob
3 Taobao
4 QQ
>>>

可以使用range()函数来创建一个列表:

>>>list(range(5))
[0, 1, 2, 3, 4]
>>>

g. break和continue语句及循环中的else子句

break 语句可以跳出 for 和 while 的循环体。如果你从 for 或 while 循环中终止,任何对应的循环 else 块将不执行。 实例如下:

#!/usr/bin/python3
 
for letter in 'password':     # 第一个实例
   if letter == 'd':
      break
   print ('当前字母为 :', letter)
  
weight = 9                    # 第二个实例
while weight > 0:              
   print ('当期变量值为 :', weight)
   weight -=1
   if weight == 5:
      break
 
print ("Goodbye!")

Result:

当前字母为 : p
当前字母为 : a
当前字母为 : s
当前字母为 : s
当前字母为 : w
当前字母为 : o
当前字母为 : r
当期变量值为 : 9
当期变量值为 : 8
当期变量值为 : 7
当期变量值为 : 6
Goodbye!

Process finished with exit code 0

continue语句被用来告诉Python跳过当前循环块中的剩余语句,然后继续进行下一轮循环。

#!/usr/bin/python3

for letter in 'Thanos':     # 第一个实例
   if letter == 'n':        # 字母为 n 时跳过输出
      continue
   print ('当前字母 :', letter)

minute = 10                    # 第二个实例
while minute > 0:
   minute -=1
   if minute == 5:             # 变量为 5 时跳过输出
      continue
   print ('当前变量值 :', minute)
print ("Goodbye!")

Result

当前字母 : T
当前字母 : h
当前字母 : a
当前字母 : o
当前字母 : s
当前变量值 : 9
当前变量值 : 8
当前变量值 : 7
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
Goodbye!
Process finished with exit code 0

循环语句可以有 else 子句,它在穷尽列表(以for循环)或条件变为 false (以while循环)导致循环终止时被执行,但循环被break终止时不执行。
如下实例用于查询质数的循环例子:

for n in range(2, 20):
    for x in range(2, n):
        if n % x == 0:
            print(n, '等于', x, '*', n//x)
            break
    else:
        # 循环中没有找到元素
        print(n, ' 是质数')

Result

2  是质数
3  是质数
4 等于 2 * 2
5  是质数
6 等于 2 * 3
7  是质数
8 等于 2 * 4
9 等于 3 * 3
10 等于 2 * 5
11  是质数
12 等于 2 * 6
13  是质数
14 等于 2 * 7
15 等于 3 * 5
16 等于 2 * 8
17  是质数
18 等于 2 * 9
19  是质数

Process finished with exit code 0

h. pass 语句

pass是空语句,是为了保持程序结构的完整性。
pass 不做任何事情,一般用做占位语句,举个例子;

>>>while True:
...     pass  # 等待键盘中断 (Ctrl+C)
for letter in 'Thanos':
   if letter == 'o':
      pass
      print ('执行 pass 块')
   print ('当前字母 :', letter)

print ("Goodbye!")
当前字母 : T
当前字母 : h
当前字母 : a
当前字母 : n
执行 pass 块
当前字母 : o
当前字母 : s
Goodbye!

Process finished with exit code 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值