第一個(gè)Python程序
print('Hello World!')
變量 Variables
my_variable = 10
布爾值 Booleans
my_int = 7
my_float = 1.23
my_bool = True
格式
在Python中利用空格控制縮進(jìn)來達(dá)到代碼分塊的效果(諸如Java中利用'{}'來進(jìn)行代碼分塊),這是很重要的。
一般使用4個(gè)空格來進(jìn)行換行的縮進(jìn)。
Python使用#進(jìn)行單行注釋。
# 這是一段注釋
mysterious_variable = 42
使用如下結(jié)果進(jìn)行多行注釋
'''
這是一段注釋。
'''
數(shù)學(xué)計(jì)算
Python實(shí)現(xiàn)數(shù)值計(jì)算的方式很簡單,跟MATLAB很像。
addition = 72 + 23
subtraction = 108 - 204
multiplication = 108 * 0.5
division = 108 / 9
eight = 2 ** 3 #冪計(jì)算
modulo = 3 % 2 #取模計(jì)算
字符串 String
Python利用兩個(gè)雙引號(hào)"",或者兩個(gè)單引號(hào)''包裹字符串
caesar = "Graham"
praline = "John"
viking = "Teresa"
在Python中利用空格控制縮進(jìn)來達(dá)到代碼分塊的效果(諸如Java中利用中,如果字符串中有',",\等,需要在它們面前增加\進(jìn)行轉(zhuǎn)義,此時(shí)字符串才能正常解釋。
選取字符串中的某個(gè)字符,只需要傳入相應(yīng)字符的下標(biāo)即可。Python中的下標(biāo)從0開始
fifth_letter = "MONTY"[4] #取出字母Y
常見的字符串函數(shù)
len() 返回字符串長度
len(string)lower() 返回小寫的字符串
string.lower()upper() 返回大寫的字符串
string.upper()str() 將非字符串類型轉(zhuǎn)化為字符串類型
str(2)isalpha() 判斷字符串是否只由字母組成
string.isalpha()
字符串拼接
Python中利用+進(jìn)行多個(gè)字符串之間的拼接;非字符串類型需要轉(zhuǎn)化為字符串類型之后才能進(jìn)行拼接。
print "The value of pi is around " + str(3.14)
字符串切片
new_word = new_word[1:len(new_word)]
打印 Print
在python3+中,利用print()進(jìn)行打印信息。
print("Hello World!")
在打印字符串的時(shí)候,字符串后面跟著一個(gè),后打印結(jié)果會(huì)輸出一個(gè)空格。
格式化輸出
string_1 = "Camelot"
string_2 = "place"
print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)
日期和時(shí)間 Date and Time
- 導(dǎo)入日期時(shí)間庫
from datetime import datetime
- 打印當(dāng)前時(shí)間
print(datetime.now())
- 獲取日期的年、月、日
datetime.now().year
datetime.now().month
datetime.now().day
- 獲取時(shí)間的時(shí)、分、秒
datetime.now().hour
datetime.now().minute
datetime.now().second
流程控制
- 邏輯運(yùn)算符
= 等于
!= 不等于
< 小于
<= 小于等于
> 大于
>= 大于等于
== 兩個(gè)變量之間比較是否相同(內(nèi)存地址值比較)
and 與
or 或
not 非
if...elif...else...結(jié)構(gòu)
def greater_less_equal_5(answer):
if answer > 5:
return 1
elif answer < 5:
return -1
else:
return 0
函數(shù) Function
函數(shù)定義格式
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)
匿名函數(shù) lambda
sum = lambda arg1, arg2: arg1 + arg2; 定義一個(gè)sum函數(shù)
filter() 函數(shù)用于過濾序列,過濾掉不符合條件的元素,返回由符合條件元素組成的新列表。
該接收兩個(gè)參數(shù),第一個(gè)為函數(shù),第二個(gè)為序列,序列的每個(gè)元素作為參數(shù)傳遞給函數(shù)進(jìn)行判斷,然后返回 True 或 False,最后將返回 True 的元素放到新列表中。
導(dǎo)入模塊
import math
print(math.sqrt(25))
from math import sqrt
# from math import *
print(sqrt(25))
查看模塊下的函數(shù)
import math
print(dir(math))
max() 返回序列中的最大值
max(1, 2, 3)min() 返回序列中的最小值
min(1, 2, 3)abs() 返回絕對值
abs(-1)type() 返回變量類型
type('abc')range() 返回一個(gè)范圍的數(shù)值序列
from random import randint
randint(0, 10) #產(chǎn)生一個(gè)范圍內(nèi)的隨機(jī)整數(shù)
列表和字典 Lists and Dictionaries
zoo_animals = ["pangolin", "cassowary", "sloth", "tiger"] 定義一個(gè)列表,列表下標(biāo)從0開始
修改列表
zoo_animals[2] = "hyena"
append() 添加元素到列表
len() 計(jì)算列表元素個(gè)數(shù)
index() 返回尋找的元素下標(biāo)
insert() 在index位置插入一個(gè)元素
sort() 列表中的元素進(jìn)行排序
pop() 從列表中刪除元素,依據(jù)下標(biāo)進(jìn)行
remove() 從列表中刪除元素,依據(jù)元素進(jìn)行
del() 從列表中刪除元素
join() 拼接列表元素
sorted([5, 2, 3, 1, 4])
列表切片
zoo_animals[1:5] 選取列表中的下標(biāo)為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)
列表推導(dǎo)式
[i for i in range(51) if i % 2 == 0]
residents = {'Puffin' : 104, 'Sloth' : 105, 'Burmese Python' : 106} 定義一個(gè)字典
items() 以列表返回可遍歷的(鍵, 值) 元組數(shù)組
dict.items()keys() 以列表返回一個(gè)字典所有的鍵
dict.keys()values() 以列表返回字典中的所有值
dict.values()
取出字典元素
residents['Puffin']
添加元素到字典
residents['Jason'] = 100
更改字典元素
residents['Puffin'] = 114
刪除字典元素
del residents['Jason']
- remove() 刪除字典元素
循環(huán) Loops
- while循環(huán)
打印1到10的平方數(shù)
num = 1
while num <= 10:
print(num ** 2)
num += 1
while循環(huán)中可以添加else塊
- break 關(guān)鍵字
跳出循環(huán)
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 循環(huán)
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() 用于將可迭代的對象作為參數(shù),將對象中對應(yīng)的元素打包成一個(gè)個(gè)元組,然后返回由這些元組組成的列表。
如果各個(gè)迭代器的元素個(gè)數(shù)不一致,則返回列表長度與最短的對象相同,利用*號(hào)操作符,可以將元組解壓為列表。
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
* 計(jì)算素?cái)?shù)
```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,結(jié)果為0
print(5 << 1) # 0101 --> 1010,結(jié)果為10
print(8 & 5) # 1000 & 0101,結(jié)果為0
print(9 | 4) # 1001 | 0100,結(jié)果為13
print(12 ^ 42) # 001100 ^ 101010,結(jié)果為38(100110)
print(~88) # 1011000 --> 0100111,結(jié)果為-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() 函數(shù) 返回一個(gè)整數(shù)int或者長整數(shù)long int的二進(jìn)制表示
int() 函數(shù) 將一個(gè)二進(jìn)制數(shù)轉(zhuǎn)化為十進(jìn)制
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
定義一個(gè)類
# 定義一個(gè)類
class Animal(object):
"""Makes cute animals."""
health = "good"# 全局變量
# 初始化對象
def __init__(self, name, age, is_hungry):# self參數(shù)指代object,即對象本身
self.name = name
self.age = age
self.is_hungry = is_hungry
zebra = Animal("Jeffrey", 2, True)#建立一個(gè)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
作用于全部類對象
- 局部變量/實(shí)例變量 member variables
作用于某些類對象
- 定義類方法和調(diào)用方法
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
* 復(fù)寫 override
PartTimeEmployee類繼承自Employee類,但是創(chuàng)建PartTimeEmployee對象的時(shí)候,因?yàn)镻artTimeEmployee中有與Employee類同名的方法,此時(shí)只使用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()函數(shù) 用于調(diào)用下一個(gè)父類(超類)并返回該父類實(shí)例的方法【python2和python3之間存在差異,此處為python3的】
#父類
Class Parent():
def __init__(self,attribute):
#子類
Class Child(Parent):
def __init__(self,attribute):
super().__init__(attribute)
* __repr__()函數(shù) 用于格式化表示對象
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()函數(shù) 打開文件
f = open("output.txt", "w") # 以write模式寫文件
my_file = open('output.txt', 'r+') # 以read和write模式處理文件
* write()函數(shù) 寫入文件 close()函數(shù) 關(guān)閉文件
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() 函數(shù) 讀取文件
my_file = open('output.txt', 'r+')
print(my_file.read())
my_file.close()
* readline() 函數(shù) 讀取文件的一行
my_file = open('text.txt', 'r')
print(my_file.readline())
my_file.close()
* with...as... 關(guān)鍵字 流式處理文件,自動(dòng)關(guān)閉文件流,不需要引用close()函數(shù)關(guān)閉文件
with open("text.txt", "w") as textfile:
textfile.write("Success!")
* closed 函數(shù) 確定文件操作是否關(guān)閉
my_file = open('text.txt', 'w')
if my_file.closed:
print(my_file.closed)
else:
my_file.close()
print(my_file.closed)