Python基礎語法¶
1、Python編程模式¶
交互式:
命令逐條運行
交互式編程不需要創建腳本文件,是通過 Python 解釋器的交互模式進來編寫代碼。
print("hello world")
>>> 1+1
>>> a=1
>>> b=1
>>> a+b
腳本式:
一次性全部運行
通過腳本參數調用解釋器開始執行腳本,直到腳本執行完畢。當腳本執行完成後,解釋器不再有效。
my_dream='I want to be a quantitative trader.'
print('Hello,world!!! '+my_dream)
print (my_dream + ' What can I do?')
#點擊run,顯示運行結果:
2、 Python標識符¶
在 Python 里,標識符由字母、數字、下劃線組成。
在 Python 中,所有標識符可以包括英文、數字以及下劃線_,但不能以數字開頭。
Python 中的標識符是區分大小寫的。
Python 可以同一行顯示多條語句,方法是用分號 ;
1A_ = 1
print(1A_)
A1_ = 1
print(A1_)
a1_ = 2
print(a1_)
A = 1; a=2
print(A,a)
3、 Python 保留字符¶
下面的列表顯示了在Python中的保留字。這些保留字不能用作常數或變數,或任何其他標識符名稱。
所有 Python 的關鍵字只包含小寫字母。
and | exec | not |
assert | finally | or |
break | for | pass |
class | from | |
continue | global | raise |
def | if | return |
del | import | try |
elif | in | while |
else | is | with |
except | lambda | yield |
4、代碼縮進問題:¶
縮進替代({})
學習Python與其他語言最大的區別就是,Python的代碼塊不使用大括號({})來控制類,函數以及其他邏輯判斷。 python最具特色的就是用縮進來寫模塊。
代碼縮進(錯誤)¶
price = 1
if price>0:
print ('True')
print ('price is greater than 0')
# 沒有嚴格縮進,在執行時會報錯
else:
print ("False")
代碼縮進(正確)¶
price = 1
if price>0:
print ('True')
print ('price is greater than 0')
else:
print ("False")
4、 多行語句處理¶
Python語句中一般以新行作為語句的結束符。
但是我們可以使用斜杠( \)將一行的語句分為多行顯示,如下所示:
Price = 1+\
2+\
3
print(Price)
5.Python 引號¶
Python 可以使用引號( ' )、雙引號( " )、三引號( ''' 或 """ ) 來表示字符串,引號的開始與結束必須的相同類型的。
其中三引號可以由多行組成,被當做注釋。
Name = 'Channel'
Career = "Quantitative Trader"
Habit = '''Poppin'''
print(Name+" is "+Career+' who like '+Habit)
def annotation():
"""
Channel is Quantitative
Trader who like Poppin
"""
annotated = """被注釋"""
return annotated
print(annotation())
6、注釋代碼¶
單行注釋用 # 開頭
多行注釋用三個引號(''')
代碼注釋有一個功能在於可以在寫代碼時跳過不想運行的行
# 寬客你好
# print('hello quant')
# 寬客你好
print('hello quant')
print('hello quant') # 寬客你好
"""
寬客你好
print('hello quant')
"""
print("OK, Let's code")