Python-4-Python控制语句执行流程

4-1 介绍If执行语句

语法:

if condition
    expression //换行后默认缩进2个空格,相同缩进的是同一语句体
other_expression

如果 condition 为 True, 将会执行 expression 里面语句的内容。还行完 expression 语句后,会继续向下执行 other_expression 里面的语句。

如果 condition 为 False, 将会跳过 expression 语句,向下执行 other_expression 里面的语句。

例子:

a=True
if a:
    print('if ok 1');
    print('if ok 2');
print('end');
-----------------------
if ok 1
if ok 2
end

=======================

a=False
if a:
    print('if ok 1');
    print('if ok 2');
print('end');
-----------------------
end

=======================

a=1;
b=2;
if a == b :
    print('a == b');
print('end');
-----------------------
end

 

4-2 if-else执行语句

语法:

if condition
    true_expression //换行后默认缩进2个空格,相同缩进的是同一语句体
else
    false_expression
other_expression

例子:

a=1;
b=2;
if a == b:
    print('a == b');
else:
    print('a != b');
print('end');
-----------------------
a != b
end

 

4-3 if-else 的不足之处

input() 会接收输入数据,返回string类型

num_str=input('please input num:') #会弹出一个输入框让你输入
type(num_str) #str
num=int(num_str) #将字符串转换为十进制数
type(num) #int

实验:

num_str=input('please input num:')
weather=int(num_str)
if weather ==1:
    print('春天');
else:
    if weather == 2:
        print('夏天');
    else:
        if weather == 3:
            print('秋天');
        else:
            if weather == 4:
                print('冬天');
            else:
                print('Please input 1-4');

嵌套太深,代码较乱。if-else应该用在条件判断较少的情况下。


4-4 完善 if-else 的不足之处

1. 语法

if condition1:
    expression1
elif condition2:
    expression2
elif condition3:
    expression3
else:
    expression

例子:

num_str=input('please input num:')
weather=int(num_str)
if weather ==1:
    print('春天');
elif weather == 2:
    print('夏天');
elif weather == 3:
    print('秋天');
elif weather == 4:
    print('冬天');
else:
    print('Please input 1-4');

 

4-5 for循环

for循环,循环遍历一个可迭代对象,主要是用来遍历序列(列表、字符串、元组)、字典、集合

语法:

for 循环变量 in 可迭代对象
    <语句1>
else:
    <语句2> #只是执行完后最后一次执行

例子:

#字符串
str='I am lemon';
for c in str:          #注意这里的冒号
    print(c, end=' '); #不加end每次输入后都带换行
-----------------------
I   a m   l e m o n 

=======================

#列表
fruits = ['apple', 'lemon', 'pear'];
for f in fruits:
    print(f);
else:
    print('loop end');
-----------------------
apple
lemon
pear
loop end

=======================

#字典:
fruits = {'apple':5, 'lemon':10, 'pear':15};
for f in fruits.keys(): #遍历字典的key,改为fruits.values():是遍历字典的值
    print(f);
-----------------------
apple
lemon
pear
=======================
#同时打印字典的键和值
fruits = {'apple':5, 'lemon':10, 'pear':15};
for k,v in fruits.items():
    print(k, v);
-----------------------
apple 5
lemon 10
pear 15

=======================

#嵌套列表
complex_list = [['apple', 'lemon', 'pear'], [5, 10, 15]];
for x in complex_list:
    print(x);
-----------------------
['apple', 'lemon', 'pear']
[5, 10, 15]
=======================
complex_list = [['apple', 'lemon', 'pear'], [5, 10, 15]];
for x in complex_list:
    for y in x:
        print(y);
-----------------------
apple
lemon
pear
5
10
15

 

4-6 range() 函数用法

1. 说明

range(start, end[, step])

start: 计数从 start 开始,默认从0开始,比如 range(10) 等价于 range(0, 10)
end: 以 end 结束,但是并不包括 end, 如 range(0, 5) 是 [0, 1, 2 ,3, 4]
step: 步长,默认为1,如 range(0, 5) 等价于 range(0, 5, 1) 

此函数根据我们设定的规则,生成一个序列,生成的序列可供for循环遍历。注意 range 里面只能是整形类型。

2. 用法:

for 循环变量 in range(start, end[, step]):
    <执行语句>
else:
    <执行语句>

例子:

for i in range(0, 10, 4):
    print(i)
-----------------------
0
4
8

 

4-7 For循环与continue、break语句的使用(一)

例子:

fruits=['apple','lemon','pear','lemon','banana','grape','banana','apple'];
for f in fruits:
    if f == 'lemon':
        continue
    if f == 'grape':
        break
    print(f, end=' ');
-----------------------
apple pear banana 

 

4-8 For循环与continue、break语句的使用(二)

例子

#什么也不打印跳出最外层循环
a=[['A', 'B', 'C'],[1, 2, 3]];
for x in a:
    if 'B' in x:
        break

 

4-9 For语句与内置迭代函数

Python 内置了4种常用迭代函数,有:
enumerate(seq) #迭代编号
sorted(seq) #排序迭代
reveraed(seq) #翻转迭代
zip(seq1, seq2...) #并行迭代

seq 为可遍历/可迭代的对象,如列表、字符串、元组。

1. enumerate()

编号迭代,迭代的时候返回序列中的编号(默认从0开始),又返回序列中的元素。需要2个循环变量,分别接收编号和元素的值。

a='abcd';
for index,value in enumerate(a):
    print(index, value);
-----------------------
0 a
1 b
2 c

2. sorted()

排序迭代,for循环遍历的时候,默认先遍历序列中较小的值,再遍历序列中较大的值(函数参数中加 reverse=True可以反向)。可迭代对象中的元素,需要是可排序的同类数据。

a=[1,5,3,2];
for i in sorted(a, reverse=True):
    print(i, end=' ')
-----------------------
5 3 2 1 

3. reveraed()

翻转迭代,对可迭代对象中的元素从尾到头进行遍历。注意不是大小排序。

a=[1,5,3,2];
for i in reversed(a):
    print(i, end=' ')
-----------------------
2 3 5 1 

3. zip()

同时遍历可迭代对象中,同一序号元素。如果元素长度不一致,只遍历到最短的序列长度。

x=[1, 2]
y=[3, 4]
z=[5, 6, 7]
for a,b,c in zip(x, y, z):
    print(a, b, c)
-----------------------
1 3 5
2 4 6

 

4-10 while循环

while循环在,只有当条件为假的时候才会结束循环。

格式:

while <条件><语句1>
else:
    <语句2>

例子:

a=1;
while a < 5:
    print(a);
    a += 1;
-----------------------
1
2
3
4

 

4-11 猜数字游戏

例子

import random
random_num = random.randint(0, 9)
times = 3
while times > 0:
    guess_num = int(input('Please input 0-9:')) #输入的是str转换为int
    if guess_num > random_num:
        print('guess num big');
    elif guess_num < random_num:
        print('guess num small');
    else:
        print('you hit it, answer is ' + str(random_num)); #将整型转换为字符型才能用+连接
        break
    times -= 1; #没有times--
    if times == 0:
        print('you are failed, answer is ' + str(random_num))
        break
-----------------------
Please input 0-9:5
guess num small
Please input 0-9:7
you hit it, answer is 7

 

posted on 2023-08-01 14:40  Hello-World3  阅读(15)  评论(0编辑  收藏  举报

导航