python基础代码大全100条
时间: 2024-09-25 20:19:52 浏览: 82
Python是一门强大的脚本语言,其简洁易读的语法使得编写各种程序变得非常方便。下面列举一些Python的基础代码示例,供初学者参考:
1. 打印Hello World:
```python
print("Hello World!")
```
2. 定义变量:
```python
name = "Alice"
age = 25
```
3. 数据类型:
- 整数: `x = 42`
- 浮点数: `pi = 3.14`
- 字符串: `"my string"`
- 列表: `[1, 2, 3]`
- 元组: `(1, 2, 3)`
- 字典: `{ 'key': 'value' }`
4. 条件判断 (if):
```python
if x > 0:
print("Positive")
```
5. 循环结构 (for, while):
```python
for i in range(5):
print(i)
```
6. 函数定义:
```python
def greet(name):
return "Hello, " + name
greet("Bob")
```
7. 模块导入:
```python
import math
math.sqrt(9)
```
8. 类和对象 (OOP):
```python
class Dog:
def bark(self):
return "Woof!"
dog = Dog()
dog.bark()
```
阅读全文