python常见语法

  • 变量赋值

    my_var = 10
    
  1. 基本数据类型

    • 整数(int)、浮点数(float)、字符串(str)、布尔值(bool)、列表(list)、元组(tuple)、集合(set)、字典(dict)。
  2. 字符串

    s = 'This is a string in single quotes.' s = "This is a string in double quotes."
    
  3. 列表

    my_list = [1, 2, 3, 'Python']
    
  4. 元组

    my_tuple = (1, 2, 3)
    
  5. 字典

    my_dict = {'name': 'Python', 'version': 3.8}
    
  6. 条件语句

    if condition: 
        # Do something 
    elif another_condition: 
        # Do something else 
    else: 
        # Do a different thing
    
  7. 循环

    #它for循环和while循环。
    
    for item in my_list: 
        print(item) 
    
    while condition: 
        # Loop body
    
  8. 函数定义

    def my_function(param1, param2): 
        # Function body return result
    
  9. 类和对象

    class MyClass: 
        def __init__(self, attribute): 
            self.attribute = attribute 
    
        def my_method(self): 
            # Method body
    
  10. 模块和包

      # 导入和使用模块。
      import module_name from package import module
    
  11. 异常处理

    try: 
        # Try to do something except Some
    Exception as e: 
        # Handle exception 
    finally: 
        # Clean-up code
    
  12. 列表推导式

    squares = [x**2 for x in range(10)]
    
  13. 字典推导式

    squares_dict = {x: x**2 for x in range(10)}
    
  14. 生成器表达式

    squares_gen = (x**2 for x in range(10))
    
  15. 装饰器

    def my_decorator(func): 
        def wrapper(*args, **kwargs): 
            # Do something before 
            result = func(*args, **kwargs) 
            # Do something after 
            return result 
        return wrapper 
    
    @my_decorator 
    def my_function(): 
        # Function body
    
  16. Lambda函数

    lambda arguments: expression
    
  17. 三元运算符

    value_if_true if condition else value_if_false
    
  18. 全局和局部变量

    global my_global_var
    
  19. 文件操作

    with open('file.txt', 'r') as file: 
        content = file.read()
    
  20. 异步编程

    async def my_async_function(): 
        await some_async_operation()
    
  21. 类型注解

    def my_function(param1: int, param2: str) -> bool: # Function body
    
  22. 属性装饰器

    @property 
    def my_property(self): 
        return self._my_attribute 
    
    @my_property.setter 
    def my_property(self, value): 
        self._my_attribute = value
    

这些是Python编程中经常使用的语法元素。掌握这些基础对于进行有效的Python编程至关重要

相关推荐
Marst Code5 分钟前
(Django)初步使用
后端·python·django
985小水博一枚呀22 分钟前
【对于Python爬虫的理解】数据挖掘、信息聚合、价格监控、新闻爬取等,附代码。
爬虫·python·深度学习·数据挖掘
立秋678934 分钟前
Python的defaultdict详解
服务器·windows·python
wjs202443 分钟前
XSLT 实例:掌握 XML 转换的艺术
开发语言
萧鼎1 小时前
Python第三方库选择与使用陷阱避免
开发语言·python
安冬的码畜日常1 小时前
【D3.js in Action 3 精译_029】3.5 给 D3 条形图加注图表标签(上)
开发语言·前端·javascript·信息可视化·数据可视化·d3.js
一颗星星辰1 小时前
C语言 | 第十章 | 函数 作用域
c语言·开发语言
lxp1997411 小时前
php函数积累
开发语言·php
科技资讯早知道1 小时前
java计算机毕设课设—坦克大战游戏
java·开发语言·游戏·毕业设计·课程设计·毕设
白拾1 小时前
使用Conda管理python环境的指南
开发语言·python·conda