【零基础入门Python】26段简短代码带你快速上手Python

用26个简短的Python代码示例来覆盖Python编程的各个方面,从基础到稍微进阶一点的内容。每个示例都将尽量保持简短且易于理解。

如果你正准备入门Python,但是找不到方向的话可以试试我这一份学习方法和籽料呀!点击 领取

1. 打印Hello, World!

print("Hello, World!")

2. 变量赋值

name = "Alice"
age = 30
print(name, age)

3. 使用if语句

x = 10
if x > 5:
print("x is greater than 5")

4. for循环遍历列表

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

5. while循环

i = 0
while i < 5:
print(i)
i += 1

6. 列表推导式

squares = [x**2 for x in range(10)]
print(squares)

7. 函数定义

def greet(name):
return "Hello, " + name
print(greet("Bob"))

8. 参数与返回值

def add(a, b):
return a + b
result = add(5, 3)
print(result)

9. 列表长度

fruits = ["apple", "banana", "cherry"]
print(len(fruits))

10. 列表追加

fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)

11. 列表索引

fruits = ["apple", "banana", "cherry"]
print(fruits[1])

12. 列表切片

fruits = ["apple", "banana", "cherry", "date"]
print(fruits[1:3])

13. 字典定义

person = {"name": "Alice", "age": 30}
print(person)

14. 访问字典项

person = {"name": "Alice", "age": 30}
print(person["name"])

15. 字典更新

person = {"name": "Alice", "age": 30}
person["city"] = "New York"
print(person)

16. 删除字典项

person = {"name": "Alice", "age": 30}
del person["age"]
print(person)

17. 集合(Set)

my_set = {1, 2, 2, 3}
print(my_set)

18. 集合添加元素

my_set = {1, 2, 3}
my_set.add(4)
print(my_set)

19. 集合移除元素

my_set = {1, 2, 3}
my_set.remove(2)
print(my_set)

20. 元组(Tuple)

my_tuple = (1, 2, 3)
print(my_tuple)

21. 列表转换为字符串

fruits = ["apple", "banana", "cherry"]
fruit_str = " ".join(fruits)
print(fruit_str)

22. 字符串格式化

name = "Alice"
age = 30
print(f"{name} is {age} years old.")

23. 异常处理

try:
x = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")

24. 读取文件

with open("example.txt", "r") as file:
content = file.read()
print(content)

25. 写入文件

with open("output.txt", "w") as file:
file.write("Hello, file!")

26. 列表推导式进阶

  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值