码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记之条件、循环和其他语句

时间:2016-05-26 18:28:58      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

一、函数导入

1、为模块提供别名

>>> import math as foobar #设置math 别名为foobar

>>> foobar.sqrt(4)

显示:2.0

2、为函数提供别名

>>> from math import sqrt as foobar

>>> foobar(4)

显示:2.0

 

二、赋值

1、多值赋值

>>> x,y,z=1,2,3

>>> print(x,y,z)

显示:1,2,3

2、多值交换

>>> x,y=y,x

>>> print(x,y,z)

显示:2,1,3

3、增量赋值

>>> x=2

>>> x+=1

>>> x*=2

>>> x

显示:6

 

三、条件执行和if语句

1、if嵌套代码

>>> name=input(‘What is your name? ‘)

>>> if name.endswith(‘Gumby‘):

>>>  if name.startswith(‘Mr.‘):

>>>    print(‘Hello, Mr. Gumby‘)

>>>  elif name.startswith(‘Mrs.‘)

>>>    print(‘Hello, Mrs. Gumby‘)

>>>  else:

>>>    print(‘Hello, Gumby‘)

>>> else:

>>>  print(‘Hello,stranger‘)

2、is,同一性运算符,和==相似,但事实上不一样

>>> x=y=[1,2,3]

>>> z=[1,2,3]

>>> x==y

显示:True

>>> x==z

显示:True

>>> x is y

显示:True

>>> x is z

显示:False

3、in,成员资格运算符

>>> if ‘s‘ in name:

>>>  print(‘Your name contains the letter "s".‘)

>>> else:

>>>  print(‘Your name does not contain the letter "s".‘)

4、assert,断言

>>>age=-1

>>> assert 0<age<100, ‘The age must be realistic‘

显示:AssertionError:The age must be realistic

5、while循环

>>> x=1

>>> while x<= 100:

>>>  print(x)

>>>  x+=1

6、for循环

>>> numbers=[0,1,2,3,4,5,6,7]

>>> for number in numbers:

>>>  print(number)

 

Python学习笔记之条件、循环和其他语句

标签:

原文地址:http://www.cnblogs.com/xiaofoyuan/p/5531931.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!