【python基础】6-控制结构


条件检查

  • 单个和组合测试
>>> num = 5
>>> num > 2
True
>>> num > 3 and num <= 5
True
>>> 3 < num <= 5
True
>>> num % 3 == 0 or num % 5 == 0
True

>>> fav_fiction = 'Harry Potter'
>>> fav_detective = 'Sherlock Holmes'
>>> fav_fiction == fav_detective
False
>>> fav_fiction == "Harry Potter"
True
  • 测试变量和值本身
>>> bool(num)
True
>>> bool(fav_detective)
True
>>> bool(3)
True
>>> bool(0)
False
>>> bool("")
False
>>> bool(None)
False

>>> if -1:
...     print("-1 evaluates to True in condition checking")
...
-1 evaluates to True in condition checking
  • 条件测试中in操作符的使用

对比这种检查方式

>>> def num_chk(n):
...     if n == 10 or n == 21 or n == 33:
...         print("Number passes condition")
...     else:
...         print("Number fails condition")
...
>>> num_chk(10)
Number passes condition
>>> num_chk(12)
Number fails condition

和另一种

>>> def num_chk(n):
...     if n in (10, 21, 33):
...         print("Number passes condition")
...     else:
...         print("Number fails condition")
...
>>> num_chk(12)
Number fails condition
>>> num_chk(10)
Number passes condition


if

#!/usr/bin/python3

num = 45

# 单个if
if num > 25:
    print("Hurray! {} is greater than 25".format(num))

# if-else
if num % 2 == 0:
    print("{} is an even number".format(num))
else:
    print("{} is an odd number".format(num))

# if-elif-else
# 可以使用任意数目的elif
if num < 0:
    print("{} is a negative number".format(num))
elif num > 0:
    print("{} is a positive number".format(num))
else:
    print("{} is neither postive nor a negative number".format(num))
  • 函数代码块、控制结构等等都是通过缩进区分
  • 一个常见的语法错误是忘记了控制结构语句后的:
  • 条件周围的()是可选的
  • 缩进代码块可以有任意数目的语句,包括空行
$ ./if_elif_else.py
Hurray! 45 is greater than 25
45 is an odd number
45 is a positive number

if-else作为条件操作符

#!/usr/bin/python3

num = 42

num_type = 'even' if num % 2 == 0 else 'odd'
print("{} is an {} number".format(num, num_type))
$ ./if_else_oneliner.py
42 is an even number


for

#!/usr/bin/python3

number = 9
for i in range(1, 5):
    mul_table = number * i
    print("{} * {} = {}".format(number, i, mul_table))
  • 传统基于循环的迭代可以通过使用range函数实现
    • 默认参数start=0step=1,不含stop
  • 针对列表、元组等等变量的迭代会在后续章节讲述
  • Python文档 - 迭代工具
$ ./for_loop.py
9 * 1 = 9
9 * 2 = 18
9 * 3 = 27
9 * 4 = 36


while

#!/usr/bin/python3

# 持续地询问直到用户输入一个正整数
usr_string = 'not a number'
while not usr_string.isnumeric():
    usr_string = input("Enter a positive integer: ")
$ ./while_loop.py
Enter a positive integer: abc
Enter a positive integer: 1.2
Enter a positive integer: 23
$


continue和break

continuebreak关键字用于在某些条件下改变正常的循环操作

continue - 跳过循环代码块余下的语句并进入下一次迭代

#!/usr/bin/python3

prev_num = 0
curr_num = 0
print("The first ten numbers in fibonacci sequence: ", end='')

for num in range(10):
    print(curr_num, end=' ')

    if num == 0:
        curr_num = 1
        continue

    temp = curr_num
    curr_num = curr_num + prev_num
    prev_num = temp

print("")
  • continue放置在循环代码块中的任意位置而不用担心复杂的代码流
  • 这个例子仅仅展示continue的使用,查看这里获取更加Python化的操作方式
$ ./loop_with_continue.py
The first ten numbers in fibonacci sequence: 0 1 1 2 3 5 8 13 21 34

break - 跳过循环代码块余下的语句(如果有)并进入退出循环代码块

#!/usr/bin/python3

import random

while True:
    # 使用range函数注意500没有包含在内
    random_int = random.randrange(500)
    if random_int % 4 == 0 and random_int % 6 == 0:
        break
print("Random number divisible by 4 and 6: {}".format(random_int))
$ ./loop_with_break.py
Random number divisible by 4 and 6: 168
$ ./loop_with_break.py
Random number divisible by 4 and 6: 216
$ ./loop_with_break.py
Random number divisible by 4 and 6: 24

这个while_loop.py例子可以用break语句重写

>>> while True:
         usr_string = input("Enter a positive integer: ")
         if usr_string.isnumeric():
             break

Enter a positive integer: a
Enter a positive integer: 3.14
Enter a positive integer: 1
>>>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,475评论 4 372
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,744评论 2 307
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,101评论 0 254
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,732评论 0 221
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,141评论 3 297
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,049评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,188评论 2 320
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,965评论 0 213
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,716评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,867评论 2 254
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,341评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,663评论 3 263
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,376评论 3 244
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,200评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,990评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,179评论 2 285
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,979评论 2 279

推荐阅读更多精彩内容

  • 前言 ||| 第二章 使用ArcPy编写脚本 Python支持大部分在其他语言中出现的编程结构。在本章内容中,我们...
    muyan阅读 89,588评论 10 55
  • Swift 提供了类似 C 语言的流程控制结构,包括可以多次执行任务的for和while循环,基于特定条件选择执行...
    穷人家的孩纸阅读 673评论 1 1
  • 你有没有那么一个她 不见 会思念 见面 会互损 我有那么一个她 她在家 我在外市 我回家 她去外市 我有那么一个她...
    遇见方知有你阅读 188评论 0 5
  • 尊敬的各位家长:您好! 教师节快到了,在这里祝您教师节快乐。作为父亲母亲,您可能已经忘记,您是孩子人生路上的领路人...
    历事炼心阅读 935评论 2 2
  • 学习了四天最喜欢“毕业演讲:愿你遭遇不幸和痛苦”。 事情要往最坏的一面去想 去打算 意外来临时才不会措手不及,...
    kyle房成阅读 203评论 0 0