如果您是 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
集合和元组:
立即学习“Python免费学习笔记(深入)”;
# 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 |
让我们看一些示例来了解这些关键字的实际作用:
age = 25 income = 50000 # check if both conditions are true if age > 20 and income > 30000: print("eligible for loan")
day = "sunday" weather = "sunny" # check if either condition is true if day == "saturday" or weather == "sunny": print("let's go to the park!")
fruits = ["apple", "banana", "cherry"] # check if a value is in the list if "apple" in fruits: print("apple is available.")
vegetables = ["carrot", "potato", "spinach"] # Check if a value is not in the list if "broccoli" not in vegetables: print("Broccoli is not in the list.")
本概述涵盖了 python 中算术运算、各种数据类型和条件关键字的基础知识。这些基本概念将帮助您构建更复杂的程序。
以上就是Python:算术、数据类型和条件逻辑的基本概念的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号