Python源代码大全
Python是一种广泛使用的高级编程语言,以其简洁明了的语法和强大的功能而受到开发者的喜爱。无论你是初学者还是资深开发者,掌握Python源代码是提升编程技能的重要一步。本文将为你提供一些经典的Python源代码示例,帮助你更好地理解和运用这门语言。
1. 简单计算器
首先,让我们从一个简单的计算器开始。这个程序能够执行加法、减法、乘法和除法操作。
```python
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x y
def divide(x, y):
if y == 0:
return "Error! Division by zero."
return x / y
print("Select operation.")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("Enter choice(1/2/3/4): ")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "", num2, "=", multiply(num1, num2))
elif choice == '4':
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid input")
```
2. 猜数字游戏
接下来是一个猜数字的游戏。程序会随机选择一个数字,然后让用户尝试猜测这个数字。
```python
import random
def guess_number():
number_to_guess = random.randint(1, 100)
attempts = 0
while True:
guess = int(input("Guess the number (between 1 and 100): "))
attempts += 1
if guess < number_to_guess:
print("Too low!")
elif guess > number_to_guess:
print("Too high!")
else:
print(f"Congratulations! You've guessed it in {attempts} attempts.")
break
guess_number()
```
3. 文件读写操作
文件操作是Python中非常常见的任务。下面是一个简单的例子,展示如何读取和写入文件。
```python
写入文件
with open('example.txt', 'w') as file:
file.write("Hello, Python!")
读取文件
with open('example.txt', 'r') as file:
content = file.read()
print(content)
```
4. 爬虫基础
爬虫可以帮助我们从网页上抓取数据。这里是一个使用`requests`库和`BeautifulSoup`库的简单爬虫示例。
```python
import requests
from bs4 import BeautifulSoup
url = 'https://www.example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
```
这些示例只是Python众多功能的一小部分。通过不断实践和探索,你可以掌握更多复杂的Python源代码,并将其应用于各种实际项目中。希望这些代码能激发你的灵感,帮助你在编程之旅中取得更大的进步!
---
以上内容尽量保持简洁,同时涵盖了多种基本的Python应用场景,适合不同层次的读者参考和学习。