注: 本文的大部分代碼示例來自書籍《Python程式設計:從入門到實踐》。
一、變量:
命名:
(1)變量名隻能包含字母、數字和下劃線。變量名可以字母或下劃線打頭,但不能以數字打頭
(2)變量名不能包含空格,但可使用下劃線來分隔其中的單詞。
(3)不要将Python關鍵字和函數名用作變量名,即不要使用Python保留用于特殊用途的單詞,如print
頭檔案聲明: #-- coding: utf-8 --
二、資料類型:
(1)數字(Number):num = 123
(2)布爾型:True 、 False
(3)字元型(char):
str = 'hello'
str[1]:取第2個字元
str[1:-1:2]: 開始位置,結束位置(-1表示最後),步長.
len(str)
str.title():首字母大寫
str.rstrip() lstrip() strip():處理空白字元串
str(numer): 轉化成字元型
(4)清單(list):list = ['huwentao','xiaozhou','tengjiang','mayan']
list.append()
list.insert(0, '')
del list[0]
list.pop()
list.remove():根據值來删除
list.sort()
(5)元組(tuple):不可修改 tuple = ('huwentao','xiaozhou','tengjiang','mayan')
(6)字典(dict):
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
❶ for key, value in user_0.items():
❷ print("\nKey: " + key)
❸ print("Value: " + value)
三、語句
(1)if語句:
age = 12
❶ if age < 4:
print("Your admission cost is $0.")
❷ elif age < 18:
print("Your admission cost is $5.")
❸ else:
print("Your admission cost is $10.")
(2)for循環
(3)while循環
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1
for循環是一種周遊清單的有效方式,但在for循環中不應修改清單,否則将導緻Python難以跟蹤其中的元素。要在周遊清單的同時對其進行修改,可使用while循環。通過将while循環同清單和字典結合起來使用,可收集、存儲并組織大量輸入,供以後檢視和顯示。
四、使用者輸入
函數input()讓程式暫停運作,等待使用者輸入一些文本。擷取使用者輸入後,Python将其存儲在一個變量中,以友善你使用。
message = input("Tell me something, and I will repeat it back to you: ")
print(message)
五、函數
基本函數的定義:
def greet_user(username):
"""顯示簡單的問候語"""
print("Hello, " + username.title() + "!")
greet_user('jesse')
使用預設值:
def describe_pet(pet_name, animal_type='dog'):
"""顯示寵物的資訊"""
print("\nI have a " + animal_type + ".")
print("My " + animal_type + "'s name is " + pet_name.title() + ".")
describe_pet(pet_name='willie')
傳遞任意數量的形參
def make_pizza(*toppings):
"""列印顧客點的所有配料"""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')
六、類
基礎類的定義:
class Car():
"""一次模拟汽車的簡單嘗試"""
❶ def __init__(self, make, model, year):
"""初始化描述汽車的屬性"""
self.make = make
self.model = model
self.year = year
❷ def get_descriptive_name(self):
"""傳回整潔的描述性資訊"""
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
❸ my_new_car = Car('audi', 'a4', 2016)
print(my_new_car.get_descriptive_name())
類的繼承:
class Car():
"""一次模拟汽車的簡單嘗試"""
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
long_name = str(self.year) + ' ' + self.make + ' ' + self.model
return long_name.title()
def read_odometer(self):
print("This car has " + str(self.odometer_reading) + " miles on it.")
def update_odometer(self, mileage):
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
self.odometer_reading += miles
❷ class ElectricCar(Car):
"""電動汽車的獨特之處"""
❸ def __init__(self, make, model, year):
"""初始化父類的屬性"""
❹ super().__init__(make, model, year)
❺ my_tesla = ElectricCar('tesla', 'model s
可以将執行個體作為屬性來定義一個類
class Car():
--snip--
❶ class Battery():
"""一次模拟電動汽車電瓶的簡單嘗試"""
❷ def __init__(self, battery_size=70):
"""初始化電瓶的屬性"""
self.battery_size = battery_size
❸ def describe_battery(self):
"""列印一條描述電瓶容量的消息"""
print("This car has a " + str(self.battery_size) + "-kWh battery.")
class ElectricCar(Car):
"""電動汽車的獨特之處"""
def __init__(self, make, model, year):
"""
初始化父類的屬性,再初始化電動汽車特有的屬性
"""
super().__init__(make, model, year)
❹ self.battery = Battery()
my_tesla = ElectricCar('tesla', 'model s', 2016)
print(my_tesla.get_descriptive_name())
my_tesla.battery.describe_battery()