print和import的更多信息

使用逗号输出

>>> print 'age:', 42
age: 42

>>> 1,2,3
(1, 2, 3)
>>> print 1,2,3
1 2 3
>>> print (1,2,3)
(1, 2, 3)

>>> name='Gumby'
>>> salutation='Mr.'
>>> greeting='Hello,'

>>> print greeting, salutation, name
Hello, Mr. Gumby

print 'Hello,',
print 'world!'

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

Hello, world!

把某件事作为另一件事导入

从模块导入函数的时候可以用

import somemodule

or

from somemodule import somefunction

or

form somemodule import somefunction.anotherfunction.yetanotherfunction

or

form somemodule import *

两个模块拥有相同函数,可以使用别名

>>> import math as foobar#为模块提供别名
>>> foobar.sqrt(4)
2.0
>>> from math import sqrt as foobar #为函数提供别名
>>> foobar(4)
2.0
>>> from module1 import open as open1

>>> from module2 import open as open2

赋值魔法

序列解包

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

>>> values=1,2,3
>>> values
(1, 2, 3)
>>> x,y,z=values
>>> x
1
>>> scoundre={'name':'Robin','girlfriend':'Marion'}
>>> key,value=scoundre.popitem()
>>> key
'girlfriend'
>>> value
'Marion'
>>>

链式赋值

x=y=somefunction()

等同于

x=somefunction()

y=x

增量赋值

>>> x=2
>>> x+=1
>>> x*=2
>>> x
6
>>> fnord='foo'
>>> fnord+='bar'
>>> fnord*=2
>>> fnord
'foobarfoobar'
>>>

条件语句

False None 0  ""  ()  [] {}表示为假,其余都被解释为真

>>> True
True
>>> False
False
>>> True==1
True
>>> False==0
True
>>> True+False+42
43

>>> bool('i think ,therefore i am')
True
>>> bool(42)
True
>>> bool('')
False
>>> bool(0)
False

if语句

name=raw_input('What is your name?')
if name.endswith('Gumby'):
print 'Hello,Mr.Gumby'

else子句

name=raw_input('what is your name?')
if name.endswith('Gumby'):
print 'Hello,Mr.Gumby'
else:
print 'Hello,stranger'

elif子句

num=input('Enter a number: ')
if num>0:
print 'The number is positive'
elif num<0:
print 'The number is negative'
else:
print 'The number is zero'

嵌套代码块

name=raw_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'

断言

语句中使用关键字assert

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

Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
assert 0<age<100
AssertionError
>>> age=-1
>>> assert 0 <age<100,'The age must be realistic'

Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
assert 0 <age<100,'The age must be realistic'
AssertionError: The age must be realistic

循环

while循环

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

name=''
while not name:
name=raw_input('Please enter your name: ')
print 'Hello,%s!'%name

for

words=['this','is','an','ex','parrot']
for word in words:
print word

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

range(10)

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

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for number in range(1,101): #包含下限,不包含上限
print number

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

1

2

.

.

100

range与xrange

>>> a=range(0,100)
>>> print type(a)
<type 'list'>
>>> print a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
>>> print a[0],a[1]
0 1
>>> a=xrange(0,100)
>>> print type(a)
<type 'xrange'>
>>> print a
xrange(100)
>>> print a[0],a[1]
0 1
>>>

遍历字典

d={'x':1,'y':2,'z':3}
for key in d:
print key,'corresponds to',d[key]

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

>>>
y corresponds to 2
x corresponds to 1
z corresponds to 3

d={'x':1,'y':2,'z':3}
for key,value in d.items():
print key,'corresponds to',value

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

y corresponds to 2
x corresponds to 1
z corresponds to 3

一些迭代工具

并行迭代

names=['anne','beth','george','damon']
ages=[12,45,32,102]
for i in range(len(names)):
print names[i],'is',ages[i],'years old'

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

>>>
anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old
>>>

zip函数用来并行迭代

>>> names=['anne','beth','george','damon']
>>> ages=[12,45,32,102]
>>> zip(names,ages)
[('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)]

>>> for name,age in zip(names,ages):
print name,'is',age,'years old'

anne is 12 years old
beth is 45 years old
george is 32 years old
damon is 102 years old
>>> zip(range(5),xrange(10000000))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
>>>

编号迭代

>>> index=0
>>> for string in strings:
if 'xxx'in string:
strings[index]=['censored']
index+=1

使用内建函数enumerate

>>> for index,string in enumerate(strings):
if 'xxx'in string:
strings[index]=['censored']

翻转和排序迭代

>>> sorted([4,3,5,8,6])
[3, 4, 5, 6, 8]
>>> sorted('hello,world!')
['!', ',', 'd', 'e', 'h', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('hello,world!'))
['!', 'd', 'l', 'r', 'o', 'w', ',', 'o', 'l', 'l', 'e', 'h']
>>> ''.join(reversed('hello,world!'))
'!dlrow,olleh'
>>>

跳出循环

break

>>> from math import sqrt
>>> for n in range(99,0,-1):
root=sqrt(n)
if root==int(root):
print n
break

81
>>>

continue

for x in seq:
if condition1: continue
if condition2: continue
if condition3: continue

do_someting()

do_someting_else()

do_another_thing()

ect()

while True/break

>>> word='dummy'
>>> while word:
word=raw_input('Please enter a world: ')
print 'The word was '+word

Please enter a world: first
The word was first
Please enter a world: sencond
The word was sencond
Please enter a world: third
The word was third
Please enter a world: dummy
The word was dummy
Please enter a world:
The word was
>>>
>>> while True:
word=raw_input('Please enter a word: ')
if not word: break
print 'The word was' + word

Please enter a word: d
The word wasd
Please enter a word:
>>>

循环中的else子句

>>> from math import sqrt
>>> for n in range(99,81,-1):
root=sqrt(n)
if root==int(root):
print n
break
else:
print "Didn't find it!"

Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
Didn't find it!
>>>

列表推导式--轻量级循环

>>> [x*x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> [x*x for x in range(10) if x%3==0]
[0, 9, 36, 81]

>>> [(x,y)for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>> result=[]
>>> for x in range(3):
for y in range(3):
result.append((x,y))

>>> list(result)
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
>>>

pass

if name=='ralph auldus melish':
print 'welcome!'
elif name=='enid':
pass
elif name=='bill gates':
print 'access denied'

del

>>> x=['hello','world']
>>> y=x
>>> y[1]='pyhton'
>>> x
['hello', 'pyhton']
>>> del x
>>> y
['hello', 'pyhton']

转载于:https://www.cnblogs.com/whats/p/4686463.html

Python学习笔记(语句)相关推荐

  1. python基本语法语句-python学习笔记:基本语法

    原标题:python学习笔记:基本语法 缩进:必须使用4个空格来表示每级缩进,支持Tab字符 if语句,经常与else, elif(相当于else if) 配合使用. for语句,迭代器,依次处理迭代 ...

  2. python学习笔记(九)之语句1

    python学习笔记(九)之语句1 print python2中,print是一个语句,python3中它是一个函数. 实例1: >> print "hello,world!&q ...

  3. 【Python学习笔记】第一章基础知识:格式化输出,转义字符,变量类型转换,算术运算符,运算符优先级和赋值运算符,逻辑运算符,世界杯案例题目,条件判断if语句,猜拳游戏与三目运算符

    Python学习笔记之[第一章]基础知识 前言: 一.格式化输出 1.基本格式: 2.练习代码: 二.转义字符 1.基本格式: 2.练习代码: 3.输出结果: 三.输入 1.基本格式: 2.练习代码: ...

  4. Python学习笔记(十一)

    Python学习笔记(十一): 生成器,迭代器回顾 模块 作业-计算器 1. 生成器,迭代器回顾 1. 列表生成式:[x for x in range(10)] 2. 生成器 (generator o ...

  5. python学习笔记目录

    人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...

  6. python 学习笔记 12 -- 写一个脚本获取城市天气信息

    近期在玩树莓派,前面写过一篇在树莓派上使用1602液晶显示屏,那么可以显示后最重要的就是显示什么的问题了. 最easy想到的就是显示时间啊,CPU利用率啊.IP地址之类的.那么我认为呢,假设可以显示当 ...

  7. 廖Python学习笔记一

    1. 廖Python学习笔记 大的分类 如函数 用二级标题,下面的用三级 如输入输出 1.1.1. 输入输出 1.1.1.1. 输出 用 print() 在括号里加上字符串,就可以向屏幕上输出指定的文 ...

  8. Python学习笔记(六)

    1. IO编程 1.1 文件读写 1.2 StringIO和BytesIO 1.3 操作文件和目录 1.4 序列化 2. 进程和线程 2.1 多进程 2.2 多线程 2.3 ThreadLocal 2 ...

  9. Python学习笔记:Day 16 编写移动App

    前言 最近在学习深度学习,已经跑出了几个模型,但Pyhton的基础不够扎实,因此,开始补习Python了,大家都推荐廖雪峰的课程,因此,开始了学习,但光学有没有用,还要和大家讨论一下,因此,写下这些帖 ...

  10. Python学习笔记:Day15 部署Web App

    前言 最近在学习深度学习,已经跑出了几个模型,但Pyhton的基础不够扎实,因此,开始补习Python了,大家都推荐廖雪峰的课程,因此,开始了学习,但光学有没有用,还要和大家讨论一下,因此,写下这些帖 ...

最新文章

  1. ios仿淘宝管理收货地址demo
  2. 宏定义中的#、##操作符和... 、 _ _VA_ARGS_ _解析
  3. 关于变量在循环内声明还是在循环外声明
  4. php MySQL快速入门_PHP 连接 MySQL
  5. neutron plugin 与 extension 编写流程
  6. 2017.10.1 互不侵犯king 思考记录
  7. Nagios+zabbix+ganglia的相关参数分析和优缺点介绍
  8. 运动目标跟踪(九)--Struck跟踪原理
  9. 【Unity3D面试题】Unity面试题
  10. 如何批量修改Word文档Mathtype公式字体
  11. 使用uTools快捷地图片转文字
  12. SCI收录期刊——声学学科 (转载)
  13. 商业广告的本质在于其商业性 在于激发对品牌的想象
  14. 鸿蒙天钟小白图片,果然又一令人震惊的取名方式-“小白”
  15. matlab 不等式组求解例子,matlab求解不等式组
  16. 射频:杂散和谐波的区别
  17. OCR手写数字识别什么软件好用?介绍一种
  18. 8421码,5421码,2421码和余3码的分类及转换
  19. 智慧养老如何养老及智慧养老的发展情况
  20. 服务器系统里面怎么查看有没有做raid,windows如何查看服务器raid信息

热门文章

  1. 2018-2019-1 20165319 《信息安全系统设计基础》第四周学习总结
  2. PHP中文分词扩展 SCWS
  3. 【转】NUnit2.0详细使用方法
  4. Delphi程序开启XP的ClearType显示效果
  5. Android 热修复的相关总结(主要是阿里百川的)
  6. 将txt文档按行分割
  7. NSIS 设置系统变量
  8. CentOS 7 常用命令
  9. 利用DELL的OMSA监控服务器的温度
  10. HTML不刷新,改数据