您的位置:首页 > 游戏 > 手游 > 100个python的基本语法知识【上】

100个python的基本语法知识【上】

2024/11/15 17:15:11 来源:https://blog.csdn.net/roc_ever/article/details/140643295  浏览:    关键词:100个python的基本语法知识【上】

0. 变量和赋值:
x = 5
name = “John”

1. 数据类型:
整数(int)
浮点数(float)
字符串(str)
布尔值(bool)

2. 注释:

# 这是单行注释
"""
这是
多行注释
"""

3. 算术运算:

a + b  # 加法
a - b  # 减法
a * b  # 乘法
a / b  # 除法
a % b  # 取余
a ** b # 幂运算

4. 比较运算:

a == b  # 等于
a != b  # 不等于
a > b   # 大于
a < b   # 小于
a >= b  # 大于等于
a <= b  # 小于等于

5. 逻辑运算:

a and b
a or b
not a

6. 条件语句:

if condition:# do something
elif another_condition:# do something else
else:# do something different

7. 循环:

for i in range(5):print(i)while condition:# do something

8. 列表:

my_list = [1, 2, 3]
my_list.append(4)
my_list[0]  # 访问元素

9. 元组:

my_tuple = (1, 2, 3)

10. 字典:

my_dict = {"name": "John", "age": 30}
my_dict["name"]  # 访问键值

11. 集合:

my_set = {1, 2, 3}
my_set.add(4)

12. 字符串操作:

s = "hello"
s.upper()
s.lower()
s.split(" ")
s.replace("h", "j")

13. 字符串格式化:

name = "John"
age = 30
f"Hello, {name}. You are {age}."

14. 列表解析:

squares = [x**2 for x in range(10)]

15. 函数定义:

def my_function(param1, param2):return param1 + param2

16. 默认参数:

def my_function(param1, param2=5):return param1 + param2

17. 关键字参数:

def my_function(param1, param2):return param1 + param2
my_function(param2=10, param1=5)

18. 可变参数:

def my_function(*args):for arg in args:print(arg)my_function(1, 2, 3)

19. 关键字可变参数:

def my_function(**kwargs):for key, value in kwargs.items():print(f"{key}: {value}")my_function(name="John", age=30)

20. lambda表达式:

f = lambda x: x**2
f(5)

21. map函数:

list(map(lambda x: x**2, range(10)))

22. filter函数:

list(filter(lambda x: x % 2 == 0, range(10)))

23. reduce函数:

from functools import reduce
reduce(lambda x, y: x + y, range(10))

24. 异常处理:

try:# do something
except Exception as e:print(e)
finally:# cleanup

25. 文件读取:

with open("file.txt", "r") as file:content = file.read()

26. 文件写入:

with open("file.txt", "w") as file:file.write("Hello, World!")

27. 类定义:

class MyClass:def __init__(self, param1):self.param1 = param1def my_method(self):return self.param1

28. 类继承:

class MyBaseClass:def __init__(self, param1):self.param1 = param1class MyDerivedClass(MyBaseClass):def __init__(self, param1, param2):super().__init__(param1)self.param2 = param2

29. 魔法方法:

class MyClass:def __init__(self, param1):self.param1 = param1def __str__(self):return f"MyClass with param1={self.param1}"

30. 属性和装饰器:

class MyClass:def __init__(self, value):self._value = value@propertydef value(self):return self._value@value.setterdef value(self, new_value):self._value = new_value

31. 生成器:

def my_generator():yield 1yield 2yield 3for value in my_generator():print(value)

32. 列表解析和生成器表达式:

[x**2 for x in range(10)]
(x**2 for x in range(10))

33. 集合解析:

{x**2 for x in range(10)}

34. 字典解析:

{x: x**2 for x in range(10)}

35. 上下文管理器:

with open("file.txt", "r") as file:content = file.read()

36. 装饰器:

def my_decorator(func):def wrapper(*args, **kwargs):print("Before function call")result = func(*args, **kwargs)print("After function call")return resultreturn wrapper@my_decorator
def my_function():print("Function call")my_function()

37. 类型注解:

def my_function(param1: int, param2: str) -> str:return param2 * param1

38. 枚举:

from enum import Enumclass Color(Enum):RED = 1GREEN = 2BLUE = 3

39. 迭代器:

class MyIterator:def __init__(self, start, end):self.current = startself.end = enddef __iter__(self):return selfdef __next__(self):if self.current >= self.end:raise StopIterationelse:self.current += 1return self.current - 1

40. JSON解析:

import jsonjson_str = '{"name": "John", "age": 30}'
data = json.loads(json_str)

41. 日期和时间:

from datetime import datetime
now = datetime.now()

42. 随机数生成:

import randomrandom_number = random.randint(1, 10)

43. 数学运算:

import mathmath.sqrt(16)

44. 模块和包:

# my_module.py
def my_function():return "Hello"# main.py
import my_module
my_module.my_function()

45. 命名空间:

global_var = 5def my_function():local_var = 10global global_varglobal_var = 20

46. 继承和多态:

class Animal:def speak(self):passclass Dog(Animal):def speak(self):return "Woof"class Cat(Animal):def speak(self):return "Meow"

47. 操作系统交互:

import osos.getcwd()
os.listdir(".")

48. 命令行参数:

import sysfor arg in sys.argv:print(arg)

49. 正则表达式:

import repattern = r"\d+"
re.findall(pattern, "There are 2 apples and 5 bananas.")

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com