Python基礎

@貳拾貳畫生


感謝?簡明Python教程


輸入輸出

輸入:raw_input

string = raw_input('Enter something:')

輸出:print

s = 'aaa'

i = 1

print string; print 's = %s, i = %d', (s, i)

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

字符串

單引號’ 雙引號” 或三引號’’’ “”"?三引號指示一個多行的字符串如

‘’'fdalkjflksajfkl

fdafdsa

fda’''

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

字符串中轉義字符?\

自然字符串,指示某些不需要如轉義符那樣的特別處理的字符串,字符串前加r或R

r”Newlines are indicated by \n"

Unicode字符串:前加u或U

u”This is a Unicode string"

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

級連字符串

兩個字符串按字面意義相鄰放著

‘What\’s?’ ‘your name?’

會被自動轉成

“What’s your name?”

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

多個物理行寫一個邏輯行

s = ’This is a string. \

This continues the string.'

print s

輸出為:This is a string. This continues the string.

同理

print \

i

等同于

print i

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

#if else 語句

number = 23

? ? ? ?guess =int(raw_input('Enter an integer : '))

if guess == number:

? ? ? print 'Congratulations, you guessed it.'

? ? ? print "(but you do not win any prizes!)"

elif guess < number:

? ? ? print 'No, it is a little higher than that'

else:

? ? ? print 'No, it is a little lower than that'

print 'Done'

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

# while語句

number =23

running =True

while running:

? ? ? guess = int(raw_input('Enter an integer : '))

? ? ? if guess == number:

? ? ? ? ? ? print 'Congratulations, you guessed it.'

? ? ? ? ? ? running =False

? ? ? elif guess < number:

? ? ? ? ? ? print 'No, it is a little higher than that'

? ? ? else:

? ? ? ? ? ? print 'No, it is a little lower than that'

else:

? ? ?print 'The while loop is over.'

print 'Done'

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

break 語句

while True:

? ? ? s = raw_input('Enter something : ')

? ? ? if s == 'quit':

? ? ? ? ? ? break

? ? ? print 'Length of the string is', len(s)

print 'Done'

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

continue 語句

continue語句被用來告訴Python跳過當前循環塊中的剩余語句,然后繼續進行下一輪循環。

while True:

? ? ? s = raw_input('Enter something : ')

? ? ? if s == 'quit':

? ? ? ? ? ? break

? ? ? if len(s) <3:

? ? ? ? ? ?continue

? ? ? print 'Input is of sufficient length'

輸出結果為:

Enter something : a

Enter something : 12

Enter something : abc

Input is of sufficient length

Enter something : quit

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

函數用?def 關鍵字來定義

def printMax(a, b):

? ? ? if a > b:

? ? ? ? ? ? ?print a, ' is maximum'

? ? ? else:

? ? ? ? ? ? print b, ' is maximum'

print Max(3,4)

x =5

y =7

print Max(x, y)

輸出:

4 is maximum

7 is maximum

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

使用 global 定義全局變量

def func():

? ? ? global x

? ? ? print 'x is', x

? ? ? x = 2

? ? ? print 'Changed local x to', x

x = 50

func()

print 'Value of x is', x

輸出:

x is 50

Changed global x to 2

Value of x is 2

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

可選的默認參數

def say(message, times = 1):

? ? ? print message * times

say('Hello')

say('World', 5)

輸出:

Hello

WorldWorldWorldWorldWorld

注意:只有在形參表末尾的那些參數可以有默認參數值,即你不能在聲明函數形參的時候,先聲明有默認值的形參而后聲明沒有默認值的形參。例如,def func(a, b=5)是有效的,但是def func(a=5, b)是無效的。

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

關鍵參數

def func(a, b=5, c=10):

? ? ? print 'a is ', a, ' and b is ', b, ' and c is ', c

func(3, 7)

func(25, c=24)

func(c=50, a=100)

輸出:

a is 3 and b is 7 and c is 10

a is 25 and b is 5 and c is 24

a is 100 and b is 5 and c is 50

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

函數返回

def maximum(x, y):

? ? ? if x > y:

? ? ? ? ? ? return x

? ? ? else:

? ? ? ? ? ? return y

print maximum(2,3)

輸出:

3

注意:沒有返回值的return語句等價于return None。None是Python中表示沒有任何東西的特殊類型。例如,如果一個變量的值為None,可以表示它沒有值。

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

使用DocStrings

def printMax(x, y):

? ? ? ?'''Prints the maximum of two numbers.

? ? ? The two values must be integers.'''

? ? ? x = int(x)

? ? ? y = int(y)

? ? ? if x > y:

? ? ? ? ? ? print x, 'is maximum'

? ? ? else:

? ? ? ? ? ? print y,'is maximum'

print Max(3,5)

print printMax.__doc__

輸出:

5 is maximum

Prints the maximum of two numbers.

The two values must be integers.

DocStrings 也適用于模塊和類。

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

模塊

模塊的文件名必須以 .py 為擴展名

使用?sys 模塊

import sys

print 'The command line arguments are:'

? ? ? for i in sys.argv:

? ? ? ? ? ? print i

print '\n\nThe PYTHONPATH is', sys.path, '\n'

輸出

The command line arguments are:

using_sys.py

we

are

arguments

The PYTHONPATH is ['/home/swaroop/byte/code', '/usr/lib/python23.zip',

'/usr/lib/python2.3', '/usr/lib/python2.3/plat-linux2',

'/usr/lib/python2.3/lib-tk', '/usr/lib/python2.3/lib-dynload',

'/usr/lib/python2.3/site-packages', '/usr/lib/python2.3/site-packages/gtk-2.0']

sys模塊包含了與Python解釋器和它的環境有關的函數。

腳本的名稱總是sys.argv列表的第一個參數。所以,在這里,'using_sys.py'是sys.argv[0]、'we'是sys.argv[1]、'are'是sys.argv[2]以及'arguments'是sys.argv[3]

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

字節編譯的.pyc文件

輸入一個模塊相對來說是一個比較費時的事情,所以Python做了一些技巧,以便使輸入模塊更加快一些。一種方法是創建字節編譯的文件,這些文件以.pyc作為擴展名。字節編譯的文件與Python變換程序的中間狀態有關(是否還記得Python如何工作的介紹?)。當你在下次從別的程序輸入這個模塊的時候,.pyc文件是十分有用的——它會快得多,因為一部分輸入模塊所需的處理已經完成了。另外,這些字節編譯的文件也是與平臺無關的。所以,現在你知道了那些.pyc文件事實上是什么了。

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

from..import語句

如果你想要直接輸入argv變量到你的程序中(避免在每次使用它時打sys.),那么你可以使用from sys import argv語句。如果你想要輸入所有sys模塊使用的名字,那么你可以使用from sys import *語句。這對于所有模塊都適用。一般說來,應該避免使用from..import而使用import語句,因為這樣可以使你的程序更加易讀,也可以避免名稱的沖突。

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

模塊的__name__

每個模塊都有一個名稱,在模塊中可以通過語句來找出模塊的名稱。這在一個場合特別有用——就如前面所提到的,當一個模塊被第一次輸入的時候,這個模塊的主塊將被運行。假如我們只想在程序本身被使用的時候運行主塊,而在它被別的模塊輸入的時候不運行主塊,我們該怎么做呢?這可以通過模塊的__name__屬性完成。

if __name__ == '__main__':

? ? ? print 'This program is being run by itself'

else:

? ? ? print 'I am being imported from another module'

輸出:

This program is being run by itself

>>> import using_name

I am being imported from another module

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

創建及引用模塊

創建自己的模塊:

#Filename: mymodule.py

def sayhi():

? ? ? print 'Hi, this is mymodule speaking.'

version ='0.1'

在與該模塊的同等目錄下

import mymodule

mymodule.sayhi()

print 'Version ', mymodule.version

輸出:

Hi, this is mymodule speaking.

Version 0.1

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

dir() 函數

用來列出模塊定義的標識符。標識符有函數、類和變量

如上例,執行

?dir(mymodule)

輸出:

['__builtins__', '__doc__', '__file__', '__name__', '__package__', 'sayhi', 'version']

如果不給?dir 函數傳遞參數,默認地,它會返回當前模塊的屬性列表。

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

Python 中有三種內建的數據結構:列表、元組和字典。

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

列表

shoplist = ['apple', 'mango', 'carrot', 'banana']

print 'I have ', len(shoplist), ' items to purchase.'

print 'These items are:', # Notice the comma at end of the line

for item in shoplist:

? ? ? print item,

print '\nI also have to buy rice.'

shoplist.append('rice')

print 'My shopping list is now', shoplist

print 'I will sort my list now'

shoplist.sort()

print 'Sorted shopping list is', shoplist

print 'The first item I will buy is', shoplist[0]

olditem = shoplist[0]

del shoplist[0]

print 'I bought the', olditem

print 'My shopping list is now', shoplist

輸出:

I have 4 items to purchase.

These items are: apple mango carrot banana

I also have to buy rice.

My shopping list is now ['apple', 'mango', 'carrot', 'banana', 'rice']

I will sort my list now

Sorted shopping list is ['apple', 'banana', 'carrot', 'mango', 'rice']

The first item I will buy is apple

I bought the apple

My shopping list is now ['banana', 'carrot', 'mango', 'rice']

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

元組

元組和列表十分類似,只不過元組和字符串一樣是不可變的,即你不能修改元組。

zoo = ('wolf', 'elephant', 'penguin')

print 'Number of animals in the zoo is', len(zoo)

new_zoo = ('monkey', 'dolphin', zoo)

print 'Number of animals in the new zoo is', len(new_zoo)

print 'All animals in new zoo are', new_zoo

print 'Animals brought from old zoo are', new_zoo[2]

print 'Last animal brought from old zoo is', new_zoo[2][2]

輸出:

Number of animals in the zoo is 3

Number of animals in the new zoo is 3

All animals in new zoo are ('monkey', 'dolphin', ('wolf', 'elephant', 'penguin'))

Animals brought from old zoo are ('wolf', 'elephant', 'penguin')

Last animal brought from old zoo is penguin

有0個項目的元組:myempty = ()

有1個項目的元組:singleton = (1, )

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

元組與打印語句

age =22

name = 'Swaroop'

print ' %s is %d years old.’ % (name, age) #此句等同:print name, ‘ is ‘, age, ‘ years old.'

print 'Why is %s playing with that python?' % name

輸出:

Swaroop is 22 years old

Why is Swaroop playing with that python?

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

字典

ab = { ? 'Swaroop' ?: ?'swaroopch@byteofpython.info',

? ? ? ? ? ? ? 'Larry' ? ? : ?'larry@wall.org',

? ? ? 'Matsumoto' ? : ?'matz@ruby-lang.org',

? ? ?'Spammer' ? ? ? : ?'spammer@hotmail.com'

}

print "Swaroop's address is %s" % ab['Swaroop']

ab['Guido'] = 'guido@python.org'

del ab['Spammer']

print '\nThere are %d contacts in the address-book\n' % len(ab)

for name, address in ab.items():

? ? ? print 'Contact %s at %s' % (name, address)

if 'Guido' in ab:

print "\nGuido's address is %s" % ab['Guido']

輸出:

Swaroop's address isswaroopch@byteofpython.info

There are 4 contacts in the address-book

Contact Swaroop atswaroopch@byteofpython.info

Contact Matsumoto atmatz@ruby-lang.org

Contact Larry atlarry@wall.org

Contact Guido atguido@python.org

Guido's address isguido@python.org

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

序列

序列的兩個主要特點是索引操作符和切片操作符。索引操作符讓我們可以從序列中抓取一個特定項目。切片操作符讓我們能夠獲取序列的一個切片,即一部分序列。

shoplist = ['apple', 'mango', 'carrot', 'banana']

print 'Item 0 is ', shoplist[0]

print 'Item 1 is ', shoplist[1]

print 'Item 2 is ', shoplist[2]

print 'Item 3 is ', shoplist[3]

print 'Item -1 is ', shoplist[-1]

print 'Item -2 is ', shoplist[-2]

# Slicing on a list

print 'Item 1 to 3 is ', shoplist[1:3]

print 'Item 2 to end is ', shoplist[2:]

print 'Item 1 to -1 is ', shoplist[1:-1]

print 'Item start to end is ', shoplist[:]

輸出:

Item 0 is apple

Item 1 is mango

Item 2 is carrot

Item 3 is banana

Item -1 is banana

Item -2 is carrot

Item 1 to 3 is ['mango', 'carrot']

Item 2 to end is ['carrot', 'banana']

Item 1 to -1 is ['mango', 'carrot']

Item start to end is ['apple', 'mango', 'carrot', 'banana']


name = 'swaroop'

print 'characters 1 to 3 is', name[1:3]

print 'characters 2 to end is', name[2:]

print 'characters 1 to -1 is', name[1:-1]

print 'characters start to end is', name[:]

輸出:

characters 1 to 3 is wa

characters 2 to end is aroop

characters 1 to -1 is waroo

characters start to end is swaroop

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

參考

當你創建一個對象并給它賦一個變量的時候,這個變量僅僅參考那個對象,而不是表示這個對象本身!也就是說,變量名指向你計算機中存儲那個對象的內存。這被稱作名稱到對象的綁定。

print 'Simple Assignment'

shoplist = ['apple', 'mango', 'carrot', 'banana']

mylist = shoplist # mylist is just another name pointing to the same object!

del shoplist[0]

print 'shoplist is', shoplist

print 'mylist is', mylist

# notice that both shoplist and mylist both print the same list without

# the 'apple' confirming that they point to the same object

print 'Copy by making a full slice'

mylist = shoplist[:] # make a copy by doing a full slice

del mylist[0]

print 'shoplist is', shoplist

print 'mylist is', Myles


輸出:

Simple Assignment

shoplist is ['mango', 'carrot', 'banana']

mylist is ['mango', 'carrot', 'banana']

Copy by making a full slice

shoplist is ['mango', 'carrot', 'banana']

mylist is ['carrot', 'banana']

注意:如果你想要復制一個列表或者類似的序列或者其他復雜的對象(不是如整數那樣的簡單對象),那么你必須使用切片操作符來取得拷貝。如果你只是想要使用另一個變量名,兩個名稱都參考同一個對象,那么如果你不小心的話,可能會引來各種麻煩。

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

更多字符串方法

name = 'Swaroop' # This is a string object

if name.startswith('Swa'):

? ? ? print 'Yes, the string starts with "Swa"'

if 'a' in name:

? ? ? print 'Yes, it contains the string "a"'

if name.find('war') !=-1: #返回-1表示找不到子字符串

? ? ? print 'Yes, it contains the string "war"'

delimiter = '_*_'

mylist = ['Brazil', 'Russia', 'India', 'China']

print delimiter.join(mylist)

輸出:

Yes, the string starts with "Swa"

Yes, it contains the string "a"

Yes, it contains the string "war"

Brazil_*_Russia_*_India_*_China

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

類 class

class Person:

? ? ? population = 0

? ? ? def __init__(self, name):

? ? ? ? ? ? ?self.name?= name

? ? ? ? ? ? print '(Initializing %s)' % self.name

? ? ? ? ? ? Person.population += 1

? ? ? def __del__(self):

? ? ? ? ? ? '''I am dying.'''

? ? ? ? ? ? print' %s says bye.' % self.name

? ? ? ? ? ? Person.population -= 1

? ? ? ? ? ? if Person.population == 0:

? ? ? ? ? ? ? ? ? print 'I am the last one.'

? ? ? ? ? ? else:

? ? ? ? ? ? ? ? ? print 'There are still %d people left.' % Person.population

? ? ? def sayHi(self):

? ? ? ? ? ? '''Greeting by the person.

? ? ? ? ? ? ?Really, that's all it does.'''

? ? ? ? ? ? print 'Hi, my name is %s.' % self.name


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

繼承

class SchoolMember:

? ? ? def __init__(self, name):

? ? ? ? ? ??self.name?= name

? ? ? def tell(self):

? ? ? ? ? ? print 'Name: ' +?self.name

class Teacher(SchoolMember):

? ? ? ?def __init__(self, name, salary):

? ? ? ? ? ? SchoolMember.__init__(self, name)

? ? ? ? ? ? self.salary = salary

? ? ? def tell(self):

? ? ? ? ? ? print 'Salary : %d ' % self.salary

class Student(SchoolMember):

? ? ? def __init__(self, name, marks):

? ? ? ? ? ? SchoolMember.__init__(self, name)

? ? ? ? ? ? self.marks = marks

? ? ? def tell(self):

? ? ? ? ? ? print 'Marks : %d' % self.marks

t = Teacher('Chengjie', 10000)

s = Student('Makai', 99)

members = [t, s]

for member in members:

? ? ? member.tell()

輸出:

Salary : 10000

Marks : 99

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

操作文件 file

poem = '''\

Programming is fun

When the work is done

if you wanna make your work also fun:

use Python!

'''

f = file('poem.txt', 'w')

f.write(poem)

f.close()

f = file('poem.txt')

# if no mode is specified, 'r'ead mode is assumed by default

while True:

? ? ? line = f.readline()

? ? ? if len(line) ==0:# Zero length indicates EOF

? ? ? ? ? ? break

? ? ? print line,

f.close()# close the file


輸出:

Programming is fun

When the work is done

if you wanna make your work also fun:

use Python!

r:讀模式

w:寫模式

a:追加模式

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

儲存器

Python提供一個標準的模塊,稱為pickle。使用它你可以在一個文件中儲存任何Python對象,之后你又可以把它完整無缺地取出來。這被稱為持久地儲存對象。

還有另一個模塊稱為cPickle,它的功能和pickle模塊完全相同,只不過它是用C語言編寫的,因此要快得多(比pickle快1000倍)。你可以使用它們中的任一個,而我們在這里將使用cPickle模塊。記住,我們把這兩個模塊都簡稱為pickle模塊。

import cPickle as p

shoplistfile = 'shoplist.data'

shoplist = ['apple', 'mango', 'carrot']

# Write to the file

f = file(shoplistfile, 'w')

p.dump(shoplist, f)# dump the object to a file

f.close()

del shoplist

# Read back from the storage

f = file(shoplistfile)

storedlist = p.load(f)

print storedlist

輸出:

['apple', 'mango', 'carrot']

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

異常

基本格式:

try:

? ? ? fadfdsafdaf

except EOFError:

? ? ? fdaferewasfsdfas

except:

? ? ? fdafdafwerwe

import sys

try:

? ? ? s = raw_input('Enter something --> ')

except EOFError:

? ? ? print '\nWhy did you do an EOF on me?'

? ? ? sys.exit()

except:

? ? ? print '\nSome error/exception occurred.'

? ? ? # here, we are not exiting the program

print 'Done'

輸出:

Enter something—>(#此處輸入ctrl + d)

Why did you do an EOF on me?

$ pythontry_except.py

Enter something --> Python is exceptional!

Done

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

使用 raise 引發異常

自定義并異常:

class ShortInputException(Exception):

? ? ? '''A user-defined exception class.'''

? ? ? def __init__(self, length, atleast):

? ? ? ? ? ? Exception.__init__(self)

? ? ? ? ? ? self.length = length

? ? ? ? ? ? self.atleast = atleast

try:

? ? ? s =raw_input('Enter something --> ')

? ? ? if len(s) < 3:

? ? ? ? ? ? raise ShortInputException(len(s), 3)

# Other work can continue as usual here

except EOFError:

? ? ? print '\nWhy did you do an EOF on me?'

except ShortInputException, x:

? ? ? print 'ShortInputException: The input was of length %d, \

? ? ? was expecting at least %d'% (x.length, x.atleast)

else:

? ? ? print 'No exception was raised.'

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

try…finally

finally 后為必定執行語句

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

os模塊

這個模塊包含普遍的操作系統功能。如果你希望你的程序能夠與平臺無關的話,這個模塊是尤為重要的。即它允許一個程序在編寫后不需要任何改動,也不會發生任何問題,就可以在Linux和Windows下運行。一個例子就是使用os.sep可以取代操作系統特定的路徑分割符。

下面列出了一些在os模塊中比較有用的部分。它們中的大多數都簡單明了。

os.name字符串指示你正在使用的平臺。比如對于Windows,它是'nt',而對于Linux/Unix用戶,它是'posix'。

os.getcwd()函數得到當前工作目錄,即當前Python腳本工作的目錄路徑。

os.getenv()和os.putenv()函數分別用來讀取和設置環境變量。

os.listdir()返回指定目錄下的所有文件和目錄名。

os.remove()函數用來刪除一個文件。

os.system()函數用來運行shell命令。

os.linesep字符串給出當前平臺使用的行終止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。

os.path.split()函數返回一個路徑的目錄名和文件名。

>>> os.path.split('/home/swaroop/byte/code/poem.txt')

('/home/swaroop/byte/code', 'poem.txt')

os.path.isfile()和os.path.isdir()函數分別檢驗給出的路徑是一個文件還是目錄。類似地,os.path.existe()函數用來檢驗給出的路徑是否真地存在。

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

特殊的方法

在類中有一些特殊的方法具有特殊的意義,比如__init__和__del__方法,它們的重要性我們已經學習過了。

一般說來,特殊的方法都被用來模仿某個行為。例如,如果你想要為你的類使用x[key]這樣的索引操作(就像列表和元組一樣),那么你只需要實現__getitem__()方法就可以了。想一下,Python就是對list類這樣做的!

下面這個表中列出了一些有用的特殊方法。如果你想要知道所有的特殊方法,你可以在《Python參考手冊》中找到一個龐大的列表。

表15.1 一些特殊的方法

名稱說明

__init__(self,...) ?這個方法在新建對象恰好要被返回使用之前被調用。

__del__(self) ?恰好在對象要被刪除之前調用。

__str__(self) ?在我們對對象使用print語句或是使用str()的時候調用。

__lt__(self,other) ?當使用小于運算符(<)的時候調用。類似地,對于所有的運算符(+,>等等)都有特殊的方法。

__getitem__(self,key) ?使用x[key]索引操作符的時候調用。

__len__(self) ?對序列對象使用內建的len()函數的時候調用。

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

列表綜合

通過列表綜合,可以從一個已有的列表導出一個新的列表。例如,你有一個數的列表,而你想要得到一個對應的列表,使其中所有大于2的數都是原來的2倍。對于這種應用,列表綜合是最理想的方法。

使用列表綜合

例15.1 使用列表綜合

#!/usr/bin/python

# Filename:list_comprehension.py

listone = [2,3,4]

listtwo = [2*i for i in listone if i >2]

print listtwo

輸出

$ pythonlist_comprehension.py

[6, 8]

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

在函數中接收元組和列表

當要使函數接收元組或字典形式的參數的時候,有一種特殊的方法,它分別使用*和**前綴。這種方法在函數需要獲取可變數量的參數的時候特別有用。

>>> def powersum(power, *args):

... ? ? ? ? ? '''Return the sum of each argument raised to specified power.'''

... ? ? ? ? ? total = 0

... ? ? ? ? ? for i in args:

... ? ? ? ? ? ? ? ?total += pow(i, power)

... ? ? ? ? ? return total

...

>>> powersum(2, 3, 4)

25

>>> powersum(2, 10)

100

由于在args變量前有*前綴,所有多余的函數參數都會作為一個元組存儲在args中。如果使用的是**前綴,多余的參數則會被認為是一個字典的鍵/值對。

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

lambda形式

lambda語句被用來創建新的函數對象,并且在運行時返回它們。

例15.2 使用lambda形式

#!/usr/bin/python

# Filename:lambda.py

def make_repeater(n):

? ? ? return lambdas: s*n #可為多參數,如:?return lambda s1,?s2: ?s1 + s2 +?n

twice = make_repeater(2)

printtwice('word')

printtwice(5)

輸出

$ pythonlambda.py

wordword

10

它如何工作

這里,我們使用了make_repeater函數在運行時創建新的函數對象,并且返回它。lambda語句用來創建函數對象。本質上,lambda需要一個參數,后面僅跟單個表達式作為函數體,而表達式的值被這個新建的函數返回。注意,即便是print語句也不能用在lambda形式中,只能使用表達式。

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

exec和eval語句

exec語句用來執行儲存在字符串或文件中的Python語句。例如,我們可以在運行時生成一個包含Python代碼的字符串,然后使用exec語句執行這些語句。下面是一個簡單的例子。

>>> exec 'print "Hello World"'

Hello World

eval語句用來計算存儲在字符串中的有效Python表達式。下面是一個簡單的例子。

>>> eval('2*3')

6

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

assert語句

assert語句用來聲明某個條件是真的。例如,如果你非常確信某個你使用的列表中至少有一個元素,而你想要檢驗這一點,并且在它非真的時候引發一個錯誤,那么assert語句是應用在這種情形下的理想語句。當assert語句失敗的時候,會引發一個AssertionError。

>>> mylist = ['item']

>>> assert len(mylist) >= 1

>>> mylist.pop()

'item'

>>> assert len(mylist) >= 1

Traceback (most recent call last):

? ? ? File "", line 1, in ?

AssertionError

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

repr函數

repr函數用來取得對象的規范字符串表示。反引號(也稱轉換符)可以完成相同的功能。注意,在大多數時候有eval(repr(object)) == object。

>>> i = []

>>> i.append('item')

>>> `i`

"['item']"

>>> repr(i)

"['item']"

基本上,repr函數和反引號用來獲取對象的可打印的表示形式。你可以通過定義類的__repr__方法來控制你的對象在被repr函數調用的時候返回的內容。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Python 基礎教程 實例(Python 2.0+) 實例(Python 3.0+) Python 簡介 Pyt...
    縱我不往矣閱讀 64,771評論 0 23
  • 本節內容 Python介紹 發展史 Python 2 or 3? 安裝 Hello World程序 變量 用戶輸入...
    小小不懂11閱讀 3,444評論 2 30
  • 1.數據類型 整數(int):1,-100浮點數(float):1.23字符串(str):'abc',"xyz"布...
    辛立閱讀 706評論 0 1
  • 今日看到公眾號【女神進化論】的最新文章:如何避免補償性消費而培養正確消費觀?文章里提到產生補償型消費的原因主要如下...
    Sing_2017閱讀 258評論 0 0
  • 今晚可能是我最后一個交作業了,有這個組織真好,互相鼓勵和監督,想偷懶都不好意思! 今天的時間很緊湊,直到現在才洗涮...
    宋寧靜閱讀 92評論 2 0