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

python基础8(表达式和语句)

时间:2014-12-03 00:16:10      阅读:218      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   os   sp   for   strong   

一、print 和 import 信息

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

二、赋值

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

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

2、链式赋值

>>> x = y = somefunction

3、增量赋值

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

>>> x = 2
>>> x +=1
>>> x *=2
>>> x
6

 

三、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 循环

 

python基础8(表达式和语句)

标签:style   blog   io   ar   color   os   sp   for   strong   

原文地址:http://www.cnblogs.com/wakey/p/4138819.html

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