python入门基础语法
Python是一种高级编程语言,为初学者提供了一个易于理解和学习的环境。本文将从多个角度介绍Python入门基础语法。
变量和数据类型
在Python中,变量是一种用于存储数据的占位符。变量名应以字母或下划线开头,并且不能以数字开头。以下是Python支持的常见数据类型:
- 整数(int)
- 浮点数(float)
- 布尔值(bool)
- 字符串(str)
- 列表(list)
- 元组(tuple)
- 集合(set)
- 字典(dict)
例如:
```python
x = 5
y = 3.14
z = True
name = "John"
fruits = ["apple", "banana", "cherry"]
colors = ("red", "green", "blue")
prime_numbers = {2, 3, 5, 7, 11}
person = {"name": "John", "age": 36}
```
运算符和表达式
Python中有很多运算符,包括算术、比较、逻辑和位运算符。表达式是由运算符和操作数组成的。例如:
```python
x = 5
y = 3
print(x + y) # 加法运算符
print(x - y) # 减法运算符
print(x * y) # 乘法运算符
print(x / y) # 除法运算符
print(x % y) # 取模运算符
print(x ** y) # 幂运算符
print(x == y) # 等于运算符
print(x != y) # 不等于运算符
print(x > y) # 大于运算符
print(x < y) # 小于运算符
print(x >= y) # 大于等于运算符
print(x <= y) # 小于等于运算符
print(x and y) # 逻辑与运算符
print(x or y) # 逻辑或运算符
print(not x) # 逻辑非运算符
print(x & y) # 按位与运算符
print(x | y) # 按位或运算符
print(x ^ y) # 按位异或运算符
print(x << y) # 左移位运算符
print(x >> y) # 右移位运算符
```
条件语句
条件语句是编程中常见的语句,用于根据条件执行不同的代码块。Python中有两种条件语句:if语句和switch语句。if语句可以根据条件执行不同的代码块。例如:
```python
x = 5
if x > 3:
print("x is greater than 3")
elif x == 3:
print("x is equal to 3")
else:
print("x is less than 3")
```
循环语句
循环语句是编程中常见的语句之一,用于重复执行一段代码块。Python中有两种循环语句:while循环和for循环。while循环用于重复执行一段代码块,直到条件不再成立。for循环用于遍历序列中的元素。例如:
```python
i = 0
while i < 5:
print(i)
i += 1
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
函数
函数是编程中非常重要的概念,可以将一段代码作为一个单元进行封装和复用。Python中可以定义自己的函数,例如:
```python
def greeting(name):
print("Hello, "+ name +"!")
greeting("John")
```
模块
模块是Python中的一个重要概念,可以将一些常用的代码封装到模块中,然后在其他程序中进行调用。Python标准库中有很多模块可以使用,例如:
```python
import math
print(math.sqrt(16)) # 返回4.0
```