[go: up one dir, main page]

0% found this document useful (0 votes)
12 views46 pages

Python Cheatsheet

This document is a comprehensive Python Cheat Sheet covering various topics including installation, basic syntax, data types, operators, control flow, loops, functions, data structures, modules, file handling, error handling, object-oriented programming, advanced topics, date and time, math and statistics, regular expressions, working with APIs, Pythonic conventions, and virtual environments. Each section provides essential information and examples to help users understand and utilize Python effectively. It also includes mini projects and interview questions for practical application and preparation.

Uploaded by

musaqureshi524
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views46 pages

Python Cheatsheet

This document is a comprehensive Python Cheat Sheet covering various topics including installation, basic syntax, data types, operators, control flow, loops, functions, data structures, modules, file handling, error handling, object-oriented programming, advanced topics, date and time, math and statistics, regular expressions, working with APIs, Pythonic conventions, and virtual environments. Each section provides essential information and examples to help users understand and utilize Python effectively. It also includes mini projects and interview questions for practical application and preparation.

Uploaded by

musaqureshi524
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

Python

CheatSheet
TABLE OF CONTENTS
1. Introduction to Python
What is Python?
History & Features
Applications of Python
Installing Python
Running Python Code (IDLE, VS Code, Terminal)

2. Basic Syntax
Comments
Variables
Keywords
Indentation
Input/Output (input(), print())

3. Data Types
Numbers (int, float, complex)
Strings
Boolean
None Type
Type Conversion
type() and isinstance()

4. Operators
Arithmetic Operators
Comparison Operators
Logical Operators
Assignment Operators
Bitwise Operators
Identity & Membership Operators
Operator Precedence

5. Control Flow
if, elif, else
Nested Conditions
Ternary Operator

6. Loops
for Loops
while Loops
Loop Control (break, continue, pass)
range() Function
List Comprehension
TABLE OF CONTENTS
7. Functions
Defining & Calling Functions
Parameters & Arguments
Default, Keyword & Arbitrary Arguments
Return Statement
Lambda Functions
map(), filter(), reduce()

8. Data Structures
Lists
Creation, Indexing, Slicing
Common Methods
Tuples
Immutable Sequences
Sets
Unique Values, Set Operations
Dictionaries
Key-Value Pairs, Methods
Strings (Advanced)
String Formatting (f-strings, format(), %)
String Methods

9. Modules and Packages


Importing Modules
import vs from
Creating Custom Modules
Using pip to Install Packages
Popular Libraries Overview (NumPy, pandas, requests, etc.)

10. File Handling


Reading and Writing Files
Working with File Paths
with Statement
CSV and JSON Handling

11. Error Handling


try, except, finally
raise Statement
Common Exceptions
TABLE OF CONTENTS
12. Object-Oriented Programming (OOP)
Classes and Objects
__init__ Constructor
self Keyword
Methods
Inheritance
Encapsulation & Abstraction
super() Function
@staticmethod & @classmethod

13. Advanced Topics


Iterators & Generators
Decorators
Recursion
*args and **kwargs
Comprehensions (List, Dict, Set)
Enumerate, Zip

14. Date and Time


datetime Module
Formatting Dates
Timestamp Conversions

15. Math and Statistics


math Module
random Module
statistics Module

16. Regular Expressions


re Module Basics
Pattern Matching
Common Regex Patterns

17. Working with APIs


requests Library Basics
GET and POST Requests
Handling JSON Data
TABLE OF CONTENTS
18. Pythonic Conventions
PEP8 Style Guide
Docstrings
Code Optimization Tips

19. Virtual Environments & Dependency Management


venv Module
requirements.txt
pip freeze

20. Popular Libraries (Overview)


Data Science: NumPy, pandas, matplotlib, seaborn
Web Development: Flask, Django
Automation: selenium, pyautogui, schedule
Machine Learning: scikit-learn, TensorFlow, PyTorch

21. Debugging & Testing


Using pdb
Writing Unit Tests with unittest or pytest

22. Mini Projects


Calculator
To-Do List
Web Scraper
Weather App using API
Alarm Clock

23. Interview Questions (Bonus)


Frequently Asked Python Questions
Code Challenges
1. INTRODUCTION TO PYTHON
1.1 What is Python?
Python is a high-level, interpreted, and general-purpose programming
language known for its simple syntax and readability.
✅ Great for beginners and professionals alike.
1.2 History & Features
Created by: Guido van Rossum
Released: 1991
Key Features:
Easy to learn
Open-source and free
Dynamically typed
Huge standard library
Portable across platforms
Supports OOP and functional programming
1.3 Applications of Python
Python is used in:
✅ Web Development (e.g., Django, Flask)
✅ Data Science & Machine Learning (e.g., Pandas, NumPy, Scikit-learn)
✅ Automation/Scripting
✅ Game Development
✅ Cybersecurity
✅ IoT
✅ Desktop & Mobile Apps
1.4 Installing Python
Go to python.org/downloads
Download and install the latest version
Add Python to system PATH during installation
1.5 Running Python Code
You can run Python code in several ways:
➤ IDLE (comes with Python)
1. INTRODUCTION TO PYTHON
➤ Terminal / Command Prompt

➤ VS Code (or any code editor)


Save file as example.py
Run in terminal:

➤ Interactive Shell (REPL)


Just type python in terminal and start typing Python code directly.
2. BASIC SYNTAX
2.1 Comments
Used to explain code; ignored during execution.

2.2 Variables
Containers for storing data; no need to declare data types explicitly.

2.3 Keywords
Reserved words in Python that cannot be used as variable names.
Examples: if, else, for, while, def, class, return, import

To view all keywords:


2. BASIC SYNTAX
2.4 Indentation
Python uses indentation (spaces/tabs) to define blocks of code (no {} like
other languages).

⚠️ Incorrect indentation will raise an IndentationError.


2.5 Input/Output
➤ input() – Takes user input (as a string):

➤ print() – Displays output:

You can also format output:


3. DATA TYPES
3.1 Numbers (int, float, complex)
Python can work with numbers just like a calculator.
int is a whole number → 5, 100
float is a number with a dot → 3.14, 2.0
complex has a little math magic → 2 + 3j (used in advanced math)

3.2 Strings
Strings are just text! You put it inside quotes.

3.3 Boolean
This is a special type that only says True or False — like yes or no!

3.4 None Type


“None” means nothing. It’s like an empty box.
3. DATA TYPES
3.5 Type Conversion
You can change one type to another.

3.6 type() and isinstance()


These help us check what kind of thing something is.
4. OPERATORS
4.1 Arithmetic Operators
These are math symbols:
+ (add), - (subtract), * (multiply), / (divide), // (divide and round down), %
(remainder), ** (power)

4.2 Comparison Operators


Used to compare numbers:
== (equal), != (not equal), > (greater), < (less), >=, <=

4.3 Logical Operators


Used when you have more than one condition.
and → both must be true
or → one can be true
not → opposite

4.4 Assignment Operators


Used to store values in a variable.
4. OPERATORS
4.5 Bitwise Operators
These work with 0s and 1s (like computer brain math) – not needed early on.
4.6 Identity & Membership Operators
“is” checks if two things are exactly the same
“in” checks if something is inside something

4.7 Operator Precedence


Some operations happen first (like multiplication before addition).
5. CONTROL FLOW
5.1 if, elif, else
It helps your code make decisions.

5.2 Nested Conditions


An if inside another if.

5.3 Ternary Operator


A short way to write if else.
6. LOOPS
6.1 for Loops
When you want to do something again and again, use a loop!

6.2 while Loops


Runs as long as something is True.

6.3 Loop Control


break: Stop the loop
continue: Skip and move to the next loop
pass: Do nothing (just a placeholder)

6.4 range() Function


It gives a list of numbers to loop through.
6. LOOPS
6.5 List Comprehension
A short and fast way to create lists.
7. FUNCTIONS
7.1 Defining & Calling Functions
Functions help you reuse code.

7.2 Parameters & Arguments


Give inputs to a function.

7.3 Default, Keyword & Arbitrary Arguments


Default → value used if nothing is given
Keyword → specify name
Arbitrary → many arguments using * or **

7.4 Return Statement


It gives back a value.
7. FUNCTIONS
7.5 Lambda Functions
Tiny functions written in one line.

7.6 map(), filter(), reduce()


Used with functions to work on lists:
8. DATA STRUCTURES
8.1 Lists
Store many items. You can change them.

8.2 Tuples
Like lists, but you can’t change them.

8.3 Sets
No duplicates allowed!

You can do math with sets like union and intersection.


8.4 Dictionaries
Think of it like a mini-database — it stores key-value pairs.
8. DATA STRUCTURES
8.5 Strings (Advanced)
f-strings, format(), %
Different ways to put variables inside strings:

String Methods
Useful tools like .upper(), .lower(), .replace()
9. MODULES AND PACKAGES
9.1 Importing Modules
Python has ready-made tools called modules.
You can use them with the import keyword:

9.2 import vs from


import math means you use math.sqrt()
from math import sqrt means just use sqrt() directly

9.3 Creating Custom Modules


You can create your own module (a .py file with some functions) and use it
in another file.
greetings.py:

main.py:
9. MODULES AND PACKAGES
9.4 Using pip to Install Packages
pip is like a shopping cart for code tools. You can install stuff like this:

9.5 Popular Libraries Overview


NumPy: Math with big numbers & arrays
pandas: Handling data like Excel
requests: Talk to websites & APIs
matplotlib: Make graphs & charts
tkinter: Build simple apps with buttons & windows
10. FILE HANDLING
10.1 Reading and Writing Files
Open files to read or write:

10.2 Working with File Paths


You can use folders and paths:

Or for better safety:

10.3 with Statement


with is used so you don’t forget to close the file.
10. FILE HANDLING
10.4 CSV and JSON Handling
CSV (Comma Separated Values)
Used for rows & columns (like Excel):

JSON (JavaScript Object Notation)


Used for storing data (like dictionaries):
11. ERROR HANDLING
Sometimes, your code might break. That’s called an error or exception. You
can catch those errors using special tools.
11.1 try, except, finally

try: Test some code


except: What to do if there’s a problem
finally: Always runs at the end (even if there’s an error)
11.2 raise Statement
You can make your own error with raise.

11.3 Common Exceptions


ValueError: Wrong type of value
TypeError: Wrong type of data
ZeroDivisionError: Dividing by 0
FileNotFoundError: Missing file
IndexError: Wrong list index
KeyError: Wrong dictionary key
12. OBJECT-ORIENTED PROGRAMMING (OOP)
OOP lets us bundle data and functions together. It's like building with
LEGO blocks!
12.1 Classes and Objects
A class is a blueprint. An object is something built from that blueprint.

12.2 __init__ Constructor


Runs automatically when an object is created.

12.3 self Keyword


self refers to the current object itself.
12.4 Methods
Functions inside a class are called methods.
12. OBJECT-ORIENTED PROGRAMMING (OOP)
12.5 Inheritance
Child classes can use and improve parent class stuff.

12.6 Encapsulation & Abstraction


Encapsulation: Hiding the code inside a class
Abstraction: Showing only what’s needed
12.7 super() Function
Lets you call the parent class method.
12. OBJECT-ORIENTED PROGRAMMING (OOP)
12.8 @staticmethod & @classmethod
@staticmethod: Doesn’t use self, like a normal function inside class
@classmethod: Uses cls (the class itself)
13. ADVANCED TOPICS
13.1 Iterators & Generators
Iterator: Goes through items one by one.

Generator: Like a function that remembers where it left off.

13.2 Decorators
A decorator is like adding magic to a function — it changes how it works.
13. ADVANCED TOPICS
13.3 Recursion
When a function calls itself.

13.4 *args and **kwargs


*args = many values
**kwargs = many key=value pairs
13. ADVANCED TOPICS
13.5 Comprehensions (List, Dict, Set)
Short way to make lists, sets, or dictionaries.

13.6 enumerate() and zip()


enumerate() gives index and value.
zip() joins two lists.
14. DATE AND TIME
14.1 datetime Module
The datetime module helps us work with dates and times.
We can get the current date/time or create specific dates.

14.2 Formatting Dates


We can format the date to look the way we want using .strftime().

Format codes example:


%d → Day
%m → Month (number)
%B → Month name
%Y → Year
%I:%M %p → Hour:Minute AM/PM
14. DATE AND TIME
14.3 Timestamp Conversions
A timestamp is a number that shows date/time in seconds since 1970.
15. MATH AND STATISTICS
15.1 math Module
The math module gives us access to math functions.

Useful for scientific calculations, square roots, trigonometry, etc.


15.2 random Module
The random module helps with random values — great for games or data
shuffling.

Great for games, simulations, and practice apps.


15.3 statistics Module
The statistics module helps us with data analysis: mean, median, mode, etc.

Useful when working with data science or analyzing user behavior.


16. REGULAR EXPRESSIONS
Regular Expressions (called RegEx) help you find patterns in text — like
phone numbers, emails, or passwords.
16.1 re Module Basics
To use RegEx in Python, we use the built-in re module:

16.2 Pattern Matching


Let’s say you want to check if a word is inside a sentence:

You can also find all matches:


16. REGULAR EXPRESSIONS
16.3 Common Regex Patterns

Pattern What it matches

\d Any digit (0–9)

\w Any letter/number/underscore

. Any character except newline

^ Start of string

$ End of string

* 0 or more repeats

+ 1 or more repeats

{n} Exactly n repeats

Example: Match email pattern


17. WORKING WITH APIS
APIs help your Python code talk to websites or apps to get or send data.
17.1 requests Library Basics
To use APIs, we need the requests library. Install it with:

Then:

17.2 GET and POST Requests


GET → To receive data
POST → To send data

17.3 Handling JSON Data


Most APIs use JSON. Python makes it easy:
18. PYTHONIC CONVENTIONS
Being "Pythonic" means writing code the smart and clean way.
18.1 PEP8 Style Guide
PEP8 is the official guide for writing neat Python code.
Some basic tips:

18.2 Docstrings
Use triple quotes (""" """") to describe what a function/class does.

18.3 Code Optimization Tips


Use list comprehensions: [x*x for x in range(5)]
Avoid unnecessary loops
Use built-in functions like sum(), max(), sorted()
Write readable and DRY (Don't Repeat Yourself) code
19. VIRTUAL ENVIRONMENTS & DEPENDENCY MANAGEMENT
When working on different Python projects, you may need different
versions of libraries. To keep things clean, we use something called a
Virtual Environment — it's like a mini Python setup just for that one
project!
19.1 venv Module
Think of venv as a private sandbox for your project:

Then activate it:


On Windows:

On Mac/Linux:

You’ll now see (myenv) before your terminal — you're inside the virtual
environment!
19.2 requirements.txt
This is a file that lists all the libraries your project uses.
Create it with:

To install everything later on another computer:


19. VIRTUAL ENVIRONMENTS & DEPENDENCY MANAGEMENT
19.3 pip freeze
This command lists all installed Python packages and their versions:

Use it to track what your project depends on.


20. POPULAR LIBRARIES (OVERVIEW)
Python has many helpful toolkits (called libraries) that make work faster
and easier. Here are some famous ones:
20.1 Data Science
NumPy: Fast math with numbers and big lists (arrays).
pandas: Organize and analyze data in tables (like Excel).
matplotlib: Make charts and graphs.
seaborn: Fancy graphs built on top of matplotlib.

20.2 Web Development


Flask: Simple tool to make websites.
Django: Big tool to make full-featured web apps (like Instagram).

20.3 Automation
selenium: Control web browsers with Python.
pyautogui: Control mouse, keyboard (like a robot).
schedule: Run tasks automatically (like a clock).
20. POPULAR LIBRARIES (OVERVIEW)
20.4 Machine Learning
scikit-learn: For learning and prediction (basic ML).
TensorFlow & PyTorch: Advanced tools to build smart apps that "learn"
from data.
21. DEBUGGING & TESTING
Debugging and testing help us find and fix mistakes in our code and
make sure everything works correctly.
21.1 Using pdb
pdb is Python's built-in debugger. It lets you pause your code and check
what’s going on step-by-step.

Use commands like n (next), c (continue), and p variable_name (to print)


while debugging.
21.2 Unit Testing with unittest or pytest
Tests check if parts of your code are working. A unit test checks one small
part of your program.
Example using unittest:

You can also use pytest for easier syntax and better output.
22. MINI PROJECTS (PRACTICE MAKES PERFECT!)
Build these to practice real-world Python coding:
22.1 Calculator
Take input from the user and perform basic operations:

22.2 To-Do List


Use lists and functions to add/remove/display tasks.
22.3 Web Scraper
Use requests and BeautifulSoup to extract info from websites.

22.4 Weather App using API


Use an API like OpenWeatherMap to get weather data for a city.
22.5 Alarm Clock
Use datetime and playsound modules to create a simple alarm.
23. INTERVIEW QUESTIONS (BONUS)
23.1 Frequently Asked Python Questions
What is Python and why is it popular?
Explain *args and **kwargs.
What is the difference between is and ==?
How does memory management work in Python?
What are Python decorators?
23.2 Code Challenges
Reverse a string
Check if a number is prime
Find the factorial of a number
Create a Fibonacci sequence
Sort a list without using sort()
Was this post helpful ?

Follow Our 2nd Account

Follow For More


Tap Here

You might also like