Python笔记③ 控制流

一,if语句

1,语句介绍

if是条件控制语句
if condition_fisrt:
	statement_first
elif condition_second:
	statement_second
else:
	statement_third
简单例子
a = 4   #定义变量a的值为4
b = 5   #定义变量b的值为5
if a>b: #如果a大于b
    c = a   #c等于a
else:       #否则
    c = b   #c等于b
print(c)   #很简单理解如果怎样,满足条件的话就执行相应额度语句 #打印输出c
输出
5

2,简化写法

c = [a,b][a<b] 
这里第二个方括号为条件判断部分,第一个方括号为输出部分
True输出b,False输出a
getstr = input("请输入性别:")
anstr = ['Gentlemen','Lady'][('female' or '女') == getstr.strip()]
print('Hi,',anstr,',welcome!')
输出
请输入性别:女
Hi, Gentlemen ,welcome!

二,while语句

1,语句介绍

while是循环执行语句,条件为True则执行循环内容
while condition:
	statement
简单例子
c = 5
while c>0:
    print(c)
    c -= 1
输出
5
4
3
2
1

2,十进制 to 二进制例子

a = input("Please enter a Decimal number:")
d = int(a)
s = " "
while d != 0:
    d,f = divmod(d,2)
    s = str(f) + s
print(s)
输出
Please enter a Decimal number:4
100 

三,for语句

1,语句介绍

for也是循环执行语句,它与while不同的地方是,它循环的是序列(sequence)容器
for item in sequence:
	statement1

2, for中用切片

words = ['I','like','Python']
for item in words[:]:
    words.insert(0,item)
    print(item)
print(words)
输出
I
like
Python
['Python', 'like', 'I', 'I', 'like', 'Python']

3,for中用range

for i in range(5):
    print(i)
输出
0
1
2
3
4

4,冒泡法排序

#bubble sort
n = [5,8,20,1]
print("原数据:",n)

for i in range(len(n) - 1):
    for j in range(len(n) - i - 1):
        if n[j] > n[j+1]:
            n[j],n[j+1] = n[j+1],n[j]
            
print("Atfer bubble sort:",n)
输出
原数据: [5, 8, 20, 1]
Atfer bubble sort: [1, 5, 8, 20]

5,for中用zip

x = [1,2,3,4,5,6]
y = (3,2,"hello")
for t1,t2 in zip(x,y):
    print(t1,t2)
输出
1 3
2 2
3 hello

6,for中用enumerate

x = ["hello",4,3.1453]
for i,item in enumerate(x):
    print(i,' ',item)
输出
0   hello
1   4
2   3.1453

四,break、continue、pass循环控制语句

1,语句简介

  1. break:跳出当前的循环
  2. continue:终止这一次执行,进入下一次循环
  3. pass:什么操作都不执行,用于结构上保持代码完整

五,循环综合例子

1,模拟人机语音交互控制流程

getstr = ''                                 #定义一个空字符串,用来接收输入
while("Bye"!=getstr):                       #使用while循环
    if ''==getstr:                          #如果输入字符为空,输出欢迎语句
        print("hello! Password!")
    getstr = input("请输入字符,并按回车结束:") #调用input函数,获得输入字符串
    if 'hello'==getstr.strip():             #如果输入字符串为hello,启动对话服务
        print('How are you today?')
        getstr = "start"                    #将getstr设为start,标志是启动对话服务                
    elif 'go away'==getstr.strip():         #如果输入的是go away,则退出
        print('sorry! bye-bye')
        break                              #使用break语句退出循环
    elif 'pardon'==getstr.strip():         #如果是pardon 重新再输出一次
        getstr = ''
        continue                           #continue将结束本次执行,开始循环的下一次执行
    else:
        pass                               #什么也不做,保持程序完整性
    if 'start'== getstr:                   #如果getstr为start,启动对话服务
        print('...init dialog-serving...') #伪代码,打印一些语句,代表启动了对话服务
        print('... one thing...')
        print('... two thing...')    
        print('......')

2,for实现列表推导式

Y = [1,1,1,0,1,1,0]
color = ['r' if item == 0 else 'b' for item in Y[:]]
print(color)

3,for打印“九九乘法表”

for x in range(1,10):
    l = ['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]    
    for i in range(len(l)):
        print(l[i],end=' ')
    print('')
    
    
for x in range(1,10):
    l = ['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]    
    print(' '.join(l[i] for i in range(len(l))))
    
print ('\n'.join([' '.join(['%s*%s=%-2s' % (y,x,x*y) for y in range(1,x+1)]) for x in range(1,10)]))

4,for循环的原理———迭代器

for语句的循环次数,由序列容器的数据个数决定
在循环过程中,隐式的使用了内置函数iter()

x = [1,2,3]
it = iter(x)

print(it.__next__())
print(it.__next__())
print(it.__next__())
#迭代完后再执行就会报错
#print(it.__next__())

x = [1,2,3]
it = iter(x)

print(next(it))
print(next(it))
print(next(it))
#print(next(it))

结束语:由于时间原因,以上内容肯定存在错误或不妥之处,欢迎指出,谢谢!

发布了34 篇原创文章 · 获赞 9 · 访问量 3031

猜你喜欢

转载自blog.csdn.net/RObot_123/article/details/103392528