Python學習筆記(語句)

來源:互聯網
上載者:User

標籤:

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‘]

 

Python學習筆記(語句)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.