python学习笔记8(表达式和语句)

来源:互联网 发布:黑马java视频解压密码 编辑:程序博客网 时间:2024/06/03 11:11
一、print import 信息

>>> print 'age:',22   # 用逗号隔开打印多个表达式age: 22
import somemodule             # 从模块导入函数>>> import math as foobar>>> foobar.sqrt(4)2.0from somemodule import *      # 从给定的模块导入所有功能

二、赋值

1、序列解包:将多个值的序列解开

>>> values = 1,2,3>>> values(1, 2, 3)>>> x,y,z=values>>> x1>>> x,y=y,x       # 交换两个变量>>> print x,y,z2 1 3

2、链式赋值

>>> x = y = somefunction

3、增量赋值

x +=1    对于 */% 等标准运算符都适用

>>> x = 2>>> x +=1>>> x *=2>>> x6

 

三、Python语句

if语句、else语句、elif语句、条件表达式、while语句、for语句、break语句、continue语句、pass语句、Iterators(迭代器)、列表解析

 1 name = raw_input('What is your name? ') 2 if name.endswith('Gumby'): 3     if name.startswith('Mr.'): 4         print 'Hello,Mr,Gumby' 5     elif name.startswith('Mrs.'): 6         print 'Hello,Mrs,Gumby' 7     else: 8         print 'Hello,Gumby' 9 else:10     print 'Hello,stranger'
number = input('Enter a number between 1 and 10: ')if number <=10 and number >=1:      #布尔运算符    print 'Great'else:    print 'Wrong'

 

断言:  与其让程序在晚些时候崩溃,不如在错误条件出现时直接让它崩溃。

if not condition:    crash program
>>> age = -1>>> assert 0 < age < 100,   'The age must be realistic'     # 条件后可以添加字符串,用来解释断言Traceback (most recent call last):  File "<pyshell#99>", line 1, in <module>    assert 0 < age < 100,   'The age must be realistic'AssertionError: The age must be realistic

 

循环:

1、while 循环       在任何条件为真的情况下重复执行一个代码块

>>> a,b=0,10>>> while a<b:    print a,   # 注意末尾的逗号,会使所有输出都出现在一行    a+=1    0 1 2 3 4 5 6 7 8 9

 

2、for 循环    当ptyhon运行for循环时,会逐个将序列对象中的元素赋值给目标,然后为每个元素执行循环主体。

numbers = [0,1,2,3,4,5,6,7,8,9]for number in numbers:    print number,       # 打印 0 1 2 3 4 5 6 7 8 9

 

跳出循环:

1、break       跳出最近所在的循环(跳出整个循环语句)            

如果你从forwhile循环中 终止 ,任何对应的循环else块将执行。

for i in range(10):    if i == 3:        break   # 停止执行整个循环    print i,    0 1 2

2、continue  结束当前的循环,跳到下一轮的循环开始

for i in range(10):    if i == 3:        continue   # 让当前的循环结束,跳到下一轮的循环开始    print i,    0 1 2 4 5 6 7 8 9

pass

pass:是一个很好的占位符,不做任何事情。

注意:编写代码时,最好先别结构定下来,如果不想让一些代码干扰,那么最好的方法就是使用pass

name=raw_input('please enter your name: ')if name == 'Ethon':    print 'welcome!'elif name == 'wakey':    pass             # 用pass做占位符elif name == 'joho':    print 'Access Denied'

 

for、while 与 else 的联合使用

其他语言中,else只能用于if条件句,但是Python不同其他语言,else还能与for、while一起使用。在循环后处理,并且如果遇到break,则也会跳过else的。

1 x=10             2 while x:         3     x=x-1        4     if x==5:5         break6     print x7 else:8     print "over"

 

0 0
原创粉丝点击