Skip to content

SriramBharath-7/python-scrolls

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

13 Commits
ย 
ย 
ย 
ย 

Repository files navigation

Python Coding



๐Ÿ“‚ Python Basics Cheatsheet

๐Ÿ Python Basics Cheatsheet

๐Ÿš€ Master the essentials of Python โ€“ your gateway to automation, web dev, data science, and beyond.


๐Ÿง  Python Syntax Overview

# 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 and Data Types

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 and Output

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

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

Control flow means making decisions and repeating stuff.

โœ… Conditional Statements:

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:

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

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 named greet
  • return gives back the result
  • You can reuse the function as many times as you want!

๐Ÿ“š Lists and Loops

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

๐Ÿงฐ Common Built-in Functions

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]

๐Ÿ’ก Tips

  • 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

๐Ÿงฑ 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!


๐Ÿงบ 1. Lists (A basket that holds items in order โ€” and you can change them!)

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

๐Ÿ” Loop through list (Look at each item one by one)

for fruit in fruits:
    print(fruit)

๐Ÿงธ This prints each fruit one by one like:

apple  
grape  
mango  
orange  

๐Ÿ“š 2. Tuples (A list you can't change โ€” like a locked box)

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)


๐Ÿ—ƒ๏ธ 3. Dictionaries (A label-sticker box: each item has a name and a value)

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"

๐Ÿ” Loop through dictionary (Check all labels and values)

for key, value in person.items():
    print(key, value)

๐Ÿงธ Output:

name Sri  
age 18  
city Chennai

๐Ÿ”ข 4. Sets (A magic bag with only unique things โ€“ no duplicates allowed!)

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

๐Ÿ“Š Summary Table

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}

๐Ÿง  Pro Tips

  • โœ… 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

๐Ÿงฑ Python OOP (Object-Oriented Programming) 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! ๐Ÿงฑ


๐Ÿงฌ 1. What is a Class?

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.


๐Ÿพ 2. What is an Object?

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!


๐ŸŽ’ 3. Attributes (What an object has)

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 object
  • self is the object itself (think: โ€œthis dogโ€)
  • self.name and self.age are like labels on that specific dog

๐ŸŽฏ 4. Creating an Object (Using the class)

dog1 = Dog("Bruno", 3)
print(dog1.name)  # Bruno
print(dog1.age)   # 3

Now Bruno is your first dog. You can make more dogs too!


โš™๏ธ 5. Methods (What an object can do)

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!

๐Ÿ‘ช 6. Inheritance (Like getting traits from your parents!)

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

๐Ÿงฑ 7. Encapsulation (Keep details private!)

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

๐Ÿ” 8. Polymorphism (Same word, different behavior)

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!

๐Ÿง  Summary Table

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

๐Ÿ’ก Pro Tips for OOP

  • 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

๐Ÿ Python Scrolls โ€” File Handling + Modules & Packages (Beginner Ninja Guide)

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! ๐Ÿง 


๐Ÿ“ Python File Handling โ€” Read, Write, Append Like a Pro!

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.


๐Ÿ“– How to Open and Read a File

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.


โœ๏ธ How to Write to a File

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.


โž• How to Add More (Append)

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.


๐Ÿงผ Best Practice โ€” Use with (Auto-Close)

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")

๐Ÿ” Read File Line by Line

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.


๐Ÿ“‹ File Modes Cheat Table

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)


๐Ÿง  File Handling Tips

  • 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 and pathlib for pro-level file tasks.

๐Ÿ“ฆ Python Modules & Packages โ€” Code Reusability Superpower

Imagine breaking your huge project into smaller magic scrolls (modules) and storing them inside chests (packages). Letโ€™s learn how!


๐Ÿ“ What Is a Module?

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

๐ŸŽฒ Random Module Example

import random
print(random.randint(1, 10))  # โžœ a number between 1 to 10

๐ŸŽ‰ Now your app can roll virtual dice!


๐ŸŽฏ Use from ... import to Be More Specific

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.


๐Ÿงฐ Make Your Own Module

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!


๐Ÿ“ฆ What is a Package?

A package is a folder with multiple modules and a special file called __init__.py

my_package/
โ”‚
โ”œโ”€โ”€ __init__.py
โ”œโ”€โ”€ module1.py
โ””โ”€โ”€ module2.py

๐Ÿ“ฆ Use a Module from a Package

from my_package import module1
module1.function_name()

๐ŸŽ’ Packages help organize related modules.


๐Ÿ” Built-in vs External 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


๐Ÿง  Pro Tools โ€” Explore Like a Curious Kid

import math
print(dir(math))       # โžœ Shows all math functions
print(help(math.sqrt)) # โžœ Explains what sqrt does

๐Ÿง  Module & Package Tips

  • 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

๐ŸŽ‰ Youโ€™ve Mastered:

โœ… 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!

About

Python projects & cheat sheets for daily mastery

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published