Python学习笔记(语句)

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