首頁  >  文章  >  後端開發  >  Python:從初學者到專業人士(第 3 部分)

Python:從初學者到專業人士(第 3 部分)

WBOY
WBOY原創
2024-07-19 19:59:11468瀏覽

Python 中的函數

函數是執行特定任務的可重複使用程式碼區塊。它們有助於組織您的程式碼,使其更具可讀性並減少重複。舉個例子,編寫的程式碼可能會變得很長,很難閱讀或找到每一行的作用,尤其是當您必須呼叫 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."

分解

  • def 告訴 Python 我們正在定義一個函數。
  • 問候是函數名稱(您可以將名稱更改為您想要的任何名稱!)
  • (Alex) 是參數 - 函數將接收的資料的佔位符

縮排區塊是函數體 - 函數的作用。

return specifies what the function gives back when it's done

使用(呼叫)函數

# Calling the function
message = greet("Alex")
print(message)


greet("Alex"):
  • 這是我們「呼叫」或「使用」該函數。
  • 我們說,「嘿,名為「greet」的函數,請以「Alex」作為輸入。」
  • 「Alex」是論點。這就像為函數提供了一條可以使用的特定資訊。

函數內部發生了什麼事:

  • 函數採用「Alex」並將其放在問候語中 {name} 的位置。
  • 因此它創建了一條訊息:「你好,Alex!歡迎來到 Python 程式設計。」

    訊息 = ...:

  • 我們將函數傳回的內容儲存在名為「message」的變數中。

  • 現在「訊息」包含文字「你好,Alex!歡迎來到 Python 程式設計。」

    列印(訊息):

  • 這只是在螢幕上顯示「訊息」的內容。

Python: From Beginners to Pro (Part 3)

「這將會輸出:『你好,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位元。

注意要點

  • Function Names: Use clear, descriptive names. calculate_total is better than calc or function1.
  • Parameters: These are the inputs your function expects. In calculate_total, we have two: items and tax_rate.
  • Return Statement: This specifies what the function gives back. Not all functions need to return something, but many do.
  • Indentation: Everything inside the function must be indented. This is how Python knows what's part of the function.
  • Calling the Function: We use the function name followed by parentheses containing the arguments.

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 Data Structures: Lists, Sets, Tuples, and Dictionaries

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.

Choosing the Right Data Structure

When deciding which data structure to use, consider these factors:

  • 需要維持秩序嗎?如果是,請考慮清單或元組。
  • 需要修改集合嗎?如果是,請使用清單或字典。
  • 需要確保唯一性嗎?如果是,請使用集合。
  • 你需要將值與鍵關聯起來嗎?如果是,請使用字典。
  • 你需要一個不可變的序列嗎?如果是,請使用元組。

了解這些資料結構以及何時以及如何使用它們將幫助您編寫更有效率、更易讀的程式碼。隨著經驗的積累,您將直觀地了解哪種結構最適合您的特定需求。

請記住,Python 的靈活性可讓您在需要時在這些結構之間進行轉換。例如,您可以將清單轉換為集合以刪除重複項,然後如果需要保持順序,則將其轉換回清單。這種互通性使得這些資料結構在組合使用時變得更加強大。

我們如何做到這一點?找出並將其發佈到我們的 Python 學習小組的評論部分。

透過掌握清單、集合、元組和字典,您將為在 Python 中處理各種資料操作任務奠定堅實的基礎。隨著您在程式設計之旅中取得進展,您會發現更專業的資料結構,但這四種結構仍將是您的 Python 程式設計工具包中的基本工具。

以上是Python:從初學者到專業人士(第 3 部分)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn