python 条件,循环和其他语句

条件,循环和其他语句

print 输出多个用 逗号隔开
>>> print 'hello','world',' !'
hello world  !

--------------------------------------------

为函数提供别名
>>> import math as qiao
>>> qiao.sqrt(9)
3.0
>>> from math import sqrt as chao
>>> chao(16)
4.0

--------------------------------------------

多个赋值操作同时进行
>>> x,y,z=1,2,3
>>> x
1
>>> print x,y,z
1 2 3
>>> a,b,rest=[1,2,3]
>>> rest
3
>>> x,y,z=1,2
Traceback (most recent call last):
  File "<pyshell#98>", line 1, in <module>
    x,y,z=1,2
ValueError: need more than 2 values to unpack
注意:赋值个数与变量个数一致,否则报错

python 3.0 特性:
>>> a,b,rest*=[1,2,3,4]
rest结果[3,4]

交互2个或者更多变量的值
>>> x
1
>>> y
2
>>> x,y=y,x
>>> print x,y
2 1

元组赋值
>>> values=1,2,3
>>> values
(1, 2, 3)
>>> a,b,c=values
>>> a
1
>>> b
2
>>> c
3

获取和删除字典中任意的键值对的时候,popitem方法以元组返回
>>> persons={'name':'john','age':42,'sex':'male'}
>>> key,value=persons.popitem()
>>> key
'age'
>>> value
42
>>> persons
{'name': 'john', 'sex': 'male'}

链式赋值
x=y=somefunction()
和下面的语句效果一样
x=y
y=somefunction()
注意:和下面的语句不一定等价
x=somefunction()
y=somefunction()


增量赋值
>>> x=2
>>> x+=1
>>> x
3
>>> x*=2
>>> x
6

同样适合其他类型
>>> ff='foo'
>>> ff+='ds'
>>> ff
'foods'
>>> ff*=2
>>> ff
'foodsfoods'

-----------------------------------------------------

False None   0  ""  ()  []  {}  对于布尔类型都是假
标准值False  None,所有数字0(包括浮点型,长整形其他类型),空序列(空串,空元组和列表)和空字典都是假
>>> True
True
>>> False
False
>>> True == 1
True
>>> False == 1
False
>>> True + False + 2
3

bool 函数可以转换其他值
>>> bool('I tasd asd')
True
>>> bool(3)
True
>>> bool('')
False
>>> bool(0)
False
>>> bool([])==bool('')==False
True
>>> bool()
False

-----------------------------------------------------

if 条件
>>> name = raw_input('name:')
name:qiaochao
>>> if name.endswith('ao'):
 print 'hello qiaochao'
 
hello qiaochao

-------------------------------------------------------

esle 语句
name = raw_input('please input your name : ')
if name.endswith('chao'):
 print 'hello qiaochao'
else:
 print 'hello stranger'

D:\>python test.py
please input your name : qiaochao
hello qiaochao

D:\>python test.py
please input your name : laojia
hello stranger

elif 子句
num = input('please input a number : ')
if num > 0 :
 print 'number is positive'
elif num < 0 :
 print 'number is negative'
elif num == 0 :
 print 'number is 0'

D:\>python test.py
please input a number : 8
number is positive

D:\>python test.py
please input a number : -9
number is negative

D:\>python test.py
please input a number : 0
number is 0

------------------------python 中的比较运算符------------------------------

x==y    ----------------   x等于y
x<y    --------------- x小于y
x>y    ----------------- x 大于y
x>=y   --------------  x大于等于y
x!=y  ---------------  x 不等于y
x is y  -------------   x 和y 是同一个对象
x is not y  -----------  x和y是不同的对象
x in y   -------------  x 是y容器(例如序列)中的成员
x not in y  --------- x不是y容器(例如序列)中的成员

注意: 在python 中几个运算符是可以一起用的
例如:
>>> 0<1<100
True

-----------------------------------------------------------------------------

>>> x=[1,2,3]
>>> y=[2,4]
>>> x is not y
True
>>> del x[2]
>>> y[1]=1
>>> y.reverse()
>>> y
[1, 2]
>>> x
[1, 2]
>>> x == y
True
>>> x is y
False
注意:x 和 y 是2个序列 ,== 运算符来判断两个对象是否相等,is判定两者是否等同(同一个对象)

-----------------------------------------------------------------------------------

字符串的比较
字符串可以按照字母顺序进行比较
>>> "abc" > "aaa"
True
>>> "Abc" > "abc"  ---- 注意大小写
False

序列的比较类似
>>> [1,2] < [2,1]
True
>>> [2,[1,3]] < [2,[1,4]]
True

--------------------------------------------------------------------------------------

if 条件判断中的 and 和 or
num = input('please input a number (between 0-10) : ')
if num <= 10 and num >= 0:
 print 'rigth'
else:
 print 'wrong'

D:\>python test.py
please input a number (between 0-10) : 9
rigth

D:\>python test.py
please input a number (between 0-10) : 99
wrong

---------------------------------------------------------------------------------------

断言

>>> assert 0<age<100
>>> age = -1
>>> assert 0<age<100

Traceback (most recent call last):
  File "<pyshell#174>", line 1, in <module>
    assert 0<age<100
AssertionError

确保程序中的某个条件必须为真才执行,assert 就有用了

----------------------------------------------------------------------------------------

while循环

x=1
while x<=100:
 print x
 x+=1

name = ''
while not name:
 name = raw_input('input your name : ')
print 'your name is ' + name

D:\>python test.py
input your name :
input your name :
input your name : qiaochao
your name is qiaochao

----------------------------------------------------------------------------------

for循环

range函数:
>>> range(0,10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(99,81,-1)    ------------------ 第三个参数为步长
[99, 98, 97, 96, 95, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82]
>>> range(99,81,-2)
[99, 97, 95, 93, 91, 89, 87, 85, 83]

for num in range(0,100):
 print num

break 和 continue 继续适用
------------------------------------------------------------------------------------

zip 函数
用来进行并行迭代,可以把2个序列“压缩”在一起,然后返回一个元组列表
>>> names=['qiao','chao','ca','ss']
>>> ages=[25,26,22,21]
>>> zip(names,ages)
[('qiao', 25), ('chao', 26), ('ca', 22), ('ss', 21)]

names=['qiao','chao','ca','ss']
ages=[25,26,22,21]
zip(names,ages)
for name,age in zip(names,ages):
 print name,' is ',age,' years old'

D:\>python test.py
qiao  is  25  years old
chao  is  26  years old
ca  is  22  years old
ss  is  21  years old

注意:zip函数可以用于任意多的序列,很重要的一点zip可以应付不等长的序列,当最短的序列"用完"的时候就会停止
如:
>>> zip(range(5),range(7))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>> zip(range(5),xrange(1000000))   ------------- 不推荐range 替换xrange ,range会计算所有的数字,花费很长时间,xrange只计算前5个
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]

---------------------------------------------------------------------------------------

列表推导式
>>> [x*x for x in range(5)]
[0, 1, 4, 9, 16]

可以在 循环中做条件筛选
>>> [x*x for x in range(10) if x%3 == 0]
[0, 9, 36, 81]
>>> girls=['alice','ben','clinda']
>>> boys=['chia','mm','ada']
>>> [b+'+'+g for b in girls for g in boys if b[0]==g[0]]
['alice+ada', 'clinda+chia']

------------------------------------------------------------------------------------------

1. pass
程序什么事情也不做
注意:python中空代码块是非法的
num = input('please input a number : ')
if num > 0 :
 print 'number is positive'
elif num < 0 :
 #还没完
 pass
elif num == 0 :
 print 'number is 0'

2. del 删除
>>> x=1
>>> x
1
>>> del x
>>> x
Traceback (most recent call last):
  File "<pyshell#214>", line 1, in <module>
    x
NameError: name 'x' is not defined

>>> x=['hellp','jjas']
>>> y=x
>>> y[1]='qiao'
>>> y
['hellp', 'qiao']
>>> x
['hellp', 'qiao']
>>> del x
>>> y
['hellp', 'qiao']
注意:x和y都指向同一个列表,但是删除x 不会影响y,原因就是删除的只是名称,而不是列表本身。
python解释器会负责内存的回收

3. exec
执行一个字符串的语句是exec
>>> exec 'print "hell workd"'
hell workd

4. eval
计算python表达式(以字符串的形式书写),并且返回结果值。
>>> eval(raw_input('enter numvers :'))
enter numvers :
1+2+3*4
15

------------------------------------------------------------------------

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值