wzh789 发表于 2018-8-14 13:56:14

python学习笔记七:条件&循环语句

  1、print/import更多信息
  print打印多个表达式,使用逗号隔开
  >>>print 'Age:',42
  Age: 42   #注意个结果之间有一个空格符
  import:从模块导入函数
  import 模块
  from 模块 import 函数
  from 模块 import *
  如果两个模块都有open函数的时候,
  1)使用下面方法使用:
module1.open()...
module2.open()...
  2)语句末尾增加as子句
  >>>import math as foobar
  >>>foobar.sqrt(4)
  2.0
  2、赋值
  1)序列解包:多个赋值同时进行,适用于当函数或者方法返回元组(或者其他序列或可迭代对象)时
  >>>x, y, z = 1, 2, 3
  >>>print x, y, z
  12 3
  典型应用场景:
  >>>scoundrel = {'name': 'Robin', 'girlfriend':'Marion'}
  >>>key, value = scoundrel.popitem()
  >>>print key, value
  girlfriendMarion
  2)链式赋值:将同一个值赋给多个变量
  x = y = somefunction() 类似于
y =somafunction()
x = y
  3)增量赋值:x+=1,对于*,/,%等标准运算符都适用
  3、语句块缩排
  推荐的方式:使用空格,缩进需要4个空格
  4、条件和条件语句
  1)布尔真值:在python中None、{}、""、[]、()都被视为假
  2)if/else语句:
  name= raw_input('What is your name?')
  ifname.endswith('Alex'):
  print 'Hello, Mr. Alex'
  else:
  print 'Hello, stranger'
  3)elif语句:也就是else if的简写
  name= input('Enter a number: ')
  ifnum > 0:
  print 'The number is positive'
  elifnum < 0:
  print 'The number is negative'
  else:
  print 'The number is zero'
  5、条件相关
  == :相等运算符,两个等号
  is:同一性运算符,是同一个对象
  >>>x = y =
  >>>z =
  >>>z == y
  True
  >>>x == z
  True
  >>>x is y
  True
  >>>x is z
  False
  如上例,x和z相等但却不是同一个对象
  总结:使用==运算符来判定两个对象是否相等,使用is使用来判定两者是否等同
  in:成员资格运算符
  布尔运算符:add ornot
  断言:确保程序中的某个条件一定为真才能让程序正常执行
  >>>age = -1
  >>>assert 0<age<100, 'The age must be realistic'
  Traceback(most recent call last):
  File "<stdin>", line 1, in<module>
  AssertionError:The age must be realisti
  循环:
  1)while循环:
x = 1
while x <= 100
print x
x +=1
  两个字符串方法:isspace() 检查字符串是否只有空格组成
  strip() 去掉字符串两边空格
  2)for循环:
numbers =
for number in numbers:
print number
  两个函数:range函数 一次创建整个序列
  xrange一次只创建一个数
  3)循环遍历字典元素
d = ['x':1, 'y':2, 'z':3]
for key, value in d.items():
print key, 'corresponds to', value
  4)迭代工具
  a. 并行迭代,使用内建zip函数,把两个序列“压缩”在一起,然后返回一个元组的列表
  >>>names = ['anne', 'beth', 'george', 'damon']
  >>>ages =
  >>>zip(names, ages)
  [('anne',12), ('beth', 45), ('george', 32), ('damon', 102)]
  >>>for name, age in zip(names, ages): print name, 'is', age, 'years old'
  ...
  anneis 12 years old
  bethis 45 years old
  georgeis 32 years old
  damonis 102 years old
  b. 按索引迭代,使用内建enumerate函数
  names= ['anne', 'beth', 'george', 'damon']
  forindex, name in enumerate(names):
  if'anne' in name:
  names = 'alex'
  5)跳出循环:
  break:结束循环
  continue:结束当前的循环,“跳”到下一轮循环
whileTrue/break
  6)循环中的else子句:
  frommath import sqrt
  forn in range(99, 81, -1):
  root = sqrt(n)
  if root == int(root):
  print n
  break
  else:
  print "Didn't find it!"
  6、轻量级循环-列表推导式:用其他列表创建新列表
  >>>
  
  >>>
  
页: [1]
查看完整版本: python学习笔记七:条件&循环语句