栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python零基础入门-3 流程控制

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python零基础入门-3 流程控制

流程控制即控制代码执行的顺序。Python中的流程控制一般通过判断、循环语句实现。

本文思维导图:

一、判断

1.1 if语句

最常用的判断语句是if语句:

例:if语句

x = int(input("Please enter an integer: "))​if x < 0:    x = 0    print('Negative changed to zero')elif x == 0:    print('Zero')elif x == 1:    print('Single')else:    print('More')

注1:这里if下面的语句有4个空格缩进,说明下面的两行语句是属于if语句的。Python中用缩进表示代码所属级别。

注2:elif即对else if的缩写。

(用户输入一个整数存到变量x中,然后对x进行判断。

如果x小于0,就让给x赋值0,并且使用print输出消息Negative changed to zero;否则,如果x等于0,就输出消息Zero;否则,如果x等于1,输出消息Single;否则,以上都不符合,输出消息More。)

if语法:

if 条件:    命令1elif 条件:    命令2...可以有更多elif...else:    命令n


二、循环

2.1 for语句

Python中最常用的循环是for语句。典型用法是用for来遍历一个列表(或任意可迭代对象)

例:使用for语句打印words中单词及其长度。

words = ['cat', 'window', 'defenestrate']for w in words:    print(w, len(w))

for -in语法:

for x in 可迭代对象:    语句

2.2 遍历集合

遍历集合时修改集合的内容,会很容易生成错误的结果。因此不能直接进行循环,而是应遍历该集合的副本或创建新的集合:

#创建一个集合。集合就是一些“键:值”形式的键值对。users = {'Hans': 'active', 'Éléonore': 'inactive', '景太郎': 'active'}​# 在副本上迭代for user, status in users.copy().items():    if status == 'inactive':        del users[user]​# 或者创建新集合active_users = {}for user, status in users.items():    if status == 'active':        active_users[user] = status

2.3 range()函数

range可当成是一种不可变序列。 range(start, stop[, step]),range可以传入三个参数,起始值,终止值,步长。其中,start默认值为0,步长默认为1。

range的典型用法就是只指定stop,用于循环指定次数。

for i in range(5):    print(i)

range(5)就能循环5次:

01234

range()三参数形式start, stop[, step]:

list(range(0, 10, 3)) #[0, 3, 6, 9]

使用len()和range()可以按索引迭代序列(不推荐)。

a = ['Mary', 'had', 'a', 'little', 'lamb']for i in range(len(a)):    print(i, a[i])

推荐使用更简洁的enumerate:

a = ['Mary', 'had', 'a', 'little', 'lamb']for i,x in enumerate(a):    print(i,x)

2.4 while循环

while循环用于在某些条件下进行循环,条件为假时,循环结束:

a, b = 0, 1while a < 10:    print(a)    a, b = b, a+b​

while语法:

while 条件为真:    执行...

2.5 循环中的break,continue语句

break 语句和 C 中的类似,用于跳出最近的 for 或 while 循环。

continue 语句也借鉴自 C 语言,表示继续执行循环的下一次迭代。

for i in range(1, 100):    if i % 7 == 0 and i % 5 == 0:        print(i)        print(i, " is good")

使用break,会直接跳出所在的for循环

#例子break。for i in range(1,100):    if i % 7 == 0 and i % 5 == 0:        print(i)        break     #会结束所在的for循环        print(i, " is good")

使用continute会跳过下面的语句,继续下一次循环。

# continue例子for i in range(1, 100):    if i % 7 == 0 and i % 5 == 0:        print(i)        continue        print(i, " is good") #会被跳过

2.6 for-else语法(不推荐)

循环结束时执行else,break停止循环时不执行。

# for- else​for i in range(5):    if i**1 +i**2 + i**3 > 200:        print("find ",i)        breakelse:    print("not find")​#not find

 循环结束,没有break,就执行else子句。

# for- else​​for i in range(10):    if i**1 +i**2 + i**3 > 200:        print("find ",i)        breakelse:    print("not find")​#find  6

 循环被break提前结束,不执行else子句。


三、其它

3.1 pass语句

pass语句什么都不做,通常当做占位符。

比如我们预期将来要写一个函数,可以先使用pass占位,后面再实现实际功能。

def initlog(*args):    pass   # Remember to implement this!

3.2 match

match语句是Python3.10新特性,用来匹配目标。

def http_error(status):    match status:        case 400:            return "Bad request"        case 404:            return "Not found"        case 418:            return "I'm a teapot"        case _:            return "Something's wrong with the internet"

变量名” _ 被作为 通配符 并必定会匹配成功

除了字面值,match还可以匹配模式。

# point is an (x, y) tuplematch point:    case (0, 0):        print("Origin")    case (0, y):        print(f"Y={y}")    case (x, 0):        print(f"X={x}")    case (x, y):        print(f"X={x}, Y={y}")    case _:        raise ValueError("Not a point")

类形式:

class Point:    x: int    y: int​def where_is(point):    match point:        case Point(x=0, y=0):            print("Origin")        case Point(x=0, y=y):            print(f"Y={y}")        case Point(x=x, y=0):            print(f"X={x}")        case Point():            print("Somewhere else")        case _:            print("Not a point")

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/893257.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号