Python:从初学者到专业人士(第 3 部分)

WBOY
发布: 2024-07-19 19:59:11
原创
497 人浏览过

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中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板