Python速查表



這份Python速查表對學生和開發者快速學習Python程式設計很有幫助。

列印Hello World

列印“Hello, World!”是一個基本程式。要列印“Hello, World”,請使用print()函式。這是一個基本的Python程式:

print("Hello, World!")  # Output: Hello, World!

列印輸出

**print()函式**也可以用來列印輸出,即變數的值到螢幕上。

name = "Kelly Hu"
print("Hi my name is: ", name)

要列印多個變數,可以使用以下print()函式的級聯形式:

name = "Kelly Hu"
age = 27
city = "Brentwood"
print("I am", name, ". I'm", age, "years old and lives in", city)

不換行列印

print()方法在列印結果後會插入一個換行符。要實現不換行列印,請在print()方法中使用end=' '引數作為最後一個引數。

print("Hello", end=" ")
print("World")

您可以為**end**引數指定任何值;新分配的值將在結果之後列印。

print("Hello", end="####")
print("World")

註釋

Python提供了三種類型的註釋

  • 單行註釋
  • 多行註釋
  • 文件字串註釋

1. 單行註釋

單行註釋後面跟著井號(#)。

# This is single-line comment

2. 多行註釋

多行註釋寫在三個單引號(''' )之間。在'''和'''之間編寫的任何內容都表示多行註釋。

'''
name = "Kelly Hu"
age = 30
city = "Brentwood"
'''

print("Hello, World!")

變數

Python變數是在您為其賦值時建立的。Python中沒有用於宣告變數的關鍵字。

name = "Kelly Hu"
age = 27
print(name)
print(age)

指定變數的資料型別

可以使用型別轉換(藉助於str()、int()、float()等內建函式)來指定變數的資料型別。

a = str(123)
b = int(123)
c = float(123)
# Printing type
print(type(a))
print(type(b))
print(type(c))

列印變數/物件的型別

type()函式可用於列印變數或物件的資料型別(物件型別)。

name = "Kelly Hu"
print(name, "is the type of", type(name))

變數名

變數名(或識別符號)必須以字母或下劃線字元開頭,並且僅允許字母數字字元和下劃線作為變數名。

一些有效的變數名:**name**、**_name**、**my_name**、**name2**、**MY_NAME**

為變數賦值多個值

可以透過逗號分隔變數名和值來為變數賦值多個值。

name, age, city = "Kelly Hu", 27, "Brentwood"
print(name)
print(age)
print(city)

資料型別

以下是Python資料型別

1. 文字型別:字串 (str)

text = "Hello, World!"

2. 數值型別

int

num_int = 10

float

num_float = 10.5

complex

num_complex = 2 + 3j

3. 序列型別

list

my_list = [1, 2, 3]

tuple

my_tuple = (1, 2, 3)

range

my_range = range(1, 10)

4. 對映型別:字典 (dict)

my_dict = {"name": "Kelly Hu", "age": 27}

5. 集合型別

set

my_set = {1, 2, 3}

frozenset

my_frozenset = frozenset([1, 2, 3])

6. 布林型別:bool

my_bool = True

7. 二進位制型別

bytes

my_bytes = b"Hello"

bytearray

my_bytearray = bytearray(5)

memoryview

my_memoryview = memoryview(b"Hello")

8. None型別:NoneType

my_none = None

運算子

Python運算子用於對運算元執行各種運算,例如算術運算、邏輯運算等。

算術運算子

Python算術運算子包括+(加法)、-(減法)、*(乘法)、/(除法)、//(地板除)、%(取模)和**(指數) 。

賦值運算子

Python賦值運算子用於將值賦給變數,包括=、+=、-=、*=、/=、%=、**=、//=、&=、|=、^=、>>=和<<=。

比較運算子

Python比較運算子用於比較兩個值,包括==(等於)、!=(不等於)、>(大於)、<(小於)、>=(大於等於)和<=(小於等於)。

邏輯運算子

Python邏輯運算子為**and**、**or**和**not**。

身份運算子

Python身份運算子為**is**和**is not**,用於檢查兩個變數是否引用記憶體中的同一個物件。

成員運算子

Python 成員運算子是 **in** 和 **not in**。這些運算子用於測試某個值是否在一個序列中。

位運算子

Python 位運算子對二進位制值執行運算;這些運算子包括 AND (&)、OR (|)、NOT (~)、XOR (^)、左移 (<<) 和右移 (>>)。

使用者輸入

Python 允許你從使用者那裡獲取不同型別的 輸入。input() 函式用於從使用者獲取字串型別的輸入。你可以使用以下基本方法將輸入轉換為特定型別:

  • int() − 將輸入轉換為整數。
  • float() − 將輸入轉換為浮點數。
  • bool() − 將輸入轉換為布林值。

基本使用者輸入

name = input("Enter your name: ")
print("Hello", name)

整數輸入

age = int(input("Enter your age: "))
print(f"You are {age} years old.")

浮點數輸入

x = float(input("Enter any float value: "))
print(x)

處理無效輸入

你可以使用 try 和 except 來處理無效輸入。

try:
   x = int(input("Input an integer value: "))
   print(x)
except ValueError:
   print("Please enter a valid number.")

條件語句

Python 條件語句 使用 **if**、**elif** 和 **else** 關鍵字編寫。

a = 10
b = 20
if a > b:
   print("a is greater than b")
elif b > a:
   print("b is greater than a")
else:
   print("a is greater than b")

迴圈

有兩種型別的 Python 迴圈for 迴圈while 迴圈

for 迴圈

students = ["Kelly Hu", "Akanksha", "Peter"]
for s in students:
   print(s)

while 迴圈

i = 1
while i <= 10:
   print(i)
   i += 1

字串

Python 字串 是用單引號或雙引號括起來的字元序列。

列印字串

print("I'm Kelly Hu I live in Brentwood")
name, city = "Kelly Hu", "Brentwood"
# Printing string variables
print("I'm", name, "I live in", city)

引號巢狀

你可以使用 print() 函式列印引號作為字串。

print("I'm Kelly Hu")
print("I am 'Kelly Hu'")
print("I am \"Kelly Hu\"")

多行字串

Python 允許將多行字串賦值給變數。只需使用三個單引號或雙引號來表示多行字串即可。

a = """I am Kelly Hu
I lives in Brentwood.
I am 27 years old"""

b = '''I am Kelly Hu
I lives in Brentwood.
I am 27 years old'''

print(a)
print(b)

字串切片

字串切片可以透過使用起始索引和結束索引來完成,這兩個索引之間用冒號分隔,並用方括號括起來。

test = "Hello, World!"
print(test[2:5])
print(test[0:])
print(test[:13])
print(test[:5])

字串連線

你可以使用加號 (+) 運算子連線兩個或多個字串。

name = "Kelly Hu"
city = "Brentwood"

person = name + " " + city
print(person)

字串格式化

字串格式化使用 Python f-string 完成。

name = "Kelly Hu"
age = 27
person = f"My name is {name}, I am {age} years old"
print(person)

字串方法

以下是常用的 字串方法

序號 方法及描述

1

capitalize()

將字串的首字母大寫

2

casefold()

將字串中的所有大寫字母轉換為小寫。類似於 lower(),但也可用於處理 Unicode 字元

3

lower()

將字串中的所有大寫字母轉換為小寫。

4

swapcase()

反轉字串中所有字母的大小寫。

5

title()

返回字串的“標題”版本,即所有單詞以大寫字母開頭,其餘字母為小寫。

6

upper()

將字串中的小寫字母轉換為大寫。

跳脫字元

Python 跳脫字元 是轉義符 (\) 和字元的組合,用於執行特定任務。以下是跳脫字元及其含義:

跳脫字元 描述 示例
\\ 反斜槓 print("This is a backslash: \\")
\' 單引號 print('It\'s a sunny day!')
\" 雙引號 print("He said, \"Hello!\"")
\n 換行符 print("Hello\nWorld")
\r 回車符 print("Hello\rWorld")
\t 水平製表符 print("Hello\tWorld")
\b 退格符 print("Hello\bWorld")
\f 換頁符 print("Hello\fWorld")
\v 垂直製表符 print("Hello\vWorld")
\ooo 八進位制值(用八進位制數表示的字元) print("\101") # 列印 'A'
\xhh 十六進位制值(用十六進位制數表示的字元) print("\x41") # 列印 'A'

列表

Python 列表用於儲存以逗號分隔的值。

建立列表

# Empty list
my_list = []
# List with elements
my_list = [1, 2, 3, 4, 5]

訪問元素

可以使用索引和列表切片來訪問列表的元素。

my_list = [1, 2, 3, 4, 5]
print(my_list[0])
print(my_list[2])
print(my_list[-1])
print(my_list[2:4])

追加和插入元素

可以使用 list.append() 和 list.insert() 方法分別追加和插入列表中的元素。

my_list = [1, 2, 3, 4, 5]
print(my_list)
my_list.append(6)
my_list.insert(0, 0)
print(my_list)

刪除列表元素

remove() 方法用於刪除列表中的元素。

my_list = [1, 2, 3, 4, 5]
print(my_list)
my_list.remove(3)
print(my_list)

複製列表

list.copy() 方法用於將一個列表複製到另一個列表。

my_list = [1, 2, 3, 4, 5]
new_list = my_list.copy()
print(my_list)
print(new_list)

清空列表

list.clear() 方法用於清空列表元素。

my_list.clear()

巢狀列表

Python 巢狀列表指的是列表中的列表。

nested_list = [[1, 2], [3, 4], [5, 6]]
print(nested_list)

元組

Python 元組 用於在一個變數中儲存多個以逗號分隔的值。元組值放在圓括號內。

建立元組

my_tuple = (1, 2, 3)
print(my_tuple)

建立空元組

my_tuple = ()
print(my_tuple)

無括號的元組(隱式元組)

my_tuple = 1, 2, 3
print(my_tuple)

單元素元組

my_tuple = (1,)
print(my_tuple)

訪問元組元素

可以使用索引和元組切片來訪問元組的元素。

my_tuple = (10, 20, 30)
print(my_tuple[0])
print(my_tuple[1])
print(my_tuple[0:])
print(my_tuple[-1])
print(my_tuple[0:2])

元組連線

要連線元組,請使用加號 (+) 運算子。

tuple1 = (10, 20, 30)
tuple2 = (40, 50)
print(tuple1 + tuple2)

元組解包

tuple1 = (10, 20, 30)
a, b, c = tuple1
print(a)
print(b)
print(c)

巢狀元組

nested_tuple = ((10, 20), (30, 40), (50, 60))
print(nested_tuple)

集合

Python 集合 是多個專案的集合,這些專案是無序的、不可更改*的和無索引的。集合值以逗號分隔,並用花括號括起來。

建立集合

set1 = {10, 20, 30, 40, 50}
# Set from a list
set2 = set([10, 20, 30, 40, 50])
print(set1)
print(set2)

新增和刪除元素

以下函式用於向集合中新增和刪除元素:

集合運算示例

set1 = {10, 20, 30, 40, 50}
set1.add(60)
print(set1)
set1.update([70, 80])
print(set1)
set1.remove(30)
print(set1)
set1.discard(10)
print(set1)
print(set1.pop(),"is removed!")
set1.clear()
print(set1)

字典

Python 字典 是鍵值對的集合,並用花括號編寫。

建立字典

my_dict = {'name': 'Kelly Hu', 'age': 27}
print(my_dict)

建立空字典

my_dict = {}
print(my_dict)

建立具有混合鍵的字典

my_dict = {1: 'Kelly', 'hair_color': 'Brown', (36, 24): 'lucky_numbers'}
print(my_dict)

訪問值

你可以透過在方括號內提供用引號括起來的鍵名來直接訪問指定鍵的值,還可以使用 dict.get() 方法 獲取指定鍵的值。

person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'}
# Direct access
print(person['name'])
print(person['age'])
print(person['city'])
# Using method
print(person.get('name'))
print(person.get('age'))
print(person.get('city'))

修改字典

你可以直接更新現有鍵的值,也可以使用 dict.update() 方法 更新多個值。

person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'}
print(person)
# Updating single value
person['age'] = 18
print(person)
# Updating multiple values
person.update({'age': 21, 'city': 'New York'})
print(person)

刪除元素

以下方法可用於從字典中刪除元素:

  • pop() − 刪除鍵值對並返回值。removed_value = person.pop('age')
  • popitem(): 刪除最後新增的項並返回鍵值對。
    removed_value = person.popitem()
  • dict.clear(): 刪除所有項並清空字典。person.clear()

遍歷字典

person = {'name': 'Kelly', 'age': 27, 'city': 'Brentwood'}
# Iterate through keys
for key in person:
   print(key)

# Iterate through values
for value in person.values():
   print(value)

# Iterate through key-value pairs
for key, value in person.items():
   print(f"{key}: {value}")

字典推導式

dict1 = {x: x**2 for x in range(5)}
print(dict1)

Lambda 函式

**Python lambda 函式** 只能有一個表示式。它們是小的匿名函式,可以接受任意數量的引數。

value = lambda x : x * 3
print(value(5))

類和物件

Python 是一種面向物件的程式語言,允許建立類和物件。你可以使用“class”關鍵字在 Python 中建立類。

class Person:
   def __init__(self, name, age):
      self.name = name
      self.age = age

   def display_info(self):
      print(f"Name: {self.name}, Age: {self.age}")

# Create objects
per1 = Person("Kelly Hu", 27)
per2 = Person("Adele", 25)

# Access object attributes
print(per1.name)
print(per1.age)

# Printing using method
per2.display_info()

繼承

Python 繼承 允許你將父類的屬性繼承給子類。

基本繼承示例

# Base class
class Student:
   def __init__(self, name, grade):
      self.name = name
      self.grade = grade

   def get_details(self):
      return f"Student: {self.name}, Grade: {self.grade}"

# Derived class
class Graduate(Student):
   def get_details(self):
      return f"Graduate: {self.name}, Grade: {self.grade}, Status: Graduated"

# Create an instance of the child class
grad = Graduate("Kelly Hu", "B+")

# Access inherited and overridden methods
print(grad.get_details())

使用 super() 方法覆蓋方法

super() 方法 用於呼叫父類(或基類)中的方法。

# Base class
class Student:
   def __init__(self, name, grade):
      self.name = name
      self.grade = grade

   def get_details(self):
      return f"Student: {self.name}, Grade: {self.grade}"

# Derived class
class Graduate(Student):
   def __init__(self, name, grade, graduation_year):
      # Call the parent class's constructor using super()
      super().__init__(name, grade)
      self.graduation_year = graduation_year

   def get_details(self):
      # Call the parent class's get_details() method using super()
      student_details = super().get_details()
      return f"{student_details}, Graduation Year: {self.graduation_year}"

# Create an instance of the child class (Graduate)
grad = Graduate("Kelly Hu", "B+", 2011)

# Access inherited and overridden methods
print(grad.get_details())

異常處理

Python 異常處理允許在程式執行期間處理異常。以下關鍵字(塊)用於異常處理:

  • **try** − 在要測試異常的主程式碼中編寫。
  • **except** − 編寫處理異常的程式碼。
  • **else** − 當沒有錯誤時編寫要執行的程式碼。
  • **finally** − 無論是否有錯誤,都要編寫最終執行的程式碼。
# Create function to divide two numbers
def divide_numbers(a, b):
   try:
      result = a / b
   except ZeroDivisionError:
      print("Error: Cannot divide by zero!")
   else:
      print(f"The divide result is : {result}")
   finally:
      print("Execution complete.")

# Calling function
print("Test Case 1:")
divide_numbers(10, 2)

print("\nTest Case 2:")
divide_numbers(10, 0)
廣告