python 学习札记(4)

1. if 语句

1) if语句

if expresion:

if_suite

expresion 非0 或者为布尔值true时执行子代码块if_suite(是缩进相同的一条或者多条语句,不需要大括号)

2)if else语句

if expresion :

if_suite

else:

else_suite

3)elif 语句

if expresion1:

if_suite

elif expresion2:

elif_suite

else:

else_suite

2.while语句

while expresion :

while_suite

while_suite会被循环执行,直到expresion 为0 或者为布尔值false

count = 0
a=raw_input("输入a的值:")
while count < 3 :
    if int(a) > 0:
        print "%d >0 "%(int(a))
    elif int(a) == 0:
        print "%d == 0 "%(int(a))
    else:
        print "%d < 0 "%(int(a))
    count +=1
    a=raw_input("输入a的值:")
输入a的值:0
0 == 0 
输入a的值:1
1 >0 
输入a的值:-1
-1 < 0 
3.for循环

1) python中的for循环与传统的for循环(计数器循环)不同,更像shell中的foreach迭代,可以把序列和迭代器作为参数,每次迭代一个对象

alist = ['name','felix','age',25]
for item in alist:
    print item
for item in alist:
    print item,
print
raw_input("pause!")
print会默认给没一行添加换行符,在后面添加逗号(,)会改变这种行为,没任何参数的print输出一个换行符

name
felix
age
25
name felix age 25
pause!
2)内建range()函数,根据提供的范围生成递增计数的列表

for eachnum in range(10):
    print eachnum
0
1
2
3
4
5
6
7
8
9
3)迭代字符串,range()和len()常用于字符串索引,但只能要么循环索引,要么循环元素,enumerate()同时能做到

#迭代字符串
for c in 'abcdef':
    print c  
a
b
c
d
e
f
name = 'felix'
for i in range(len(name)):
    print i,name[i]  
0 f
1 e
2 l
3 i
4 x
day = 'monday'
for i,ch in enumerate(day):
    print i,ch
0 m
1 o
2 n
3 d
4 a
5 y
4.列表解析

使用for循环在一行中把所有值放到一个列表中

square = [x**2 for x in range(4)]
print square
[0, 1, 4, 9]
使用for循环把符合条件的元素放入列表

specialsquare = [x**2 for x in range(8) if not x%2 ]
print specialsquare
[0, 4, 16, 36]


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值