printpython
print 如今是一個函數,再也不是一個語句。<語法更爲清晰>函數
實例1spa
打開文件 log.txt 以便進行寫入並將對象指定給 fid。而後利用 print將一個字符串重定向給文件 fid。3d
fid=open("log.txt",'w')對象
print("log.txt", file=fid)blog
print("hello")字符串
#fid = open("log.txt", 'w')get
#print>>fid, "log text"class
#print "hello"變量
#print("Foo", "Bar", sep="%")
Python3.X執行結果:
#fid=open("log.txt",'w')
#print("log.txt", file=fid)
#print("hello")
fid = open("log.txt", 'w')
print>>fid, "log text"
print "hello"
#print("Foo", "Bar", sep="%")
Python2.X執行結果:
實例2
print("Foo", "Bar", sep="%")
#fid=open("log.txt",'w')
#print("log.txt", file=fid)
#print("hello")
#fid = open("log.txt", 'w')
#print>>fid, "log text"
#print "hello"
print("Foo", "Bar", sep="%")
Python3.X中執行結果:
exec
exec()做爲函數,只操做globals()和locals()函數返回的字典。locals()函數返回的字典其實是局部變量的一個副本。exec()函數中進行的賦值只修改了局部變量的這份副本,而非局部變量自己。
實例:
def foo():
exec('a=4')
print(a)
foo()
#def foo():
# _locals = locals()
# exec('a=4',globals(),_locals)
# a = _locals['a']
#print (a)
#foo()
Python2.X中執行結果:
Python3.X中執行結果:
#def foo():
# exec('a=4')
# print(a)
#foo()
def foo():
_locals = locals()
exec('a=4',globals(),_locals)
a = _locals['a']
print (a)
foo()
Python3.X中執行結果: