Python基础-流程控制

Python基础-流程控制

条件语句

if语句

Python条件语句是通过一条或多条语句的执行结果(True或False)来决定执行的代码块。

graph TD A[开始] B{条件} C[条件代码] D[结束] A-->B B--条件为True-->C B--条件为False-->D C-->D

代码的执行过程:

	if (<expr>):  ----------false----
true|     <statement>                |
    |     <statement>                |
    |     ...                        |
|---|     <statement>                |
|---><following_statement> <---------|        

if语句的一般形式

if condition_1:
    statement_block_1
elif condition_2:
    statement_block_2
else:
    statement_block_3

1、若condition_1为True将执行statement_block_1块语句

2、若condition_1为False,将判断condition_2

3、若contidion_2为True将执行statement_block_2块语句

4、若condtion_2为False,将执行statement_block_3块语句

Python中用elif代替了else if,所以if语句的关键字为:if-elif-else

注意:

1、每个条件后面要使用冒号:,表示接下来是满足条件后要执行的语句块。

2、使用缩进来划分语句块, 相同缩进数的语句在一起组成一个语句块

3、在Python中没有switch-case语句。

以下是代码示例:

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')

以下为if中常用的操作运算符:

操作符 描述
< 小于
<= 小于等于
> 大于
>= 大于等于
== 等于,比较两个值是否相等
!= 不等于
>>> print(5 == 6)
False
>>> print(5 > 6)
False
>>> print(5 < 6)
True
>>> print(5 != 6)
True

if嵌套

在嵌套if语句中,可以把if...elif...else结构放到另外一个if...elif...else结构中。 代码形式如下:

if 表达式1:

​ 语句

​ if 表达式2:

​ 语句

​ elif 表达式3:

​ 语句

​ else:

​ 语句

elif 表达式4:

​ 语句

else:

​ 语句

实例:

num = int(input("输入一个数字:"))
if num % 2 == 0:
    if num % 3 == 0:
        print('输入的数字可以整除2和3')
    else:
        print('输入的数字可以整除2, 但不能整除3')
else:
    if num % 3 == 0:
        print('输入的数字可以整除3, 但不能整除2')
    else:
        print('输入的数字不能整除2和3')

循环语句

Python中循环语句有for和while。

Python中循环语句的控制结构如下图所示:

graph TD A[开始] B{条件} C[条件代码] D[结束] A-->B B--条件为true-->C C-->B B--条件为false-->D

while循环

Python中while循环语句的一般形式:

while 判断条件(condition):

​ 执行语句(statements)...

在Python中没有do...while循环。

以下实例使用了while来计算1到100的总和:

n = 100
sum = 0
counter = 1
while counter <= 100:
    sum += counter
    counter += 1
print("1 到 %d之和为: %d" % (n, sum))

while循环使用else语句

在while...else在条件语句为false时执行else的语句块。

语法格式如下:

while :

​ <statement(s)>

else:

​ <additional_statement(s)>

循环输出数字, 并判断大小实例:

count = 0
while count < 5:
    print(count, " 小于 5")
    count = count + 1
else:
    print(count, ' 大于或等于5')

无限循环

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

var = 1
while var == 1:
    num = int(input('输入一个数字:'))
    print('你输入的数字为:',num)
    
print('Good bye!')

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

for循环

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

for循环的一般格式如下:

for in :

else:

Python for 循环实例

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

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

sites = ['baidu', 'google', 'taobao', 'alibaba']
for site in sites:
    if site == 'taobao':
        print('淘宝')
        break
    print('循环数据+' + site)
else:
    print('没有循环数据')
print('完成循环')

range()函数

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

for i in range(5):
    print(i)
# 可以使用range指定数字开始指定不同的增量,看(可以是负数, 有时候也叫步长)
for i in range(0, 10, 3):
    print(i)
# 可以结合range()和len()函数遍历一个序列的索引
a = ['google', 'baidu', 'taobao', 'qq']
for i in range(len(a)):
    print(i, a[i])
# 可以使用range()函数来创建一个列表
print(list(range(5)))

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

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

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

循环语句可以有else子句, 它在穷尽列表(以for循环)或条件变为false(以while循环)导致循环终止时被执行, 但是循环被break终止时不执行。

以下示例说明:

# while 中使用break
n = 5 
while n > 0:
    n -= 1
    if n == 2:
        break
    print(n)
print('循环结束。')

# while中使用continue
n = 5
while n > 0:
    n -= 1
    if n == 2:
        continue
    print(n)
print('循环结束。')

# for中使用break
for letter in 'python':
    if letter == 'o':
        break
    print('当前字母为:', letter)

# for中使用continue
for letter in 'python':
    if letter == 'o':
        continue
    print('当前字母为:', letter)

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

pass语句

Python pass是空语句, 是为了保持程序结构的完整性。

pass不做任何事情, 一般用作占位语句。

>>> while True:
...		pass 
posted @ 2020-10-13 09:40  phper-liunian  阅读(141)  评论(0编辑  收藏  举报