函數是執行特定任務的可重複使用程式碼區塊。它們有助於組織您的程式碼,使其更具可讀性並減少重複。舉個例子,編寫的程式碼可能會變得很長,很難閱讀或找到每一行的作用,尤其是當您必須呼叫 value 時。
def greet(name):
想像一下您正在烹調一頓複雜的餐點。您不必嘗試一次完成所有事情,而是將流程分解為更小的任務:切蔬菜、準備醬汁、烹飪主菜等。這些任務中的每一個都可以被視為程式設計中的一個函數。
每一個都放入一個可以在我們需要時調用的部分,而不必用所有程式碼堵塞整頓飯,使我們的程式碼更易於閱讀並減少錯誤。
函數使我們能夠:
現實生活中的例子:
現在,讓我們看看如何建立和定義函數:
def greet(name): """ This function takes a name and returns a greeting message. """ return f"Hello, {name}! Welcome to Python programming."
分解
縮排區塊是函數體 - 函數的作用。
return specifies what the function gives back when it's done
使用(呼叫)函數
# Calling the function message = greet("Alex") print(message) greet("Alex"):
函數內部發生了什麼事:
因此它創建了一條訊息:「你好,Alex!歡迎來到 Python 程式設計。」
訊息 = ...:
我們將函數傳回的內容儲存在名為「message」的變數中。
現在「訊息」包含文字「你好,Alex!歡迎來到 Python 程式設計。」
列印(訊息):
這只是在螢幕上顯示「訊息」的內容。
「這將會輸出:『你好,Alex!歡迎來到 Python 程式設計。 ”
在這裡,「Alex」是一個參數 - 我們傳遞給函數的實際資料。
更複雜的範例:
讓我們建立一個函數來計算購物車中商品的總成本:
def calculate_total(items, tax_rate): subtotal = sum(items) tax = subtotal * tax_rate total = subtotal + tax return total # Using the function cart = [10.99, 5.50, 8.99] tax = 0.08 # 8% tax total_cost = calculate_total(cart, tax) print(f"Your total including tax is: ${total_cost:.2f}")
在這個例子中,我探索了多個參數,我將 items 和tax_rate 作為參數放置在我們的函數中,並為我們的函數提供了一些明確的參數。
subtotal = sum(items) - subtotal 是它計算的值的變數或占位符,即總和(記住sum 是Python 中的一個函式庫,它會傳回「起始」值的總和(默認: 0) 加上一個可迭代的數字) 的項目。
tax = subtotal *tax_rate 這裡,我們將tax作為一個新變量,在該變量中,我們說取之前的變量subtotal(sum(items)) *tax_rate,它是任何的佔位符用戶輸入的數字。
總計=小計+稅;這是兩個變數(小計和稅)的總和。
一旦我們呼叫函數calculate_total(cart,tax),購物車就會將購物車中的所有值相加(10.99+5.50+8.99),然後我們將這個值乘以0.08得到稅金,然後將它們相相加得到總數。
我們的列印語句使用格式化字串,然後我們說total_cost應該減少到小數點後2f位元。
注意要點
Practice Exercise:
Try creating a function that takes a person's name and age, and returns a message like "Hello [name], you will be [age+10] in 10 years." This will help you practice using multiple parameters and doing calculations within a function.
Python offers several built-in data structures that allow programmers to organize and manipulate data efficiently. we'll explore four essential data structures: lists, sets, tuples, and dictionaries. Each of these structures has unique characteristics and use cases.
Lists
Lists are the most commonly used data structure in Python. They are ordered, mutable collections that can contain elements of different data types. You can create a list using square brackets:
fruits = ["apple", "banana", "cherry"]
Lists maintain the order of elements, allowing you to access them by their index. For example, fruits[0] would return "apple". This ordering makes lists ideal for situations where the sequence of elements matters, such as maintaining a playlist or a to-do list.
One of the key advantages of lists is their mutability. You can easily add, remove, or modify elements:
fruits.append("date") # Adds "date" to the end fruits[1] = "blueberry" # Replaces "banana" with "blueberry"
Lists also support various operations like slicing, concatenation, and list comprehensions, making them extremely versatile. Use lists when you need an ordered collection that you can modify and when you want to allow duplicate elements.
To learn more about lists, check this guide by Bala Priya C (Lists in Python – A Comprehensive Guide)
Sets
Sets are unordered collections of unique elements. You can create a set using curly braces or the set() function.
unique_numbers = {1, 2, 3, 4, 5}
The defining feature of sets is that they only store unique elements. If you try to add a duplicate element, it will be ignored. This makes sets perfect for removing duplicates from a list or for membership testing.
Sets also support mathematical set operations like union, intersection, and difference:
set1 = {1, 2, 3} set2 = {3, 4, 5} print(set1.union(set2)) # {1, 2, 3, 4, 5}
While sets are mutable (you can add or remove elements), they must be immutable. Use sets when you need to ensure uniqueness of elements and don't care about their order.
To learn more about sets, check this guide on w3school
Tuples
Tuples are similar to lists in that they are ordered sequences, but they are immutable – once created, they cannot be modified. You create a tuple using parentheses:
coordinates = (10, 20)
The immutability of tuples makes them useful for representing fixed collections of items, like the x and y coordinates in our example. They're also commonly used to return multiple values from a function.
def get_user_info(): return ("Alice", 30, "New York") name, age, city = get_user_info()
Tuples can be used as dictionary keys (unlike lists) because of their immutability. Use tuples when you have a collection of related items that shouldn't change throughout your program's execution.
If you need more insight on tuples, Geeksforgeeks has a very informative guide on it
Dictionaries: Key-Value Pairs
Dictionaries are unordered collections of key-value pairs. They provide a way to associate related information. You create a dictionary using curly braces with key-value pairs:
person = {"name": "Alex", "age": 25, "city": "San Francisco"}
Dictionaries allow fast lookup of values based on their keys. You can access, add, or modify values using their associated keys:
print(person["name"]) # Prints "Alex" person["job"] = "Engineer" # Adds a new key-value pair
Dictionaries are incredibly useful for representing structured data, similar to JSON. They're also great for counting occurrences of items or creating mappings between related pieces of information.
I love what Simplilearn did with this guide on dictionary; find it here.
When deciding which data structure to use, consider these factors:
了解這些資料結構以及何時以及如何使用它們將幫助您編寫更有效率、更易讀的程式碼。隨著經驗的積累,您將直觀地了解哪種結構最適合您的特定需求。
請記住,Python 的靈活性可讓您在需要時在這些結構之間進行轉換。例如,您可以將清單轉換為集合以刪除重複項,然後如果需要保持順序,則將其轉換回清單。這種互通性使得這些資料結構在組合使用時變得更加強大。
我們如何做到這一點?找出並將其發佈到我們的 Python 學習小組的評論部分。
透過掌握清單、集合、元組和字典,您將為在 Python 中處理各種資料操作任務奠定堅實的基礎。隨著您在程式設計之旅中取得進展,您會發現更專業的資料結構,但這四種結構仍將是您的 Python 程式設計工具包中的基本工具。
以上是Python:從初學者到專業人士(第 3 部分)的詳細內容。更多資訊請關注PHP中文網其他相關文章!