python - dwilson2547/wiki_demo GitHub Wiki
Python is a high-level, interpreted, and general-purpose programming language known for its simplicity, readability, and versatility. Created by Guido van Rossum in 1991, Python emphasizes code readability with its clean syntax and indentation-based structure. It is widely used in web development, data science, machine learning, automation, scripting, and more.
- 1. Key Features of Python
- 2. Basic Python Syntax
- 3. Python for Different Domains
- 4. Example: Simple Python Script
- 5. Python 2 vs. Python 3
- 6. Installing Python
- 7. Python Strengths
- 8. Python Weaknesses
- 9. When to Use Python
- 10. Example: Simple Web Server with Flask
- 11. Learning Resources
- 12. Summary
-
Simple Syntax: Uses indentation (whitespace) instead of braces
{}
or keywords likeend
. -
Example:
if x > 10: print("x is greater than 10") else: print("x is 10 or less")
- No Compilation Needed: Python code is executed line-by-line by the Python interpreter.
-
Example:
python script.py
- No Explicit Type Declarations: Variable types are inferred at runtime.
-
Example:
x = 10 # Integer x = "hello" # Now a string
- Runs on Windows, macOS, Linux, and more.
-
Example:
# Install Python on Ubuntu sudo apt install python3
- Batteries Included: Comes with modules for file I/O, networking, databases, math, and more.
-
Example:
import os print(os.listdir()) # List files in the current directory
- Supports procedural, object-oriented, and functional programming.
-
Example (OOP):
class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says woof!") my_dog = Dog("Buddy") my_dog.bark() # Output: Buddy says woof!
-
Third-Party Libraries: Over 300,000 packages on PyPI (Python Package Index).
- Web Development: Django, Flask
- Data Science: NumPy, Pandas, Matplotlib
- Machine Learning: TensorFlow, PyTorch, Scikit-learn
- Automation: Selenium, BeautifulSoup
- Scripting: Requests, Click
# Variables
name = "Alice"
age = 25
is_student = True
height = 5.9
# Data Types
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(is_student)) # <class 'bool'>
print(type(height)) # <class 'float'>
age = 18
if age >= 18:
print("Adult")
elif age >= 13:
print("Teen")
else:
print("Child")
# For loop
for i in range(5):
print(i) # Prints 0 to 4
# While loop
count = 0
while count < 5:
print(count)
count += 1
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
# List (mutable)
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
# Tuple (immutable)
colors = ("red", "green", "blue")
# Dictionary (key-value pairs)
person = {"name": "Alice", "age": 25, "is_student": True}
print(person["name"]) # Output: Alice
# Write to a file
with open("example.txt", "w") as file:
file.write("Hello, Python!")
# Read from a file
with open("example.txt", "r") as file:
content = file.read()
print(content) # Output: Hello, Python!
Domain | Use Case | Popular Libraries |
---|---|---|
Web Development | Backend APIs, full-stack apps | Django, Flask, FastAPI |
Data Science | Data analysis, visualization | NumPy, Pandas, Matplotlib, Seaborn |
Machine Learning | AI/ML models, deep learning | TensorFlow, PyTorch, Scikit-learn |
Automation | Scripting, web scraping, task automation | Selenium, BeautifulSoup, Requests |
Game Development | 2D games | Pygame |
Desktop Apps | GUI applications | Tkinter, PyQt, Kivy |
DevOps | Automation, CI/CD | Ansible, Fabric |
Embedded Systems | Microcontrollers (Raspberry Pi, Arduino) | MicroPython, CircuitPython |
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
print(soup.title.text) # Prints the title of the webpage
pip install pandas
import pandas as pd
data = {"Name": ["Alice", "Bob", "Charlie"], "Age": [25, 30, 35]}
df = pd.DataFrame(data)
print(df)
Feature | Python 2 (EOL) | Python 3 (Current) |
---|---|---|
Support | End-of-life (no updates since 2020) | Actively maintained |
Print Statement | print "Hello" |
print("Hello") |
Unicode | ASCII by default | Unicode by default |
Integer Division |
5 / 2 = 2 (floor division) |
5 / 2 = 2.5 (true division) |
xrange |
xrange() for memory efficiency |
range() (same as xrange in Py2) |
Libraries | Legacy libraries | Modern libraries (e.g., asyncio ) |
Note: Always use Python 3 for new projects.
- Official Website: python.org/downloads
-
Linux (Debian/Ubuntu):
sudo apt update sudo apt install python3
-
macOS (comes pre-installed, but update via Homebrew):
brew install python
- Windows: Download the installer from python.org.
python3 --version
# Output: Python 3.x.x
pip install package_name
# Example:
pip install requests pandas numpy
✅ Easy to Learn: Simple and readable syntax. ✅ Versatile: Used in web dev, data science, AI, automation, and more. ✅ Large Community: Extensive documentation and support. ✅ Cross-Platform: Runs on Windows, macOS, Linux, and embedded systems. ✅ Extensive Libraries: Rich ecosystem for almost any task. ✅ Interpreted: No compilation step; easy to test and debug. ✅ Integrates Well: Works with C/C++, Java, and other languages.
❌ Slower Execution: Interpreted languages are generally slower than compiled languages (e.g., C++, Rust). ❌ Not Ideal for Mobile Apps: Limited support for mobile development (though Kivy and BeeWare exist). ❌ Global Interpreter Lock (GIL): Limits multi-threading performance (mitigated by multi-processing or asyncio). ❌ Memory Consumption: Can be higher than lower-level languages.
- Rapid Prototyping: Quickly test ideas and build MVPs.
- Data Science/Machine Learning: Libraries like NumPy, Pandas, TensorFlow.
- Web Development: Frameworks like Django, Flask, FastAPI.
- Automation/Scripting: Write scripts for repetitive tasks.
- Education: Beginner-friendly syntax for learning programming.
- DevOps: Automate infrastructure with Ansible, Fabric.
- Embedded Systems: MicroPython for microcontrollers (e.g., Raspberry Pi, ESP32).
pip install flask
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, World!"
if __name__ == "__main__":
app.run(debug=True)
Run the server:
python app.py
Visit http://localhost:5000 in your browser.
- Official Docs: python.org/doc
- Tutorials:
-
Books:
- Automate the Boring Stuff with Python (Al Sweigart)
- Fluent Python (Luciano Ramalho)
- Python Crash Course (Eric Matthes)
- Courses:
- Python is a versatile, easy-to-learn, high-level programming language used for web development, data science, automation, and more.
- Key Features: Dynamic typing, extensive standard library, and a vast ecosystem of third-party packages.
- Strengths: Readability, cross-platform support, and strong community.
- Weaknesses: Slower execution and GIL limitations for multi-threading.
- Use Cases: Ideal for beginners, data analysis, web apps, scripting, and prototyping.
Python is often the first choice for developers due to its simplicity and power, making it one of the most popular languages worldwide.