如何系统的学习Python——Python的基本语法

学习Python的基本语法是入门的第一步,以下是一些常见的基本语法概念:

  1. 注释:#符号来添加单行注释,或使用三引号('''""")来添加多行注释。
python 复制代码
# 这是一个单行注释

'''
这是
多行
注释
'''
  1. 变量和数据类型: 变量用于存储数据,而数据类型包括整数、浮点数、字符串、布尔值等。
python 复制代码
x = 10  # 整数
y = 3.14  # 浮点数
name = "Python"  # 字符串
is_true = True  # 布尔值
  1. 输入和输出: 使用input()函数接收用户输入,使用print()函数输出结果。
python 复制代码
name = input("请输入你的名字:")
print("你好,", name)
  1. 运算符: 包括算术运算符(+-*/等),比较运算符(==!=<>等)和逻辑运算符(andornot等)。
python 复制代码
a = 5
b = 2

sum_result = a + b
print("和:", sum_result)

is_equal = a == b
print("是否相等:", is_equal)

logical_result = (a > 0) and (b < 5)
print("逻辑结果:", logical_result)
  1. 字符串操作: 字符串可以通过索引和切片访问,也可以使用各种字符串方法。
python 复制代码
text = "Hello, Python!"

print(text[0])      # 输出第一个字符 'H'
print(text[7:13])   # 输出从索引7到13的子字符串 'Python'
print(len(text))    # 输出字符串长度 13
print(text.lower()) # 输出小写字符串 'hello, python!'
  1. 条件语句: 使用ifelifelse来实现条件判断。
python 复制代码
num = 10

if num > 0:
    print("正数")
elif num < 0:
    print("负数")
else:
    print("零")
  1. 循环结构: 使用forwhile进行循环操作。
python 复制代码
# for循环
for i in range(5):
    print(i)

# while循环
count = 0
while count < 3:
    print("循环中", count)
    count += 1
  1. 列表和字典: 列表用于存储一系列数据,字典用于存储键值对。
python 复制代码
# 列表
numbers = [1, 2, 3, 4, 5]
print(numbers[2])  # 输出索引为2的元素 '3'

# 字典
person = {'name': 'John', 'age': 30, 'city': 'New York'}
print(person['age'])  # 输出键为'age'的值 30
相关推荐
金銀銅鐵17 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li19 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸1 天前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学1 天前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田2 天前
Pydantic校验配置文件
python
hboot2 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python