【Python入门】10个实用的代码段带你上手
Python是一种高级编程语言,有着简单易学、代码精简、高效快速的特点。Python的应用范围非常广泛,它可以用于Web开发、数据挖掘、人工智能等领域。如果你是一名初学者,那么这篇文章将会为你介绍10个实用的Python代码段,带你轻松入门!
1. 打印Hello World
```python
print("Hello World!")
```
这是Python里最基本的代码段,它可以让你了解如何在Python中打印输出。
2. 输入和输出
```python
# 输入字符串
name = input("What's your name?")
print("Your name is " + name)
# 输出数字
age = 18
print("Your age is", age)
# 格式化输出
score = 90
print("Your score is %.2f" % score)
```
这段代码可以帮助你学习输入和输出的基础知识,以及如何使用字符串格式化输出。
3. 列表
```python
# 创建列表
fruits = ['apple', 'banana', 'cherry']
# 遍历列表
for fruit in fruits:
print(fruit)
# 添加元素
fruits.append('orange')
# 删除元素
fruits.remove('cherry')
```
这段代码可以让你学习如何创建和处理列表。
4. 字典
```python
# 创建字典
person = {'name': 'Tom', 'age': 18, 'gender': 'male'}
# 获取值
print(person['name'])
# 修改值
person['age'] = 20
# 添加键值对
person['height'] = '180cm'
# 遍历字典
for key, value in person.items():
print(key + ':', value)
```
这段代码可以让你学习如何创建和处理字典。
5. 条件语句
```python
# if语句
age = 18
if age >= 18:
print("You are an adult")
else:
print("You are a child")
# elif语句
score = 90
if score >= 90:
print("A")
elif score >= 80:
print("B")
else:
print("C")
```
这段代码可以让你学习如何使用条件语句来判断条件。
6. 循环语句
```python
# while循环
i = 1
while i <= 10:
print(i)
i += 1
# for循环
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
```
这段代码可以让你学习如何使用循环语句来循环执行代码。
7. 函数
```python
# 定义函数
def add(a, b):
return a + b
# 调用函数
result = add(1, 2)
print(result)
```
这段代码可以让你学习如何定义和调用函数。
8. 文件操作
```python
# 打开文件
f = open('test.txt', 'w')
# 写入文件
f.write('Hello World!')
# 关闭文件
f.close()
# 读取文件
f = open('test.txt', 'r')
content = f.read()
print(content)
```
这段代码可以让你学习如何进行文件操作。
9. 正则表达式
```python
import re
# 匹配邮箱
email = 'abc@abc.com'
result = re.match(r'([\w.-]+)@([\w.-]+)', email)
if result:
print(result.group(1))
print(result.group(2))
```
这段代码可以让你学习如何使用正则表达式来匹配字符串。
10. 爬虫
```python
import requests
from bs4 import BeautifulSoup
# 访问网页
url = 'https://www.baidu.com'
response = requests.get(url)
# 解析网页
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.string)
```
这段代码可以让你学习如何使用Python爬虫来获取网页内容。
以上就是10个实用的Python代码段,这些代码能够帮助你快速上手Python编程。希望这篇文章对你有所帮助!