๐ Python Basics Cheatsheet
๐ Master the essentials of Python โ your gateway to automation, web dev, data science, and beyond.
# This is a comment
# (Think of this like a note for humans, Python ignores it)
print("Hello, world!") # Output something to the screen
# This shows the words โHello, world!โ on your screen
Variables are like boxes where you can store stuff โ numbers, words, or True/False.
# Numbers
x = 10 # x is a box that holds the number 10 (integer)
pi = 3.14 # pi holds a decimal number (called a float)
# Strings (words inside quotes)
name = "Sri" # name holds the word Sri
greeting = 'Hello' # greeting holds Hello (single or double quotes both work)
# Booleans (True or False โ like Yes or No)
is_coding = True # means YES, I am coding
is_sleeping = False # means NO, I am not sleeping
Input lets you ask the user something. Output shows something on the screen.
name = input("What's your name? ")
# This asks the user their name and saves it into a box called 'name'
print("Hello", name)
# This shows: Hello <whatever the user typed>
๐งธ Example:
What's your name? โ Sri
Output: Hello Sri
Operators help us do things like math, comparisons, and logic.
# Arithmetic Operators (like in school)
+ # Add things
- # Subtract
* # Multiply
/ # Divide
% # Remainder after division
** # Power (2 ** 3 means 2 to the power of 3 = 8)
// # Floor divide (cuts off decimals)
# Comparison Operators
== # Is equal to?
!= # Is NOT equal?
> # Greater than?
< # Less than?
>= # Greater than or equal to?
<= # Less than or equal to?
# Logical Operators
and # Both conditions must be True
or # At least one must be True
not # Opposite of the condition
๐งธ Example:
2 + 3 == 5 # True
5 > 3 and 2 < 4 # True
not True # False
Control flow means making decisions and repeating stuff.
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
๐งธ Example:
If x = 5
, it prints โPositiveโ.
If x = 0
, it prints โZeroโ.
Loops repeat things over and over.
# For loop: Repeat a fixed number of times
for i in range(5):
print(i)
๐งธ Output:
0
1
2
3
4
# While loop: Keep going until something is False
count = 0
while count < 5:
print(count)
count += 1 # Adds 1 each time
๐งธ Output:
0
1
2
3
4
Functions are like mini-machines. You give them input, they give you output.
def greet(name):
return "Hello " + name
message = greet("Sri")
print(message)
๐งธ Output:
Hello Sri
Explanation:
def greet(name):
creates a function namedgreet
return
gives back the result- You can reuse the function as many times as you want!
Lists are like toy boxes that hold multiple items.
fruits = ["apple", "banana", "cherry"]
# A list of 3 fruits
for fruit in fruits:
print(fruit) # Print each fruit one by one
๐งธ Output:
apple
banana
cherry
fruits.append("mango") # Add mango to the list
print(fruits[0]) # Shows the first fruit: apple
Python has lots of ready-made tools (functions) you can use:
len("hello") # Gives 5 (the number of letters)
type(10) # Says it's an int (number)
int("5") # Turns the string "5" into a number
str(10) # Turns number 10 into a string
float("3.14") # Makes it a decimal number
bool("") # Empty things are False, others are True
range(3) # Makes numbers 0, 1, 2
๐งธ Example:
list(range(3)) โ [0, 1, 2]
- Use
snake_case
for variable and function names (like:total_score
,get_input
) - Indentation (spacing) is VERY important! Always use 4 spaces.
- To run your Python file:
python filename.py
๐ Python Data Structures Cheatsheet
๐ฏ Data structures let you store, access, and organize your stuff (like toys, lists, or cards).
They help you remember things, find them fast, and keep them tidy when you're coding!
fruits = ["apple", "banana", "mango"]
๐งธ This is a list โ like a toy basket.
It has three fruits, and you can do lots of things with it:
fruits.append("orange") # Adds "orange" to the basket
fruits.remove("banana") # Takes "banana" out
fruits[0] # Gets the first fruit ("apple")
fruits[1] = "grape" # Changes second fruit to "grape"
len(fruits) # Counts how many fruits are in the basket
for fruit in fruits:
print(fruit)
๐งธ This prints each fruit one by one like:
apple
grape
mango
orange
coordinates = (10, 20)
print(coordinates[0]) # Gets the first number (10)
๐งธ Tuples are like coordinates on a map.
You can look at them, but you can't change them.
๐ Use tuples when your data should stay the same.
Example: (latitude, longitude)
, or sizes like (width, height)
person = {"name": "Sri", "age": 17}
๐งธ This is a dictionary. Itโs like a box where each item has a label:
print(person["name"]) # Shows "Sri"
person["age"] = 18 # Changes age to 18
person["city"] = "Chennai" # Adds a new label: "city"
for key, value in person.items():
print(key, value)
๐งธ Output:
name Sri
age 18
city Chennai
numbers = {1, 2, 3, 2, 1}
๐งธ This bag only keeps one of each number, so it becomes:
{1, 2, 3}
numbers.add(4) # Adds number 4
numbers.remove(2) # Removes number 2
๐ You can also check if somethingโs in the set:
if 3 in numbers:
print("Found")
๐งธ Output:
Found
Type | Ordered | Can Change? | Allows Duplicates? | Example |
---|---|---|---|---|
List | โ Yes | โ Yes | โ Yes | ["a", "b", "c"] |
Tuple | โ Yes | โ No | โ Yes | (1, 2, 3) |
Dictionary | โ Yes (by key) | โ Yes | โ No (keys must be unique) | {"key": "value"} |
Set | โ No | โ Yes | โ No | {1, 2, 3} |
- โ Use lists when you need an ordered group of things you want to change
- ๐ Use tuples when the data should never change
- ๐ท๏ธ Use dictionaries when each value needs a name or label
- ๐งน Use sets to remove duplicates or check if something exists
๐ Python OOP Cheatsheet
๐ง OOP lets you create your own blueprints for real things (like people, animals, cars).
It helps you organize your code and reuse it like LEGO blocks! ๐งฑ
A class is like a blueprint or recipe.
class Dog:
pass
๐งธ Imagine youโre drawing a โDogโ template โ but you havenโt made a real dog yet.
An object is a real thing made from a class.
my_dog = Dog()
Now youโve made an actual dog using the Dog
blueprint.
You can make as many dogs as you want!
class Dog:
def __init__(self, name, age):
self.name = name # Every dog has a name
self.age = age # Every dog has an age
Explanation:
__init__()
is a special function that runs when we create a new objectself
is the object itself (think: โthis dogโ)self.name
andself.age
are like labels on that specific dog
dog1 = Dog("Bruno", 3)
print(dog1.name) # Bruno
print(dog1.age) # 3
Now Bruno is your first dog. You can make more dogs too!
class Dog:
def __init__(self, name):
self.name = name
def bark(self):
print(self.name + " says woof!")
Now every dog can bark!
dog1 = Dog("Shadow")
dog1.bark()
๐งธ Output:
Shadow says woof!
class Animal:
def eat(self):
print("This animal eats food.")
class Cat(Animal):
def meow(self):
print("Meow!")
Now Cat
can do everything Animal can do + its own stuff!
kitty = Cat()
kitty.eat() # From Animal
kitty.meow() # From Cat
class BankAccount:
def __init__(self, balance):
self.__balance = balance # private!
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
The __balance
is private. You can't access it directly!
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
class Bird:
def speak(self):
print("Chirp!")
class Duck(Bird):
def speak(self):
print("Quack!")
class Parrot(Bird):
def speak(self):
print("Squawk!")
Now each bird has its own voice:
for bird in [Duck(), Parrot(), Bird()]:
bird.speak()
๐งธ Output:
Quack!
Squawk!
Chirp!
Concept | What it Means (Kid Version) | Python Example |
---|---|---|
Class | A blueprint for things | class Dog: |
Object | A real thing made from a class | dog1 = Dog() |
Attribute | Something an object has | self.name |
Method | Something an object does | def bark(self): |
Inheritance | Child inherits from parent | class Cat(Animal): |
Encapsulation | Hide secret stuff inside a box | self.__balance |
Polymorphism | Same method, different behaviors | def speak() in many classes |
- Use PascalCase for class names (
class MyCar
) - Always use
self
inside classes โ it refers to the object - OOP is great for games, web apps, cybersecurity tools, and everything real-world
๐ฎ Think of classes as characters, attributes as stats, and methods as powers.
Master OOP and youโll code like a dev boss ๐ป๐
๐ File Handling + Modules & Packages Cheatsheet
Welcome, apprentice! In this scroll, youโll learn how to open files, write into them, and reuse code using modules & packages. Everything is explained simply, with examples. Let's begin! ๐ง
Think of a file like a notebook on your computer. You can open it, read what's inside, write something new, or add more stuff at the end.
file = open("example.txt", "r") # "r" means read mode
content = file.read() # Reads everything in the file
print(content) # Shows it on the screen
file.close() # Closes the file
๐งธ Imagine opening your storybook, reading it, and then closing it.
file = open("example.txt", "w") # "w" means write mode (starts fresh)
file.write("Hello, world!") # Writes this sentence inside the file
file.close() # Close the book after writing
๐ "w" deletes everything and starts clean like a new notebook.
file = open("example.txt", "a") # "a" means append (add)
file.write("\nNew line added!") # Adds new text on a new line
file.close()
๐ "a" is like turning to the next page and continuing the story.
with open("example.txt", "r") as file: # Open and name it 'file'
content = file.read() # Read the content
print(content) # Print it out
โ Using
with
makes sure your file is always closed โ even if there's an error.
with open("example.txt", "w") as file:
file.write("Safe writing with context manager")
with open("example.txt", "r") as file:
for line in file: # Go through each line one by one
print(line.strip()) # Print each line, but remove the '\n' newline
๐
strip()
removes invisible characters like extra spaces or newlines.
Mode | What It Means | Example |
---|---|---|
"r" | Read only | open("file.txt", "r") |
"w" | Write (erase) | open("file.txt", "w") |
"a" | Append | open("file.txt", "a") |
"x" | Create new | open("file.txt", "x") |
"b" | Binary | open("file.png", "rb") |
๐ค Combine them like
"rb"
(read in binary) or"wb"
(write in binary)
- Always use
with open(...)
โ safer and cleaner! - Use
"a"
to add stuff,"w"
to overwrite,"r"
to read. - Use
.strip()
to clean up text. - You can also use
os
andpathlib
for pro-level file tasks.
Imagine breaking your huge project into smaller magic scrolls (modules) and storing them inside chests (packages). Letโs learn how!
A module is just a .py
file that has code you want to reuse.
๐งช Example:
# math is a built-in module
import math
print(math.sqrt(16)) # โ 4.0
import random
print(random.randint(1, 10)) # โ a number between 1 to 10
๐ Now your app can roll virtual dice!
from math import sqrt, pi
print(sqrt(25)) # โ 5.0
print(pi) # โ 3.141592...
from random import choice
print(choice(["Sri", "Dukkie", "Ninja"])) # Picks one name randomly
๐ง
from
lets you import only what you need.
File: my_module.py
def greet(name):
return f"Hello, {name}!"
Another file: main.py
import my_module
print(my_module.greet("Sri")) # โ Hello, Sri!
๐ง You just created and used your own magic scroll!
A package is a folder with multiple modules and a special file called __init__.py
my_package/
โ
โโโ __init__.py
โโโ module1.py
โโโ module2.py
from my_package import module1
module1.function_name()
๐ Packages help organize related modules.
Type | Example | How to Use |
---|---|---|
Built-in | math , os |
Comes with Python |
External | flask , requests |
Install with pip |
pip install requests
๐งฐ External modules = advanced tools from Python community
import math
print(dir(math)) # โ Shows all math functions
print(help(math.sqrt)) # โ Explains what sqrt does
- Break code into smaller .py files
- Use
import
to reuse code again and again - Group related modules inside packages
- Use
pip
to install amazing external tools
โ
Reading, writing & appending to files
โ
Creating & importing modules
โ
Using Python packages
โ
Installing external tools with pip
๐ Now you're not just a coder... you're a Python Scrollkeeper ๐๐
Let me know what scroll to unlock next!