python之判断和循环

计算机之所以能做很多自动化的任务,因为它可以自己做条件判断。
比如,输入用户年龄,根据年龄打印不同的内容,在Python程序中,可以用if语句实现:

age = 20
if age >= 18:
    print ('your age is,'+str(age))
    print ('adult')
print ('END')

注意: Python代码的缩进规则。具有相同缩进的代码被视为代码块,上面的3,4行 print 语句就构成一个代码块(但不包括第5行的print)。如果 if 语句判断为 True,就会执行这个代码块。
缩进请严格按照Python的习惯写法:4个空格,不要使用Tab,更不要混合Tab和空格,否则很容易造成因为缩进引起的语法错误。
注意: if 语句后接表达式,然后用:表示代码块开始。

ages=input('please input you age: ')
age=int(ages)
if age >= 18:
    print('adult')
elif age >= 6:
    print('teenager')
elif age >= 3:
    print('kid')
else:
    print('baby')

list或tuple可以表示一个有序集合。如果我们想依次访问一个list中的每一个元素呢?

Python的 for 循环就可以依次把list或tuple的每个元素迭代出来:

L = ['Adam', 'Lisa', 'Bart']
for name in L:
    print(name)
结果:
[python@master if]$ python3 3.py 
Adam
Lisa
Bart

在 python 中,for … else 表示这样的意思,for 中的语句和普通的没有区别,else 中的语句会在循环正常执行完(即 for 不是通过 break 跳出而中断的)的情况下执行,while … else 也是一样。

Python 编程中 while 语句用于循环执行程序,即在某条件下,循环执行某段程序,以处理需要重复处理的相同任务。其基本形式为:

  while 判断条件:

      执行语句……

执行语句可以是单个语句或语句块。判断条件可以是任何表达式,任何非零、或非空(null)的值均为true。当判断条件假false时,循环结束。

count = 0
sum=0
while(count < 9):
   print('The count is:' + str(count))
   sum=sum+count
   count = count + 1
print('sum is :'+ str(sum)) 
print('Good bye!')
结果:
[python@master if]$ python3 4.py 
The count is:0
The count is:1
The count is:2
The count is:3
The count is:4
The count is:5
The count is:6
The count is:7
The count is:8
sum is :36
Good bye!

python之break语句退出循环。

sum = 0
x = 1
while True:
    sum = sum + x
    x = x + 1
    if x > 100:
        break
print(sum)
结果:
[python@master if]$ python3 5.py 
5050

在循环过程中,可以用break退出当前循环,还可以用continue跳过后续循环代码,继续下一次循环。

L = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
    sum = sum + x
    n = n + 1
print(sum/n)
结果:
[python@master if]$ python3 6.py 
72.0

现在老师只想统计及格分数的平均分,就要把 x < 60 的分数剔除掉,这时,利用 continue,可以做到当 x < 60的时候,不继续执行循环体的后续代码,直接进入下一次循环:

L = [75, 98, 59, 81, 66, 43, 69, 85]
sum = 0.0
n = 0
for x in L:
     if x < 60:
        continue
     sum = sum + x
     n = n + 1
print(sum/n)
结果:
[python@master if]$ python3 7.py 
79.0

python 还有多重循环

for x in ['A', 'B', 'C']:
    for y in ['1', '2', '3']:
        print (x + y)
结果:
x 每循环一次,y 就会循环 3 次,这样,我们可以打印出一个全排列: [python@master
if]$ python3 8.py A1 A2 A3 B1 B2 B3 C1 C2 C3
原文地址:https://www.cnblogs.com/hello-wei/p/9542815.html