標籤:解析 eth imp image 分享 nal ror marked 儲存
Hello World程式
學習語言必經之路。
1 #!/usr/bin/env python2 3 print "hello,world"
在互動器中執行
除了把程式寫在檔案裡,還可以直接調用python內建的互動器運行代碼。
D:\python>python "hello world.py"Hello World
Pyhthon基礎文法標識符/關鍵字
- 第一個字元必須是字母或底線。
標識符由字母、數字和底線組成。
標識符對大小寫敏感
import keyword #引入模組
keyword.kwlist #keyword儲存了python所有關鍵字。
變數\字元編碼聲明變數
#_*_coding:utf-8_*_ name = "Mr peng"
上述代碼聲明一個變數,變數名為name值為"Mr peng"
注釋
單行--->#
多行--->"""被注釋的內容"""(多行注釋需要成對出現)。
行的縮減
python最具特色的就是使用縮排來表示代碼塊,不需要使用大括弧 {} 。
縮排的空格數是可變的,但是同一個代碼塊的語句必須包含相同的縮排空格數。執行個體如下:
同一代碼塊縮排時空格數必須相同。
多行語句
Python 通常是一行寫完一條語句,但如果語句很長,我們可以使用反斜線(\)來實現多行語句。
total = item_one + \
item_two + \
item_three
在 [], {}, 或 () 中的多行語句,不需要使用反斜線(\),例如:
total = [‘item_one‘, ‘item_two‘, ‘item_three‘,
‘item_four‘, ‘item_five‘]
同一行顯示多條語句
Python可以在同一行中使用多條語句,語句之間使用分號(;)分割
使用者輸入
#!/usr/bin/env python#_*_coding:utf-8_*_ #name = raw_input("What is your name?") #only on python 2.xname = input("What is your name?") #python 3.#print("Hello " + name )
輸入密碼時:在Pycharm5.0.3中引用:
#!/usr/bin/env python# -*- coding: utf-8 -*-import getpass#會出現執行不下去pwd = getpass.getpass("請輸入密碼:") 查看print詳細資料
print() ---->ctrl+滑鼠左鍵 可以查看函數詳細資料
def print(*args, sep=‘ ‘, end=‘\n‘, file=None): # known special case of print
"""
print(value, ..., sep=‘ ‘, end=‘\n‘, file=sys.stdout, flush=False)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
flush: whether to forcibly flush the stream.
"""
pass
條件判斷
#根據系統提示猜測商品價格#僅限猜測3次,超過則提示# 如果正確,則輸出bigger# 猜多猜少均有提示#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:Mr pengC_PRICE = 1520count = 0while count < 3: price = int(input("輸入商品價格")) if price == C_PRICE: print("bigger") break elif price < C_PRICE: print("少了") else: #表示排除以上兩種剩餘的哪些 print("多了") count += 1 if count == 3: countlink = input("按Enter鍵繼續n結束") if countlink != ‘n‘: count = 0
條件迴圈
Python迴圈語句有 for 和 while.
for語句
Python for迴圈可以遍曆任何序列的項目,如一個列表或者一個字串。
for迴圈的一般格式如下:
for i in range(0,10): print("loop",i) if i == 5: breakelse: #for迴圈正常結束,就能執行 print(‘結束‘)
for的遍曆執行個體:
languages = ["C", "C++", "Perl", "Python"] for x in languages: print (x)
whlie語句
有一種愛叫做天長地久,有一種迴圈叫做死迴圈,一旦運行,就運行到天荒地老。
天荒地老代碼:
count = 0while True: print(count) count +=1
Python3 解譯器
由兩種互動式編程(命令列) 指令碼式編程(編寫完程式後,邊解析邊執行)
python學習之路1