社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

小小的python学习社 • 6 天前 • 37 次点击  

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 ba or bnot a

6. 条件语句:

if condition:    # do somethingelif another_condition:    # do something elseelse:    # 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 = (123)

10. 字典:

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

11. 集合:

my_set = {123}my_set.add(4)

12. 字符串操作:

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

13. 字符串格式化:

name = "John"age = 30f"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 + param2my_function(param2=10, param1=5)

18. 可变参数:

def my_function(*args):    for arg in args:        print(arg)
my_function(123)

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**2f(5)

21. map函数:

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

22. filter函数:

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

23. reduce函数:

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

24. 异常处理:

try:    # do somethingexcept 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 = param1
    def my_method(self):        return self.param1

28. 类继承:

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

29. 魔法方法:

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

30. 属性和装饰器:

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

31. 生成器:

def my_generator():    yield 1    yield 2    yield 3
for 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 result    return wrapper

@my_decoratordef my_function():    print("Function call")

my_function()

37. 类型注解:

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

38. 枚举:

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

39. 迭代器:

class MyIterator:    def __init__(self, start, end):        self.current = start        self.end = end

    def __iter__(self):        return self

    def __next__(self):        if self.current >= self.end:            raise StopIteration        else:            self.current += 1            return self.current - 1

40. JSON解析:

import json

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

41. 日期和时间:

from datetime import datetimenow = datetime.now()

42. 随机数生成:

import random

random_number = random.randint(110)

43. 数学运算:

import math

math.sqrt(16)

44. 模块和包:

# my_module.pydef my_function():    return "Hello"

# main.pyimport my_modulemy_module.my_function()

45. 命名空间:

global_var = 5

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

46. 继承和多态:

class Animal:    def speak(self):        pass

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

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

47. 操作系统交互:

import os

os.getcwd()os.listdir(".")

48. 命令行参数:

import sys

for arg in sys.argv:    print(arg)

49. 正则表达式:

import re

pattern = r"\d+"re.findall(pattern, "There are 2 apples and 5 bananas.")
以上就是今天的全部内容分享,篇幅有限,下半部分关注下次的内容,觉得有用的话欢迎点赞收藏哦!
安装包工具+资料获取方式:↓↓↓↓
1.关注下方公众号↓↓↓↓
2.点赞+再看
3.在后台发送:“python可免费领取

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/180046
 
37 次点击