Exploring Python: From 1 to 20 — A Comprehensive Journey through Code and Concepts
1. Hello, Python
print('Hello, Python!')
2. Variables and Data Types
name = 'Michael Jordan'
age = 33
height = 198
weight = 95
3. Lists
singers = ['Jackie Cheung', 'Andy Lau', 'Leon Lai']
singers.append('Aaron Kwok')
print(singers)
4. Dictionaries
singer = {'name': 'Jane Zhang', 'birthday': '1984-10-11', 'birthplace': 'Chengdu', 'height': 162, 'weight': 49}
print(singer['name'])
5. Loops
for i in range(1, 11):
print(i)
6. Conditional Statements
score = 85
if score > 90:
print('You are excellent!')
else:
print('You are not excellent yet. Keep working!')
7. Functions
def add(a, b):
return f'Result: {a + b}'
result = add(2, 3)
print(result)
8. Importing Modules
import math
print(math.sqrt(100))
9. Exception Handling
try:
result = 2 / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
10. File Operations
with open('d:/test.txt', 'w') as f:
f.write('Hello, Python!')
with open('d:/test.txt', 'r') as f:
content = f.read()
print(content)
11. Date and Time
from datetime import datetime
now = datetime.now()
print(now)
12. Regular Expressions
import re
text = 'Phone Number: 18688886666'
pattern = r'\d+'
match = re.search(pattern, text)
if match:
print(match.group()) # Extracting phone number
13. Web Requests
import requests
resp = requests.get('https://www.google.com')
content = resp.text
print(content)
14. BeautifulSoup Web Scraping
from bs4 import BeautifulSoup
import requests
url = 'https://www.google.com'
resp = requests.get(url)
soup = BeautifulSoup(resp.text, 'html.parser')
print(soup)
15. Graphical User Interface (GUI)
import tkinter as tk
root = tk.Tk()
label = tk.Label(root, text='Hello, Python!')
label.pack()
root.mainloop()
16. Generating Test Data
from faker import Faker
fake = Faker()
print(fake.name())
17. Numpy Data Analysis
import numpy as np
arr = np.array([10, 20, 30, 40, 50])
print(arr.mean())
18. Pandas Data Processing
import pandas as pd
data = {'Name': ['Lu Bu', 'Zhao Yun', 'Dian Wei'], 'Power': [100, 95, 90]}
df = pd.DataFrame(data)
print(df)
19. Matplotlib Data Visualization
import matplotlib.pyplot as plt
x = [2, 4, 6, 8, 10]
y = [4, 8, 12, 16, 20]
plt.plot(x, y)
plt.show()
20. Plotly Data Visualization
import plotly.express as px
fig = px.scatter(x=[1, 2, 3, 4, 5], y=[2, 4, 6, 8, 10])
fig.show()