第一個Python程序
print('Hello World!')
變量 Variables
my_variable = 10
布爾值 Booleans
my_int = 7
my_float = 1.23
my_bool = True
格式
在Python中利用空格控制縮進來達到代碼分塊的效果(諸如Java中利用'{}'來進行代碼分塊),這是很重要的。
一般使用4個空格來進行換行的縮進。
Python使用#
進行單行注釋。
# 這是一段注釋
mysterious_variable = 42
使用如下結果進行多行注釋
'''
這是一段注釋。
'''
數學計算
Python實現數值計算的方式很簡單,跟MATLAB很像。
addition = 72 + 23
subtraction = 108 - 204
multiplication = 108 * 0.5
division = 108 / 9
eight = 2 ** 3 #冪計算
modulo = 3 % 2 #取模計算
字符串 String
Python利用兩個雙引號"",或者兩個單引號''包裹字符串
caesar = "Graham"
praline = "John"
viking = "Teresa"
在Python中利用空格控制縮進來達到代碼分塊的效果(諸如Java中利用中,如果字符串中有'
,"
,\
等,需要在它們面前增加\
進行轉義,此時字符串才能正常解釋。
選取字符串中的某個字符,只需要傳入相應字符的下標即可。Python中的下標從0開始
fifth_letter = "MONTY"[4] #取出字母Y
常見的字符串函數
len() 返回字符串長度
len(string)
lower() 返回小寫的字符串
string.lower()
upper() 返回大寫的字符串
string.upper()
str() 將非字符串類型轉化為字符串類型
str(2)
isalpha() 判斷字符串是否只由字母組成
string.isalpha()
字符串拼接
Python中利用+
進行多個字符串之間的拼接;非字符串類型需要轉化為字符串類型之后才能進行拼接。
print "The value of pi is around " + str(3.14)
字符串切片
new_word = new_word[1:len(new_word)]
打印 Print
在python3+中,利用print()進行打印信息。
print("Hello World!")
在打印字符串的時候,字符串后面跟著一個,
后打印結果會輸出一個空格。
格式化輸出
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
日期和時間 Date and Time
- 導入日期時間庫
from datetime import datetime
- 打印當前時間
print(datetime.now())
- 獲取日期的年、月、日
datetime.now().year
datetime.now().month
datetime.now().day
- 獲取時間的時、分、秒
datetime.now().hour
datetime.now().minute
datetime.now().second
流程控制
- 邏輯運算符
=
等于
!=
不等于
<
小于
<=
小于等于
>
大于
>=
大于等于
==
兩個變量之間比較是否相同(內存地址值比較)
and
與
or
或
not
非
if...elif...else...結構
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
函數 Function
函數定義格式
def hello_world():
"""Prints 'Hello World!' to the console."""
print "Hello World!"
def power(base, exponent):
result = base**exponent
print("%d to the power of %d is %d." % (base, exponent, result))
power(37, 4)
匿名函數 lambda
sum = lambda arg1, arg2: arg1 + arg2;
定義一個sum函數
filter() 函數用于過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
該接收兩個參數,第一個為函數,第二個為序列,序列的每個元素作為參數傳遞給函數進行判斷,然后返回 True 或 False,最后將返回 True 的元素放到新列表中。
導入模塊
import math
print(math.sqrt(25))
from math import sqrt
# from math import *
print(sqrt(25))
查看模塊下的函數
import math
print(dir(math))
max() 返回序列中的最大值
max(1, 2, 3)
min() 返回序列中的最小值
min(1, 2, 3)
abs() 返回絕對值
abs(-1)
type() 返回變量類型
type('abc')
range() 返回一個范圍的數值序列
from random import randint
randint(0, 10) #產生一個范圍內的隨機整數
列表和字典 Lists and Dictionaries
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"]
定義一個列表,列表下標從0開始
修改列表
zoo_animals[2] = "hyena"
append() 添加元素到列表
len() 計算列表元素個數
index() 返回尋找的元素下標
insert() 在index位置插入一個元素
sort() 列表中的元素進行排序
pop() 從列表中刪除元素,依據下標進行
remove() 從列表中刪除元素,依據元素進行
del() 從列表中刪除元素
join() 拼接列表元素
sorted([5, 2, 3, 1, 4])
列表切片
zoo_animals[1:5]
選取列表中的下標為1到4的元素
my_list = range(1, 11)
my_list[::2]
以步長為2遍歷列表元素
my_list = range(1, 11)
my_list[::-1]
逆序排序列表元素
字符串是特殊的列表
遍歷列表
for animal in animals:
print(animal)
列表推導式
[i for i in range(51) if i % 2 == 0]
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106}
定義一個字典
items() 以列表返回可遍歷的(鍵, 值) 元組數組
dict.items()
keys() 以列表返回一個字典所有的鍵
dict.keys()
values() 以列表返回字典中的所有值
dict.values()
取出字典元素
residents['Puffin']
添加元素到字典
residents['Jason'] = 100
更改字典元素
residents['Puffin'] = 114
刪除字典元素
del residents['Jason']
- remove() 刪除字典元素
循環 Loops
- while循環
打印1到10的平方數
num = 1
while num <= 10:
print(num ** 2)
num += 1
while循環中可以添加else塊
- break 關鍵字
跳出循環
count = 0
while count < 3:
num = random.randint(1, 6)
print num
if num == 5:
print "Sorry, you lose!"
break
count += 1
else:
print "You win!"
- for 循環
for i in range(20):
print i
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape']
print 'You have...'
for f in fruits:
if f == 'tomato':
print 'A tomato is not a fruit!' # (It actually is.)
print 'A', f
else:
print 'A fine selection of fruits!'
- zip() 用于將可迭代的對象作為參數,將對象中對應的元素打包成一個個元組,然后返回由這些元組組成的列表。
如果各個迭代器的元素個數不一致,則返回列表長度與最短的對象相同,利用*號操作符,可以將元組解壓為列表。
list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
for a, b in zip(list_a, list_b):
if a > b:
print(a)
else:
print(b)
- 遞歸
def factorial(x):
if x == 0:
return 1
return factorial(x - 1) * x
* 計算素數
```python
def is_prime(x):
if x <= 1:
return False
if x == 2:
return True
if x % 2 == 0:
return False
n = 3
while n * n <= x:
if x % n == 0:
return False
n += 2
return True
- 字符串逆序
def reverse(text):
result = ""
i = len(text) - 1
while i >= 0:
result = result + text[i]
i -= 1
return result
reverse('Python')
位操作 Bitwise Operators
print(5 >> 4) # 0101 --> 0000,結果為0
print(5 << 1) # 0101 --> 1010,結果為10
print(8 & 5) # 1000 & 0101,結果為0
print(9 | 4) # 1001 | 0100,結果為13
print(12 ^ 42) # 001100 ^ 101010,結果為38(100110)
print(~88) # 1011000 --> 0100111,結果為-89
print(0b1) # 1
print(0b10) # 2
print(0b11) # 3
print(0b100) # 4
print(0b101) # 5
print(0b110) # 6
print(0b111) # 7
print(0b1 + 0b11)
print(0b11 * 0b11)
bin() 函數 返回一個整數int或者長整數long int的二進制表示
int() 函數 將一個二進制數轉化為十進制
int("11001001", 2)
掩碼
def check_bit4(input):
mask = 0b1000
desired = input & mask
if desired > 0:
return 'on'
else:
return 'off'
def flip_bit(number, n):
mask = (0b1 << n - 1)
result = number ^ mask
return bin(result)
類 Clsaaes
定義一個類
# 定義一個類
class Animal(object):
"""Makes cute animals."""
health = "good"# 全局變量
# 初始化對象
def __init__(self, name, age, is_hungry):# self參數指代object,即對象本身
self.name = name
self.age = age
self.is_hungry = is_hungry
zebra = Animal("Jeffrey", 2, True)#建立一個Animal類對象
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)
print(zebra.name, zebra.age, zebra.is_hungry)
print(giraffe.name, giraffe.age, giraffe.is_hungry)
print(panda.name, panda.age, panda.is_hungry)
- 全局變量 global variables
作用于全部類對象
- 局部變量/實例變量 member variables
作用于某些類對象
- 定義類方法和調用方法
class Animal(object):
"""Makes cute animals."""
is_alive = True
def __init__(self, name, age):
self.name = name
self.age = age
# Add your method here!
def description(self):
print(self.name)
print(self.age)
hippo = Animal("hippo", 12)
hippo.description()
- 繼承 Inheritance
Triangle類繼承子Shape類
class Shape(object):
"""Makes shapes!"""
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides
class Triangle(Shape):
def __init__(self, side1, side2, side3):
self.side1 = side1
self.side2 = side2
self.side3 = side3
* 復寫 override
PartTimeEmployee類繼承自Employee類,但是創建PartTimeEmployee對象的時候,因為PartTimeEmployee中有與Employee類同名的方法,此時只使用PartTimeEmployee的同名方法。
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
* super()函數 用于調用下一個父類(超類)并返回該父類實例的方法【python2和python3之間存在差異,此處為python3的】
#父類
Class Parent():
def __init__(self,attribute):
#子類
Class Child(Parent):
def __init__(self,attribute):
super().__init__(attribute)
* __repr__()函數 用于格式化表示對象
class Point3D(object):
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point.__repr__()
文件輸入/輸出 File Input/Output
* open()函數 打開文件
f = open("output.txt", "w") # 以write模式寫文件
my_file = open('output.txt', 'r+') # 以read和write模式處理文件
* write()函數 寫入文件 close()函數 關閉文件
my_list = [i**2 for i in range(1,11)]
my_file = open("output.txt", "r+")
for i in my_list:
my_file.write(str(i))
my_file.write('\n')
my_file.close()
* read() 函數 讀取文件
my_file = open('output.txt', 'r+')
print(my_file.read())
my_file.close()
* readline() 函數 讀取文件的一行
my_file = open('text.txt', 'r')
print(my_file.readline())
my_file.close()
* with...as... 關鍵字 流式處理文件,自動關閉文件流,不需要引用close()函數關閉文件
with open("text.txt", "w") as textfile:
textfile.write("Success!")
* closed 函數 確定文件操作是否關閉
my_file = open('text.txt', 'w')
if my_file.closed:
print(my_file.closed)
else:
my_file.close()
print(my_file.closed)