列印基礎知識
在 Python 3 及更高版本中,print 是一個函式而不是關鍵字。
print('hello world!')
# out: hello world!
foo = 1
bar = 'bar'
baz = 3.14
print(foo)    
# out: 1
print(bar)    
# out: bar
print(baz)
# out: 3.14
你還可以將許多引數傳遞給 print:
print(foo, bar, baz)
# out: 1 bar 3.14
通過+使用 print 的另一種方法是使用+
print(str(foo) + " " + bar + " " + str(baz))
# out: 1 bar 3.14
但是,使用+列印多個引數時應注意的是引數的型別應該相同。嘗試列印上面的示例而不首先使用強制轉換為 string 會導致錯誤,因為它會嘗試將數字 1 新增到字串 bar 並將其新增到數字 3.14。
# Wrong:
# type:int  str  float
print(foo + bar + baz)
# will result in an error
這是因為首先評估 print 的內容:
print(4 + 5)
# out: 9
print("4" + "5")
# out: 45
print([4] + [5])
# out: [4, 5]
否則,使用+對於使用者讀取變數輸出非常有幫助。在下面的示例中,輸出非常容易閱讀!
下面的指令碼演示了這一點
import random 
#telling python to include a function to create random numbers
randnum = random.randint(0, 12) 
#make a random number between 0 and 12 and assign it to a variable
print("The randomly generated number was - " + str(randnum))
你可以使用 end 引數阻止 print 函式自動列印換行符:
print("this has no newline at the end of it... ", end="")
print("see?")
# out: this has no newline at the end of it... see?
如果要寫入檔案,可以將其作為引數 file 傳遞:
with open('my_file.txt', 'w+') as my_file:
    print("this goes to the file!", file=my_file)
這到檔案!