python中的循环

2018-05-01  本文已影响0人  又大又甜的桂圆

表达式(expression)是运算符(operator)和操作数(operand)所构成的序列

使用IDE(Intergrated Development Environment)

mood = 0

if mood:
    print("it's right")
else:
    print("it's wrong")
it's wrong

while循环

避免死循环的办法

适合在递归中使用

for循环

range中的参数分别是,起始位置,截止位置(英语被翻译为偏移量),步长

for x in range(10,0,-2):
    print(x)
10
8
6
4
2

if循环

mood = 0

if mood:
    print("it's right")
else:
    print("it's wrong")
it's wrong
'''
1. python中约定常量值要全部大写
2. python中没有switch,使用elif代替,更好的方式是使用字典代替,详见python官方文档
3. if、else必须成对出现
4. 默认终端输入的1是字符串,可以使用a=int(a)转化一下
'''
ACCOUNT = 'aa'
PASSWORD = '121'

print('please input account')
user_account = input()

print('please input',user_account,"'s password")
user_password = input()

if ACCOUNT == user_account and PASSWORD == user_password:
    print('success')
else:
    print('fail')
please input account
aa
please input aa 's password
121
success

while循环

counter = 1

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

for循环

a=[['milk','paper','banana'],(1,2,3)]

for x in a:
    for y in x:
        print(y,end='|')
else:
    print('上面的循环执行完后执行')
milk|paper|banana|1|2|3|上面的循环执行完后执行
'''
break是终止
continue是跳过继续执行
'''

a = [1,2,3]

for x in a:
    if x==2:
        continue
    print(x)
else:
    print('如果改成break这句就不会执行')
1
3
如果改成break这句就不会执行

嵌套循环

'''
1. 这里y的break只是跳出了内部的循环
2. 如果什么都不打印,可以在x中加上break和判断语句
'''
a=[['milk','paper','banana'],(1,2,3)]

for x in a:
    for y in x:
        if y=='paper':
            break
        print(y,end='|')
else:
    print('上面的循环执行完后执行')

milk|1|2|3|上面的循环执行完后执行

谢谢观看

上一篇 下一篇

猜你喜欢

热点阅读