您的位置:首页 > 编程语言 > Python开发

Python -- if while for 语句

2016-05-24 21:04 543 查看
小Q:谁念西风独自凉,萧萧黄叶闭疏窗,沉思往事立残阳。
被酒莫惊春水重,赌书消得泼茶香,当时只道是寻常。 ---- 纳兰容若《浣溪沙》
----------------------------------------------------------------------------------------------------
每个关键词后都用冒号( :)分割
模块以缩进空格定义,一般空四格

注:python中没有do...while和switch语句;但是有for....else和while.....else语句。

if 判断条件1:
执行语句1……
elif 判断条件2:
执行语句2……
else:
执行语句3……
#!/usr/bin/python
# -*- coding:UFT-8 -*-
#有外界交互的成绩评定器

source = int (raw_input("please input a num: "))  #raw_input输入的是字符串,需要转化才能if
if source >= 90:
print 'A'
print 'very good'
elif source >= 70:
print 'B'
print 'good'
else:
print 'C'
print 'It's bad'
print "ending"
while 判断条件:
执行语句……
#!/usr/bin/python

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
注:while..else和for...else相同,会在循环正常执行完的情况下执行(并非遇到break等跳出中断)
Python for循环可以遍历任何序列的项目,如一个列表或者一个字符串。

for iterating_var in sequence:
statements(s)
#!/usr/bin/python
# -*- coding: UTF-8 -*-

fruits = ['banana', 'apple',  'mango']
for index in range(len(fruits)):
print '当前水果 :', fruits[index]
print "Good bye!"

>>>>>>>>
当前水果 : banana
当前水果 : apple
当前水果 : mango
Good bye!
随机函数:
range(5) >>> 0,1,2,3,4
range(1,6) >>> 1,2,3,4,5
range(1,10,2) >>> 1,3,5,7,9
xrange(5) >>> 0,1,2,3,4
xrange(1,6) >>> 1,2,3,4,5
xrange不占内存,当用到时才会调用到,测试:
a = xrange(5); print a
举例:嵌套循环输出2-30之间的素数?

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

i = 2
for i < 30:
j = 2
while (j <=(i/j)):        #无优先级时,括号可有可无
if not (i%j):break   #i 除以 j 没有余数,则中断
j = j + 1
if j > i/j :
print 1,' 是素数'
i= i+ 1
print "good bye"

>>>>>>>>>
2 是素数
3 是素数
5 是素数
7 是素数
11 是素数
13 是素数
17 是素数
19 是素数
23 是素数
29 是素数
举例:打印9*9乘法表?

#!/usr/bin/python

for i in xrange(1,10):
for j in xrange(1,i+1):
print "%s*%s=%s" % (j,i,j*i),
print             #打印换行符

>>>>>>>>>
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
----------------------------------------------------------------------------------------------------





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

for letter in 'Python':     # 第一个实例break
if letter == 'h':
break
print 'Current Letter :', letter

var = 7             # 第二个实例continue
while var > 0:
var = var -1
if var == 5:
continue
print '当前变量值 :', var

for letter in 'abcd':          #第三个实例pass
if letter == 'b':
pass
print '这是 pass 块'
print '当前字母 :', letter
print "Good bye!"

>>>>>>>>>
Current Letter : P
Current Letter : y
Current Letter : t
当前变量值 : 6
当前变量值 : 4
当前变量值 : 3
当前变量值 : 2
当前变量值 : 1
当前变量值 : 0
当前字母 : a
这是 pass 块
当前字母 : b
当前字母 : c
当前字母 : d
Good bye!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python if while