Python条件、循环语句

Python中不靠{}花括号来区分代码块,而是靠缩进来区分代码块,缩进的空格数是可变的,以4个空格为一段,但是同一个代码块的语句必须保持相同的缩进

流程控制语句

条件控制:if语句

例1:
更改mood的值下面输出的内容会变化

mood =True
if mood:
    print("mood is True")

例2:

a=1
b=2
c=2
if not a or b + 1 == c:
    print("go left")
else:
    print("go right")

例3:

d=[]
if d:
    print("d is not empty")
else:
    print("d is empty")

例4:下面模拟一个用户登录的环境,用到input函数

ACCOUNT=“admin”
password=“123456”

以上两行会提示:Constant name "password" doesn't conform to UPPER_CASE naming style。原因是常量constant常量的命名要大写

ACCOUNT="admin"
PASSWORD="123456"
usr_account=input("请输入用户名:")
usr_password=input("请输入密码:")
if usr_account == ACCOUNT and usr_password == PASSWORD:
    print("登录成功")
else:
    print("登录失败")

以上的内容称作为一个模块,推荐用模块化设计,一个个调用,很方便

代码块:非常不推荐这么写

if condition:
    code1
    code2
        code11
        code22
            code111
            code222

if嵌套:也不推荐这么写,典型的面向过程,没有任何的封装思维,推荐用函数把嵌套的代码块封装起来,然后调用函数

if condition1:
    code1
        if condition2:
           code2
        else:
           code3
 else:
    code4
        if condition3:
           code5

if嵌套+函数+模块化:推荐这么写,模块化设计,封装性好,可读性高,可维护性高

举例:找出下面if嵌套的问题

a = input()
if a == 1:
    print ('apple')
else:
    if a == 2:
        print ('banana')
    else:
        if a == 3:
            print ('orange')
        else:
            print ('go shopping')

发现无论输入几,都是输出'go shopping'

使用elif简化上面的代码:在其他的语言里switch语句更适合描述这类嵌套,但很可惜python没有switch语句,官方建议用字典的方式描述,也很优雅

a = input()
if a == 1:
    print ('apple')
elif a == 2:
    print ('banana')
elif a == 3:
    print ('orange')
else:
    print ('go shopping')

发现还是一样的问题
动态语言的缺点就来了,不用定义变量导致它出问题不会报错

解决:问题出在'a == 1; a ==2; a == 3',实际上在终端里输入的内容都是str类型,也就是终端输入1,实际上是'1',拿str类型与int类型比较,肯定是不满足的

修改为:

a = input()
a = int(a)
if a == 1:
    print ('apple')
elif a == 2:
    print ('banana')
elif a == 3:
    print ('orange')
else:
    print ('go shopping')
#或者不添加'a=int(a)',修改a == '1' ; a == '2' ; a == '3'

循环语句:while循环for循环

例1:while循环

CONDITION = True
while CONDITION:
    print('hello')
#这段代码会不断输出'hello',原因在于当CONDITION的值不发生改变,while就会一直判断下去,要避免出现死循环

例2:while循环

counter = 1
while counter <= 10:
    counter += 1
    print(counter)
#输出:1 2 3 4 5 6 7 8 9 10 11-----在到10的时候,还会运行一次,输出11

while还可以跟else语句

counter = 1
while counter <= 10:
    counter += 1
    print(counter)
else:
    print('end')
#输出:1 2 3 4 5 6 7 8 9 10 11 end

在递归的时候用while是十分合适的,其他的情况用for更多

例3:for循环
主要用于遍历序列或者集合、字典

a = [1,2,3,4,5,6,7,8,9]
for i in a:
    print(i)
#输出:1 2 3 4 5 6 7 8 9

例4:要求遍历a里面的元素

a = [['a','b','c','d'],(1,2,3)]
for i in a:
    print(i)
输出:['a','b','c','d'] (1,2,3)

解决:

for i in a:
    for j in i:
        print(j)
#输出:a b c d 1 2 3

同样可以跟一个else语句

for i in a:
    for j in i:
        print(j)
else:
    print('end')
#输出:a b c d 1 2 3 end-----当列表里的内容都遍历完,就会输出end

例5:break打破循环

a = [1,2,3]
for i in a:
    if i == 2:
        break
    print(i)
else:
    print('end')
#输出:1
#当遍历到2的时候,直接就会进入break,不会再有下面的print,和else

例6:continue跳出本次循环

a = [1,2,3]
for i in a:
    if i == 2:
        continue
print(i)
else:
    print('end')
#输出:1 3 end
#当遍历到2的时候,执行continue,直接进入下一次循环,不执行print,从3开始进入for循环,continue不会影响else

例7:思考,为什么break后面还是有内容被输出出来了

a = [['a','b','c','d'],(1,2,3)]
for i in a:
    for x in i:
        if x == 'c':
            break
        print(x)
else:
    print('end')
输出:a b 1 2 3 end

解答:break打破的是内部的循环,外部的循环还在继续

例8:嵌套循环

a = [1,2,3]
b = [4,5,6]
for i in a:
    for j in b:
        print(i,j)
#输出:1 4 2 5 3 6

例9:让循环执行想要的次数,使用range函数

for i in range(0,10):
    print(i)
#输出:0 1 2 3 4 5 6 7 8 9
#range(0,10)表示从0开始,到10结束,但不包含10

而静态语言会这么写:

for (i=0;i<10;i++){
    print(i);
 }

例10:range函数的第三个参数,表示步长

for i in range(0,10,2):
    print(i)
#输出:0 2 4 6 8
#range(0,10,2)表示从0开始,到10结束,但不包含10,步长为2
#如果要让循环从10开始,到0结束,且步长为2,可以使用range(10,0,-2)

例11:实践range函数

a = [1,2,3,4,5,6,7,8]
for i in range(0,len(a),2):
    print(a[i])
#输出:1 3 5 7

其实还有更常用的方法,运用第2章里的切片运算,b = a[0:len(a):2],然后print(b)

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值