当前位置: 首页 > news >正文

第二天 Python基础语法

Python 是一种广泛使用的高级编程语言,以其简洁易读、语法优雅而著称。以下是 Python 基础语法的简要介绍,适合初学者入门:

  1. 变量和数据类型
    变量
    变量用于存储数据值。
    Python 是动态类型语言,变量类型在赋值时自动确定。
    python
    x = 10 # 整数
    y = 3.14 # 浮点数
    z = “Hello, World!” # 字符串
    数据类型
    整数 (int): 10, -5
    浮点数 (float): 3.14, -0.01
    字符串 (str): “Hello”, ‘Python’
    布尔值 (bool): True, False
    列表 (list): [1, 2, 3], [“a”, “b”, “c”]
    元组 (tuple): (1, 2, 3), (“a”, “b”, “c”)
    字典 (dict): {“name”: “Alice”, “age”: 25}, dict(name=“Alice”, age=25)
    集合 (set): {1, 2, 3}, {“a”, “b”, “c”}
  2. 控制结构
    条件语句
    使用 if, elif, else 进行条件判断。
    python
    if x > 10:
    print(“x is greater than 10”)
    elif x == 10:
    print(“x is equal to 10”)
    else:
    print(“x is less than 10”)
    循环
    使用 for 和 while 进行循环。
    python

for 循环

for i in range(5):
print(i)

while 循环

count = 0
while count < 5:
print(count)
count += 1
3. 函数
使用 def 定义函数。
python
def greet(name):
print(f"Hello, {name}!")

greet(“Alice”)
4. 类和对象
使用 class 定义类。
类的实例称为对象。
python
class Dog:
def init(self, name, age):
self.name = name
self.age = age

def bark(self):  print(f"{self.name} says woof!")  

dog = Dog(“Buddy”, 3)
dog.bark()
5. 模块和包
Python 模块是一个包含 Python 代码的文件,文件扩展名为 .py。
使用 import 语句导入模块。
python
import math
print(math.sqrt(16)) # 输出 4.0

导入特定函数

from math import sqrt
print(sqrt(16)) # 输出 4.0
6. 文件操作
使用内置函数进行文件读写。
python

写文件

with open(“example.txt”, “w”) as file:
file.write(“Hello, World!\n”)

读文件

with open(“example.txt”, “r”) as file:
content = file.read()
print(content) # 输出 Hello, World!
7. 异常处理
使用 try, except, else, finally 进行异常处理。
python
try:
result = 10 / 0
except ZeroDivisionError:
print(“Cannot divide by zero!”)
else:
print(f"Result: {result}")
finally:
print(“Execution of try/except block is finished.”)
8. 输入输出
使用 input() 函数获取用户输入。
使用 print() 函数输出结果。
python
name = input("Enter your name: “)
print(f"Hello, {name}!”)
这些是 Python 编程的基础语法和概念。通过学习和实践这些基础知识,你可以逐步掌握更高级的编程技巧。祝你学习愉快!


http://www.mrgr.cn/news/52121.html

相关文章:

  • Python入门:轻松学会Python的*args和**kwargs
  • MPI程序实例:二维热传导方程(上)
  • JsonObject (JSON 数据中的一个对象)
  • 波兰式与逆波兰式【1】
  • 苍穹外卖学习笔记(二十四)
  • 人工智能 | MetaLlama大模型
  • 通用代码生成器与编程初学者的“第一个系统”
  • 【python】生成环境下依赖的关系拓扑图
  • Spring Boot环境下的图书进销存管理系统
  • 看了大厂用AI审简历,我才发现社会的残酷真相!今年的秋招太可怕了
  • etcd集群修复异常节点
  • SpringBoot长江驾校学员预约系统-计算机毕业设计源码86072
  • 从牛顿第一定律看待人生
  • AMR Codec参数在SDP中的详细解析及其与AMR编解码的关系
  • 查找资料网站:
  • 云开发 | 如何获取用户输入数据,并且在云数据库中删除该条数据
  • > Invalid revision: 3.22.1-g37088a8-dirty
  • 【优选算法】(第四十五篇)
  • 浅谈dll劫持-白加黑免杀指南
  • WebSocket