如果您是 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中文網其他相關文章!