python中的循环

时间:2021-04-25 20:17:53

>>> x = 100
>>> y = 10
>>> x < y and x or y
10
>>> x if x > y else y
100

if 语句:

>>> x = 10
>>> if x == 10:
... print(x)
...
10

>>> if x == 10:
... print(x)
... else:
... print("x not 10!")
...
10

>>> if x == 10:
... print(x)
... elif x == 100:
... print(x)
... else:
... print(x)
...
10

while循环:

super@super:/python$ cat w.py
#!/usr/bin/env python

list1=[1,2,3,4,5,6,7,8,9,10]
sum = 0
while list1:
    sum += list1[0]
    list1 = list1[1:]
print(sum)

super@super:/python$ python w.py
55

for循环:

super@super:/python$ cat f.py 
#!/usr/bin/env python

list1 = [1,3,5,6,9]
for i in list1:
    print(i)

super@super:/python$ python f.py
1
3
5
6
9

else语句:

super@super:/python$ cat f.py
#!/usr/bin/env python

list1 = [1,3,5,6,9]
for i in list1:
    print(i)
else:
    print("while is normal over!")

super@super:/python$ python f.py
1
3
5
6
9
while is normal over!

break语句:

super@super:/python$ cat f.py
#!/usr/bin/env python

list1 = [1,3,5,6,9]
for i in list1:
    print(i)
    break
else:
    print("while is normal over!")
super@super:/python$ python f.py
1

continue语句:

super@super:/python$ cat f.py
#!/usr/bin/env python

list1 = [1,3,5,6,9]
for i in list1:
    if i == 5:
        continue
    print(i)
else:
print("while is normal over!")
super@super:/python$ python f.py
1
3
6
9
while is normal over!