pathon常用代码
时间: 2024-09-27 13:13:04 浏览: 38
Python是一种高级编程语言,它以其简洁、易读的语法而闻名。以下是几个常见的Python代码片段:
1. **打印Hello World**:
```python
print("Hello, World!")
```
2. **变量赋值与数据类型**:
```python
name = "Alice" # 字符串
age = 30 # 整数
pi = 3.14159 # 浮点数
```
3. **条件判断** (if-else):
```python
if age > 18:
print("成年人")
else:
print("未成年人")
```
4. **循环** (for和while):
```python
for i in range(5): # 遍历0到4
print(i)
while condition: # 当条件为真时持续循环
do_something()
```
5. **函数定义**:
```python
def greet(name):
return f"你好,{name}!"
greeting = greet("Bob") # 调用函数
```
阅读全文