python基础知识整理——条件/循环语句

1.条件语句

基本语句

Python程序语言指定任何非0和非空(null)值为true,0 或者 null为false。

Python 编程中 if 语句用于控制程序的执行,基本形式为:

if 条件判断:
    执行语句
else:
    执行语句

其中"判断条件"成立时(非零),则执行后面的语句,而执行内容可以多行,以缩进来区分表示同一范围。

多条件判断语句

由于 python 并不支持 switch 语句,所以多个条件判断,只能用 elif 来实现,如果判断需要多个条件需同时判断时,可以使用 or (或),表示两个条件有一个成立时判断条件成功;使用 and (与)时,表示只有两个条件同时成立的情况下,判断条件才成功;else 为可选语句,当需要在条件不成立时执行内容则可以执行相关语句,当判断条件为多个值时,可以使用以下形式。

if 条件语句:
    执行语句
elif 条件语句:
    执行语句
elif 条件语句:
    执行语句
...
else:
    执行语句

      当if有多个条件时可使用括号来区分判断的先后顺序,括号中的判断优先执行,此外 and 和 or 的优先级低于>(大于)、<(小于)等判断符号,即大于和小于在没有括号的情况下会比与或要优先判断。

#!/user/bin/python
# -*- coding: cp936 -*-
h=1.75
w=80.5
a=80.5/(1.75*1.75)
if a<18.5:
    print"过轻"
elif 18.5<a and a<25:
    print "正常"
elif 25<a and a<28:
    print "过重"
elif 28<a and a<32:
    print "肥胖"
else:
    print "严重肥胖"

#输出结果
>>> 
过重
    

简单语句组

    
v=100
if (v==10):print "变量v的值为:",v
print "cood bye"

python 复合布尔表达式计算采用短路规则,即如果通过前面的部分已经计算出整个表达式的值,则后面的部分不再计算。

a,b=0,1
if (a>0) and (b/a>2):
    print "youo got it"
else:
    print "game over"

a,b=0,1
if (a>0) or (b/a>2):
    print "you got it"
else:
    print "game over"
#一个简单的条件循环语句实现汉诺塔问题
def my_print(args):
    print args
def move(n,a,b,c):
    my_print((a,'--->',c)) if n== 1 else (move(n-1,a,c,b) or move(1,a,b,c) or move(n-1,b,a,c))
    move (3,'a','b','c')

2.循环语句

(1)While 循环语句

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

while 判断条件:
    执行语句……

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

执行流程图如下:

python_while_loop

Python while 语句执行过程

#!/user/bin/python
# -*- coding: cp936 -*-
list=[12,37,5,42,8,3]
n1=[]
n2=[]
n=0
while n<len(list):
    if (list[n]%2==0):
        n1.append(list[n])
    else:
        n2.append(list[n])
    n=n+1
print "n1列表内容:%s;n2列表内容:%s"%(n1,n2)

#输出结果

>>> 
n1列表内容:[12, 42, 8];n2列表内容:[37, 5, 3]
    

break、continue的用法

break的作用是当符合一定的条件时,终止循环;continue的作用是,当满足一定条件,满足条件的这一项停止运行。

#打印偶数
i=1
while i<10:
    i+=1
    if i%2>0:
        continue
    print i
#打印出从1到10
i=1
while 1:
    print i
    i+=1
    if i>10:
        break

#输出结果

>>> 
2
4
6
8
10
1
2
3
4
5
6
7
8
9
10

循环使用 else 语句

count=0
while count<5:
    print count,"is less than 5"
    count=count+1
else:
    print count,"is not less than 5"

#输出的结果
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
>>> 

简单语句组

i=input("please input number:")
while i<0:print "game over"
print i

#输出结果

>>> 
please input number:12
12

猜大小的游戏

#!/usr/bin/python
# -*- coding: UTF-8 -*-

import random
s = int(random.uniform(1,10))
#print(s)
m = int(input('输入整数:'))
while m != s:
    if m > s:
        print('大了')
        m = int(input('输入整数:'))
    if m < s:
        print('小了')
        m = int(input('输入整数:'))
    if m == s:
        print('OK')
        break;

猜拳小游戏

import random
while 1:
    s=int(random.randint(1,3))
    if s==1:
        ind='石头'
    elif s==2:
        ind='剪子'
    elif s==3:
        ind='布'
    m=raw_input('输入 石头、剪子、布,输入"end"结束游戏:')
    blist=['石头','剪子','布']
    if (m not in blist) and (m=='end'):
        print "输入错误,请从新输入!"
    elif m==ind:
        print "电脑出了:"+ind+",平局!"
    elif (m=='石头' and ind=='剪刀') or (m=='剪刀' and ind=='布') or (m=='布' and ind=='石头'):
        print "你赢了"
    elif (m=='石头' and ind=='布') or (m=='布' and ind=='剪刀') or (m=='剪刀' and ind=='石头'):
        print '机器赢了'
 
    elif m=='end':
        break

十进制转二进制

denum=input("输入十进制数:")
print denum,"(10)",
binnum=[]
#二进制数
while denum >0:
    binnum.append(str(denum%2))
    denum //= 2
print '='
while len(binnum)>0:
    import sys
    sys.stdout.write(binnum.pop())

(2)for 循环语句

Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

语法:

for循环的语法格式如下:

for iterating_var in sequence:
   statements(s)

通过序列索引迭代

fruits=['banana','apple','mango']
for index in range(len(fruits)):
    print '当前水果:',fruits[index]
print "game over"
for i,j in enumerate(fruits):
    print i,j

else 语句

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

for num in range(10,20):
    for i in range(2,num):
        if num%i==0:
            j=num
            print '%d 等于%d*%d'%(num,i,j)
            break
    else:
        print num,'是一个质数'

冒泡排序

arays=[1,8,2,6,3,9,4]
for i in range(len(arays)):
    print len(arays)
    for j in range(i):
        if arays[i] <arays[j]:
            arays[i],arays[j]=arays[j],arays[i]
print arays

#输出结果

>>> 
7
7
7
7
7
7
7
[1, 2, 3, 4, 6, 8, 9]

(3)循环嵌套

Python for 循环嵌套语法:

for iterating_var in sequence:
   for iterating_var in sequence:
      statements(s)
   statements(s)

Python while 循环嵌套语法:

while expression:
   while expression:
      statement(s)
   statement(s)

100以内的质数:

num=[]
i=2
for i in range(2,100):
    j=2
    for j in range(2,i):
        if (i%j==0):
            break
        else:
            num.append(i)
print num

猜你喜欢

转载自my.oschina.net/u/3754854/blog/1624069