【Python基础4】for循环、while循环与if分支

1 if 分支

Python代码块是通过缩进来创建的,对缩进格式有严格的要求,需要注意space空格键和tab键创建的缩进是不一样的,注意不要出现空格和tab混用的情况。
if分支语句里面一般还可以包含elif、else语句,如下是代码块嵌套的实例

name=input('what is your name:')
if name.endswith('Sudley'):
    if name.startswith('Mr. '):
        print('Hello, Mr. Sudley')
    elif name.startswith('Mrs. '):
        print('Hello, Mrs. Sudley')
    else:
        print('Hello, Sudley')
else:
    print('Hello, stranger')

if else语句的另外一种写法

age=input('How old are you:')
#交换模式
if int(age) < 18:
    print("hey, little boy")
else:
    print('Hi, man')

a = 8
if a < 5:
    score='A'
elif a < 8:
    score='A+'
else:
    score='S'
print(score)

等价于

age=input('How old are you:')
#条件表达式
print("hey, little boy") if int(age) < 18 else print('Hi, man')

a = 8
score = ('A' if a < 5 else
         'A+' if a < 8 else
         'S' )
print(score)

在if后的条件表达式中,最基本的运算符可能是比较运算符

表达式描述
x == yx等于y
x < yx小于y
x <= yx小于等于y
x > yx大于y
x >= yx大于等于y
x != yx不等于y
x is yx和y是同一个对象
x is not yx和y是不同的对象
x in yx是容器(如序列)y的成员
x not in yx是容器(如序列)y的成员

关于容器数据类型的介绍参考
python-容器数据类型-知识小结

2 while循环

打印1~100

x = 1
while x < 101:
    print(x)
    x += 1

3 for循环

打印1~100

for x in range(1,101):
    print(x)

相比使用while循环,这里for循环的代码要紧凑得多。
原则上只要能使用for循环,就不要使用while循环

d = {'x':1,'y':2}
for key in d:
    print(key,'corresponds to',d[key])

#d.items()以元组方式返回键-值对,for循环的优点之一是,可以在其中使用序列解包。
for key,value in d.items():
    print(key,'corresponds to',d[key])

4 跳出循环

break:结束循环
continue:结束当前迭代,并跳到下一次迭代

>>> for x in range(1,5):
    if x == 3:
        break
    print(x)

    
1
2
>>> for x in range(1,5):
    if x == 3:
        continue
    print(x)

    
1
2
4
>>>

5 while True/break

word = 'qq'
while word:
    word = input('pls enter a word:')
    print(word)

上述代码中word = 'qq’称为哑值(未用的值),这样的哑值一般昭示着做法不太对,不会使用的值自然不应该定义。这里可以换成下面的形式,注意True首字母需要大写

while True:
    word = input('pls enter a word:')
    if not word:break
    print(word)

6 循环中的else字句

循环中else子句在循环没有break的时候调用

>>> for x in range(5,1,-1):
    if x == 3:
        break
    print(x)
else:
    print('loop is not break')

    
5
4
>>> for x in range(5,1,-1):
    if x == 3:
        continue
    print(x)
else:
    print('loop is not break')

    
5
4
2
loop is not break
>>> for x in range(5,1,-1):
    print(x)
else:
    print('loop is not break')

    
5
4
3
2
loop is not break
>>> 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值