文章目录
- notation
# 单行注释
- variable
x = 10 # 整数
y = 3.14 # 浮点数
name = "Alice" # 字符串
- the number type
# 数字
int_num = 10
float_num = 3.14
# 字符串
str_val = "Hello, World!"
# 列表
list_val = [1, 2, 3, 4, 5]
# 元组
tuple_val = (1, 2, 3, 4, 5)
# 集合
set_val = {1, 2, 3, 4, 5}
# 字典
dict_val = {"name": "Alice", "age": 25}
- control flow
# if 语句
if x > 10:
print("x 大于 10")
elif x == 10:
print("x 等于 10")
else:
print("x 小于 10")
# for 循环
for i in range(5):
print(i)
# while 循环
while x < 10:
x += 1
print(x)
- function
# 定义函数
def greet(name):
return f"Hello, {name}!"
# 调用函数
print(greet("Alice"))
# 带默认参数的函数
def greet(name="World"):
return f"Hello, {name}!"
# 调用函数
print(greet())
print(greet("Alice"))
- class and object
# 定义类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, my name is {self.name} and I am {self.age} years old."
# 创建对象
person = Person("Alice", 25)
# 调用方法
print(person.greet())
-
handle the exception
try:
result = 10 / 0
except ZeroDivisionError:
print(“除数不能为零”)
finally:
print(“执行完毕”) -
moudle and package
# import moudle
import math
using function from moudle
print(math.sqrt(16))
import the special funtion
from math import sqrt
apply the function imported from the library
print(sqrt(16))
- control the file
# open the file
file = open("example.txt", "r")
# read the file
content = file.read()
print(content)
# close the file
file.close()
write into file
file = open("example.txt", "w")
file.write("Hello, World!")
file.close()
- the standard library
using os module
import os
# to ask for the current work directory
```python
print(os.getcwd())
using sys module
import sys
to get the arguments of sys
print(sys.argv)