如果您是 Python 新手,了解基本操作、数据类型和条件逻辑至关重要。让我们回顾一下一些基本主题。我们将通过示例探讨每个主题。
Python提供了多种运算符,可以轻松执行数学运算。以下是最常见运算符的快速概述:
Syntax | Action | Example | Output |
---|---|---|---|
* | Multiply | 4 * 10 | 40 |
Addition | 7 9 | 16 | |
- | Subtract | 23 - 4 | 19 |
/ | Division | 27 / 3 | 9 |
** | Power | 3 ** 2 | 9 |
% | Modulo | 7 % 4 | 3 |
这些运算符可帮助您处理代码中的数字。以下是一些示例:
# Multiplication result = 4 * 10 print(result) # Output: 40 # Addition total = 7 + 9 print(total) # Output: 16 # Power squared = 3 ** 2 print(squared) # Output: 9
您还可以使用这些运算符为变量赋值:
# Define total spend amount total_spend = 3150.96 print(total_spend) # Output: 3150.96
在 Python 中,您有多种存储数据的方法,每种方法都适合不同类型的任务。
字符串:用于文本。您可以使用单引号或双引号定义字符串。
# Defining a string customer_name = 'George Boorman' print(customer_name) # Double quotes also work customer_name = "George Boorman"
列表:列表是可以包含多个值的有序集合。
# Creating a list prices = [10, 20, 30, 15, 25, 35] # Accessing the first item print(prices[0]) # Output: 10
字典:字典存储键值对,允许您根据键查找值。
# Creating a dictionary products_dict = { "AG32": 10, "HT91": 20, "PL65": 30, "OS31": 15, "KB07": 25, "TR48": 35 } # Accessing a value by key print(products_dict["AG32"]) # Output: 10
集合和元组:
# Creating a set prices_set = {10, 20, 30, 15, 25, 35} # Creating a tuple prices_tuple = (10, 20, 30, 15, 25, 35)
Python 包含几个用于评估条件的关键字,这对于代码中的决策至关重要。
Keyword | Function |
---|---|
and | Evaluate if multiple conditions are true |
or | Evaluate if one or more conditions are true |
in | Check if a value exists in a data structure |
not | Evaluate if a value is not in a data structure |
让我们看一些示例来了解这些关键字的实际作用:
# Multiplication result = 4 * 10 print(result) # Output: 40 # Addition total = 7 + 9 print(total) # Output: 16 # Power squared = 3 ** 2 print(squared) # Output: 9
# Define total spend amount total_spend = 3150.96 print(total_spend) # Output: 3150.96
# Defining a string customer_name = 'George Boorman' print(customer_name) # Double quotes also work customer_name = "George Boorman"
# Creating a list prices = [10, 20, 30, 15, 25, 35] # Accessing the first item print(prices[0]) # Output: 10
本概述涵盖了 Python 中算术运算、各种数据类型和条件关键字的基础知识。这些基本概念将帮助您构建更复杂的程序。
以上是Python:算术、数据类型和条件逻辑的基本概念的详细内容。更多信息请关注PHP中文网其他相关文章!