- Chapter 1: Introduction to Python
- Chapter 2: Control Structures
- Chapter 3: Functions
- Chapter 4: Object-Oriented Programming
- Chapter 5: Exception Handling
- Chapter 6: Modules and Packages
- Chapter 7: File Handling
- Chapter 8: Data Structures
- Chapter 9: Advanced Topics
- Chapter 10: Libraries and Frameworks
- Chapter 11: Web Scraping
- Chapter 12: Networking
- Chapter 13: Concurrency
- Chapter 14: GUI Programming
- Chapter 15: Deployment
- Chapter 16: Miscellaneous
- PDF Download Link
Chapter 1: Introduction to Python
What is Python? and Its Importance.
Python is a high-level, interpreted programming language known for its simplicity and readability.
First Python Program
This code prints “Hello, World!” to the console, demonstrating the basic syntax of Python.
print("Hello, World!")
Variables and Data Types
Variables store data of various types like integers, floats, strings, and booleans.
x = 5 # Integer y = 3.14 # Float name = "Alice" # String is_active = True # Boolean
Constants
Constants are usually defined in uppercase and do not change throughout the program.
PI = 3.14159
Operations in Python
Basic arithmetic operations in Python: addition, subtraction, multiplication, and division.
a = 10 b = 5 sum = a + b diff = a - b prod = a * b quot = a / b
Chapter 2: Control Structures
Conditional Statements
Control the flow of execution using conditions: if, elif, and else statements.
if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative")
Looping Constructs
For loop iterates over a sequence, while loop repeats as long as a condition is true.
# For loop for i in range(5): print(i) # While loop i = 0 while i < 5: print(i) i += 1
Jump Statements
Break exits the loop, continue skips to the next iteration.
# Break statement for i in range(5): if i == 3: break print(i) # Continue statement for i in range(5): if i == 3: continue print(i)
Chapter 3: Functions
Defining Functions
Define a function with def keyword, followed by the function name and parameters.
def greet(name): return f"Hello, {name}!"
Function Parameters and Return Type
Functions can take parameters and return a value using the return statement.
def add(a, b): return a + b
Lambda Functions
Lambda functions are small anonymous functions defined with the lambda keyword.
square = lambda x: x * x print(square(5))
Chapter 4: Object-Oriented Programming
Classes and Objects
Classes define objects with attributes and methods; instantiate objects using the class.
class Dog: def __init__(self, name): self.name = name def bark(self): return f"{self.name} says woof!" dog = Dog("Buddy") print(dog.bark())
Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
class Animal: def __init__(self, name): self.name = name class Dog(Animal): def bark(self): return f"{self.name} says woof!" dog = Dog("Buddy") print(dog.bark())
Polymorphism
Polymorphism lets different objects be treated as instances of the same class through shared interfaces.
class Cat: def speak(self): return "Meow" class Dog: def speak(self): return "Woof" animals = [Cat(), Dog()] for animal in animals: print(animal.speak())
Chapter 5: Exception Handling
Understanding Exceptions
Handle runtime errors using try, except blocks.
try: x = 1 / 0 except ZeroDivisionError: print("Cannot divide by zero")
Creating Custom Exceptions
Define custom exceptions by subclassing the Exception class.
class CustomError(Exception): pass try: raise CustomError("An error occurred") except CustomError as e: print(e)
Chapter 6: Modules and Packages
Importing Modules
Import and use standard library modules like math for mathematical functions.
import math print(math.sqrt(16))
Creating and Using Packages
Packages are directories containing multiple modules; use init.py to mark them as packages.
# File structure: # mypackage/ # __init__.py # module.py # module.py def greet(): return "Hello from the module!" # Using the package from mypackage import module print(module.greet())
Chapter 7: File Handling
Reading and Writing Files
Use open() with ‘r’ or ‘w’ mode to read or write files; with statement ensures proper closure.
# Writing to a file with open("example.txt", "w") as file: file.write("Hello, World!") # Reading from a file with open("example.txt", "r") as file: content = file.read() print(content)
Chapter 8: Data Structures
Lists
Lists are ordered collections of items, accessible by index, and mutable.
numbers = [1, 2, 3, 4, 5] print(numbers[0]) # Access element numbers.append(6) # Add element print(numbers)
Tuples
Tuples are ordered, immutable collections of items.
coordinates = (10, 20) print(coordinates[0])
Sets
Sets are unordered collections of unique items.
unique_numbers = {1, 2, 3, 4, 4, 5} print(unique_numbers)
Dictionaries
Dictionaries are key-value pairs, allowing fast lookup of values by keys.
student = {"name": "Alice", "age": 25} print(student["name"]) student["age"] = 26 print(student)
Chapter 9: Advanced Topics
List Comprehensions
List comprehensions provide a concise way to create lists.
squares = [x * x for x in range(10)] print(squares)
Generators
Generators yield items one at a time, useful for large datasets.
def countdown(n): while n > 0: yield n n -= 1 for num in countdown(5): print(num)
Decorators
Decorators modify the behavior of functions or methods.
def my_decorator(func): def wrapper(): print("Something before the function") func() print("Something after the function") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello()
Chapter 10: Libraries and Frameworks
NumPy
NumPy is a library for numerical computations with arrays.
import numpy as np array = np.array([1, 2, 3]) print(array * 2)
Pandas
Pandas is a library for data manipulation and analysis.
import pandas as pd data = {'name': ['Alice', 'Bob'], 'age': [25, 30]} df = pd.DataFrame(data) print(df)
Matplotlib
Matplotlib is a library for creating static, animated, and interactive visualizations.
import matplotlib.pyplot as plt plt.plot([1, 2, 3], [4, 5, 6]) plt.show()
Flask
Flask is a micro web framework for building web applications.
from flask import Flask app = Flask(__name__) @app.route("/") def home(): return "Hello, Flask!" if __name__ == "__main__": app.run(debug=True)
Chapter 11: Web Scraping
BeautifulSoup
BeautifulSoup is a library for parsing HTML and XML documents.
from bs4 import BeautifulSoup import requests response = requests.get("https://example.com") soup = BeautifulSoup(response.content, "html.parser") print(soup.title.text)
Scrapy
Scrapy is a framework for web scraping and crawling websites.
import scrapy class QuotesSpider(scrapy.Spider): name = "quotes" start_urls = ["http://quotes.toscrape.com/"] def parse(self, response): for quote in response.css("div.quote"): yield { "text": quote.css("span.text::text").get(), "author": quote.css("small.author::text").get(), }
Chapter 12: Networking
Sockets
Sockets provide a way to communicate over the network.
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(("example.com", 80)) s.sendall(b"GET / HTTP/1.1\r\nHost: example.com\r\n\r\n") print(s.recv(1024)) s.close()
HTTP Requests
Requests library is used to send HTTP requests.
import requests response = requests.get("https://api.example.com/data") print(response.json())
WebSockets
WebSockets provide full-duplex communication channels over a single TCP connection.
import asyncio import websockets async def hello(): uri = "ws://example.com/websocket" async with websockets.connect(uri) as websocket: await websocket.send("Hello!") print(await websocket.recv()) asyncio.run(hello())
Chapter 13: Concurrency
Threading
Threading allows concurrent execution of code.
import threading def print_numbers(): for i in range(5): print(i) thread = threading.Thread(target=print_numbers) thread.start() thread.join()
Multiprocessing
Multiprocessing creates separate processes, providing true parallelism.
from multiprocessing import Process def print_numbers(): for i in range(5): print(i) process = Process(target=print_numbers) process.start() process.join()
Asyncio
Asyncio provides asynchronous programming support, enabling concurrency.
import asyncio async def say_hello(): print("Hello") await asyncio.sleep(1) print("World") asyncio.run(say_hello())
Chapter 14: GUI Programming
Tkinter
Tkinter is the standard GUI library for Python.
import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Hello, Tkinter!") label.pack() root.mainloop()
PyQt
PyQt is a set of Python bindings for the Qt application framework.
from PyQt5.QtWidgets import QApplication, QLabel app = QApplication([]) label = QLabel("Hello, PyQt!") label.show() app.exec_()
Chapter 15: Deployment
Packaging with setuptools
Setuptools is used to package Python projects.
from setuptools import setup, find_packages setup( name="mypackage", version="0.1", packages=find_packages(), )
Creating Virtual Environments
Virtual environments isolate project dependencies.
# Create a virtual environment python -m venv myenv # Activate the virtual environment # Windows myenv\Scripts\activate # Unix or MacOS source myenv/bin/activate
Docker
Docker automates the deployment of applications inside lightweight containers.
# Dockerfile FROM python:3.8-slim COPY . /app WORKDIR /app RUN pip install -r requirements.txt CMD ["python", "app.py"]
Chapter 16: Miscellaneous
Logging
Logging provides a way to track events that happen when software runs.
import logging logging.basicConfig(level=logging.INFO) logging.info("This is an info message")
Regular Expressions
Regular expressions are used for string matching and manipulation.
import re pattern = r"\b[A-Za-z]+\b" text = "Hello, World!" matches = re.findall(pattern, text) print(matches)
JSON Handling
JSON handling involves serializing and deserializing JSON data.
import json data = {"name": "Alice", "age": 25} json_str = json.dumps(data) print(json.loads(json_str))
Command Line Arguments
Sys.argv provides access to command-line arguments.
import sys print(sys.argv)
Date and Time
DateTime module handles date and time operations.
from datetime import datetime now = datetime.now() print(now.strftime("%Y-%m-%d %H:%M:%S"))
PDF Download Link
Here is the download button for download the pdf of Python Cheat Sheet.
Send download link to:
Hi