Python:算术、数据类型和条件逻辑的基本概念
如果您是 python 新手,了解基本操作、数据类型和条件逻辑至关重要。让我们回顾一下一些基本主题。我们将通过示例探讨每个主题。
第 1 章:算术运算符
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 |
这些运算符可帮助您处理代码中的数字。以下是一些示例:
# multiplicationresult = 4 * 10print(result) # output: 40# additiontotal = 7 + 9print(total) # output: 16# powersquared = 3 ** 2print(squared) # output: 9
您还可以使用这些运算符为变量赋值:
# define total spend amounttotal_spend = 3150.96print(total_spend) # output: 3150.96
第 2 章:数据类型和集合
在 python 中,您有多种存储数据的方法,每种方法都适合不同类型的任务。
字符串:用于文本。您可以使用单引号或双引号定义字符串。
# defining a stringcustomer_name = 'george boorman'print(customer_name)# double quotes also workcustomer_name = "george boorman"
列表:列表是可以包含多个值的有序集合。
# creating a listprices = [10, 20, 30, 15, 25, 35]# accessing the first itemprint(prices[0]) # output: 10
字典:字典存储键值对,允许您根据键查找值。
# creating a dictionaryproducts_dict = { "ag32": 10, "ht91": 20, "pl65": 30, "os31": 15, "kb07": 25, "tr48": 35}# accessing a value by keyprint(products_dict["ag32"]) # output: 10
集合和元组:
立即学习“Python免费学习笔记(深入)”;
# creating a setprices_set = {10, 20, 30, 15, 25, 35}# creating a tupleprices_tuple = (10, 20, 30, 15, 25, 35)
第 3 章:条件关键字
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 中算术运算、各种数据类型和条件关键字的基础知识。这些基本概念将帮助您构建更复杂的程序。