# 【python基础】6-控制结构

2018-02-27 11:14:25来源:https://www.jianshu.com/p/968e00a326e5作者:王诗翔人点击

if
for
while
continue和break

``>>> num = 5>>> num > 2True>>> num > 3 and num <= 5True>>> 3 < num <= 5True>>> num % 3 == 0 or num % 5 == 0True>>> fav_fiction = 'Harry Potter'>>> fav_detective = 'Sherlock Holmes'>>> fav_fiction == fav_detectiveFalse>>> 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``

``>>> 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``

`(10, 21, 33)`是一个元组数据类型，会在后面的章节讲解
Python文档 - 真值检验

if
``#!/usr/bin/python3num = 45# 单个ifif num > 25:    print("Hurray! {} is greater than 25".format(num))# if-elseif num % 2 == 0:    print("{} is an even number".format(num))else:    print("{} is an odd number".format(num))# if-elif-else# 可以使用任意数目的elifif 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))``

Python文档 - 编码风格

``\$ ./if_elif_else.pyHurray! 45 is greater than 2545 is an odd number45 is a positive number``

if-else作为条件操作符

``#!/usr/bin/python3num = 42num_type = 'even' if num % 2 == 0 else 'odd'print("{} is an {} number".format(num, num_type))``

``\$ ./if_else_oneliner.py42 is an even number``

for
``#!/usr/bin/python3number = 9for i in range(1, 5):    mul_table = number * i    print("{} * {} = {}".format(number, i, mul_table))``

Python文档 - 迭代工具
``\$ ./for_loop.py9 * 1 = 99 * 2 = 189 * 3 = 279 * 4 = 36``

while
``#!/usr/bin/python3# 持续地询问直到用户输入一个正整数usr_string = 'not a number'while not usr_string.isnumeric():    usr_string = input("Enter a positive integer: ")``

while循环允许我们直到某个条件被满足之前不断执行语句块
Python docs - 字符串方法
``\$ ./while_loop.pyEnter a positive integer: abcEnter a positive integer: 1.2Enter a positive integer: 23\$``

continue和break

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

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

``#!/usr/bin/python3prev_num = 0curr_num = 0print("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 = tempprint("")``

`continue`放置在循环代码块中的任意位置而不用担心复杂的代码流

``\$ ./loop_with_continue.pyThe first ten numbers in fibonacci sequence: 0 1 1 2 3 5 8 13 21 34``

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

``#!/usr/bin/python3import randomwhile True:    # 使用range函数注意500没有包含在内    random_int = random.randrange(500)    if random_int % 4 == 0 and random_int % 6 == 0:        breakprint("Random number divisible by 4 and 6: {}".format(random_int))``

`while True:`是常用作无限循环
randrange和range函数相似，有`start, stop, step`参数
Python文档 - random
``\$ ./loop_with_break.pyRandom number divisible by 4 and 6: 168\$ ./loop_with_break.pyRandom number divisible by 4 and 6: 216\$ ./loop_with_break.pyRandom number divisible by 4 and 6: 24``

``>>> while True:         usr_string = input("Enter a positive integer: ")         if usr_string.isnumeric():             breakEnter a positive integer: aEnter a positive integer: 3.14Enter a positive integer: 1>>>``

Python文档 - 循环中的else从句