Welcome to this blog, where we will Learn to code Python from scratch. This blog will contain tutorials in the form of lessons, notes, and videos.
Learn to Code Python – Part 1 – Basics
๐ Section 1: What is Python and Programming?
๐ก Programming
Programming means giving step-by-step instructions to a computer to perform a task โ like telling a robot what to do.
๐ก Python
Python is a simple and powerful programming language used in web development, data science, automation, and more.
โ๏ธ Section 2: Setting Up Python
โ Step 1: Install Python
You need Python installed to write and run your code. Download it from python.org.
โ Step 2: Install VS Code
VS Code is a code editor where you write Python scripts. It makes coding easier with suggestions, error checks, and a terminal.
๐ง Section 3: Python Basics
๐ Data Types
Python has different types of data, just like real life:
| Type | Example | Python Name |
|---|---|---|
| Text | "hello" | str |
| Number | 24 | int |
| Decimal | 59.7 | float |
| True/False | True or False | bool |
๐ Variables
Variables are containers to store data.
name = "Kunal"
age = 24
is_married = False
Think of a cup holding water โ the cup is the variable, and the water is the data.
๐งช Section 4: Type, Input, and Conversion
๐ type() Function
This shows what type of data a variable has.
print(type(name)) # str
print(type(age)) # int
๐ Getting User Input
We can ask users questions and store their answers.
name = input("What is your name? ")
๐ Section 5: Data Conversion and F-Strings
๐ Type Conversion
Sometimes we need to change data from one type to another.
age = int(input("Enter your age: "))
๐ f-Strings
This is a cool way to write dynamic messages:
name = "Kunal"
age = 24
print(f"My name is {name} and I am {age} years old.")
๐งฎ Section 6: Lists and Operators
๐ Operators in Python
Operators are used to perform calculations:
| Symbol | Meaning | Example |
|---|---|---|
+ | Addition | 2 + 3 = 5 |
- | Subtraction | 5 - 2 = 3 |
* | Multiplication | 3 * 2 = 6 |
/ | Division | 6 / 3 = 2.0 |
// | Floor Division | 7 // 2 = 3 |
% | Modulus | 7 % 2 = 1 |
๐ Lists
A list is a collection that can store multiple values:
fruits = ["apple", "banana", "mango"]
print(fruits[0]) # apple
Lists can even store different data types.
๐ง Recap of What Youโve Learned in Part 1:
- What programming is and why Python is a great choice
- How to install Python and VS Code
- Variables and Data Types
- Checking data types using
type() - Taking user input
- Converting data types
- Using f-strings for clean output
- Working with lists and operators
Learn to Code Python – Part 2 – Operators
Welcome back, future Python masters! ๐ In Part 1 of our Python journey, we learned the basics โ variables, data types, user input, and printing values. Now, it’s time to unlock the real power of Python by mastering operators.
In this post, weโll break down operators step-by-step with simple examples, real-life analogies, and mini challenges to help you understand and apply them confidently.
๐ง What Are Operators?
Operators are symbols used to perform operations on values and variables.
Think of them like calculator buttons โ they help you do math, compare values, and more.
๐งฎ Lesson 1: Arithmetic Operators
Operators Covered: +, -, *, /
These are basic math operations used in almost every program.
x = 20
y = 4
print(x + y) # 24
print(x - y) # 16
print(x * y) # 80
print(x / y) # 5.0
๐ Output:
24
16
80
5.0
๐ข Lesson 2: Floor Division and Modulus
Operators Covered: //, %
//โ Returns only the whole number part (floor division)%โ Gives the remainder after division (modulus)
print(7 // 2) # 3
print(7 % 2) # 1
๐ Output:
3
1
๐ง Example: Sharing 7 chocolates with 2 friends โ each gets 3, and 1 is left.
โก Lesson 3: Power Operator
Operator Covered: **
Used for exponentiation โ multiplying a number by itself multiple times.
print(2 ** 3) # 8 (2ร2ร2)
print(5 ** 2) # 25 (5ร5)
๐ Output:
8
25
๐ฏ Try It: Calculate the cube of a number using **.
๐ค Lesson 4: Comparison Operators
Operators: ==, !=, >, <, >=, <=
These return True or False when comparing values.
a = 10
b = 20
print(a == b) # False
print(a < b) # True
๐ Output:
False
True
Use them in conditions โ like checking age for voting eligibility.
๐ฆ Lesson 5: Assignment Operators
Operators: =, +=, -=, *=, /=
These update variable values in short form.
x = 10
x += 5
print(x) # 15
x *= 2
print(x) # 20
๐ Output:
15
20
๐ Analogy: Like adding more food to your plate without changing plates.
๐ Lesson 6: Logical Operators
Operators: and, or, not
Used for combining conditions in if statements or filters.
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
๐ Output:
False
True
False
Logical AND (and)
| condition_1 | condition_2 | condition_1 and condition_2 |
|---|---|---|
| True | True | True |
| True | False | False |
| False | True | False |
| False | False | False |
Logical OR (or)
| condition_1 | condition_2 | condition_1 or condition_2 |
|---|---|---|
| True | True | True |
| True | False | True |
| False | True | True |
| False | False | False |
Logical NOT (not condition_1)
| condition_1 | not condition_1 |
|---|---|
| True | False |
| False | True |
Try this:
age = 18
is_student = True
print(age > 17 and is_student) # True
๐งฌ Lesson 7: Identity & Membership Operators
Operators: is, is not, in, not in
is: Checks if two variables point to the same object in memory.in: Checks if a value exists in a list, string, etc.
a = [1, 2, 3]
b = a
print(a is b) # True
print(2 in a) # True
๐ Output:
True
True
๐งฎ Lesson 8: Operator Precedence
Like BODMAS in math, Python follows an order of operations.
print(2 + 3 * 4) # 14
print((2 + 3) * 4) # 20
๐ Output:
14
20
๐ฏ Always use parentheses () to control execution order clearly.
โ Python Equivalent of PEMDAS
Python uses the same basic math precedence rules:
| PEMDAS | Python Equivalent | Example |
|---|---|---|
| P | () Parentheses | (2 + 3) * 4 โ 20 |
| E | ** Exponentiation | 2 ** 3 โ 8 |
| MD | *, /, //, % | 10 / 2 * 3 โ 15.0 |
| AS | +, - | 10 - 2 + 1 โ 9 |
๐ Note: Multiplication/Division and Addition/Subtraction are evaluated left to right, depending on which comes first.
๐งช Lesson 9: Mini Python Calculator (Project)
Letโs combine all your knowledge and build a simple calculator.
a = 10
b = 5
op = '*'
if op == '+':
print(a + b)
elif op == '-':
print(a - b)
elif op == '*':
print(a * b)
elif op == '/':
print(a / b)
๐ Output:
50
๐ฏ Try replacing op = '*' with other operators and see the results.
Learn to Code Python โ Part 3 – Conditions
Welcome back! In this chapter, weโll explore how Python makes decisions using conditional statements. These are essential when your program needs to choose between actions โ just like we do in real life.
๐น Lesson 1: Introduction to Conditional Statements
Think of conditional statements like making decisions in real life. For example:
“If I study, I will pass.”
In Python, we write:
marks = 80
if marks > 35:
print('You passed!')
๐ฅ๏ธ Output:
You passed!
๐น Lesson 2: if, else, elif in Action
Use if for one condition, else when itโs false, and elif for more choices.
marks = 70
if marks >= 90:
print('A Grade')
elif marks >= 60:
print('B Grade')
else:
print('Fail')
๐ฅ๏ธ Output:
B Grade
๐น Lesson 3: Nested Conditions
You can place one if inside another. Useful when one condition depends on another.
age = 20
has_id = True
if age >= 18:
if has_id:
print('Eligible')
๐ฅ๏ธ Output:
Eligible
๐น Lesson 4: Logical Operators in Conditions
Use and, or, not to combine conditions in one line.
age = 22
has_pass = True
if age > 18 and has_pass:
print('Allowed')
๐ฅ๏ธ Output:
Allowed
๐น Lesson 5: assert Statement
assert is like saying: โThis better be true!โ Itโs used to catch bugs.
age = 25
assert age > 0, 'Age must be positive'
print('Age is valid')
๐ฅ๏ธ Output:
Age is valid
๐น Lesson 6: return Statement
Used inside a function to send a value back.
def is_even(n):
return n % 2 == 0
print(is_even(10))
๐ฅ๏ธ Output:
True
๐น Lesson 7: pass Statement
pass means โdo nothing.โ It helps when writing code youโll fill in later.
def check():
pass
print('Function defined')
๐ฅ๏ธ Output:
Function defined
๐น Lesson 8: break and continue in Conditions
breakexits the loopcontinueskips the current step
for i in range(5):
if i == 3:
break
print(i)
๐ฅ๏ธ Output:
0
1
2
๐น Lesson 9: else with Loop
Python allows else after loops. It runs only if loop ends normally (not broken).
for i in range(3):
print(i)
else:
print('Done!')
๐ฅ๏ธ Output:
0
1
2
Done!
๐น Lesson 10: ๐งช Mini Project โ Smart Checker System
Letโs bring everything together!
def check_user(name, age, has_id):
assert age > 0, 'Invalid age'
if age >= 18:
if has_id:
return f'{name} is eligible โ
'
else:
return 'ID required โ'
else:
return 'Not eligible โ'
print(check_user('Kunal', 20, True))
๐ฅ๏ธ Output:
Kunal is eligible โ
๐ Bonus Lessons for Part 3: Loops & Range (Python Flow Control)
Letโs now explore how Python repeats actions using loops โ these go hand-in-hand with conditional logic!
๐น While Loop
The while loop keeps running as long as a condition is True.
count = 1
while count <= 3:
print("Count:", count)
count += 1
๐ฅ๏ธ Output:
Count: 1
Count: 2
Count: 3
It stops when the condition becomes False (
count > 3).
๐น For Loop with Range
The for loop is used to run a block of code a certain number of times โ often with range().
for i in range(5):
print("i =", i)
๐ฅ๏ธ Output:
i = 0
i = 1
i = 2
i = 3
i = 4
๐ธ range(5) means: start at 0, stop before 5.
๐น For Loop with Custom Range
You can customize the start, stop, and step values:
for i in range(1, 10, 2):
print(i)
๐ฅ๏ธ Output:
1
3
5
7
9
๐น Infinite Loop (Be Careful!)
If you forget to change the condition in a while loop, it can go on forever!
# Uncommenting below will create an infinite loop
# while True:
# print("I won't stop!")
Use Ctrl+C to stop in terminal or reboot kernel in notebooks.
๐น While-Else Block
else runs only when the while condition becomes False.
x = 0
while x < 3:
print(x)
x += 1
else:
print("Loop finished!")
๐ฅ๏ธ Output:
0
1
2
Loop finished!
These loop concepts fit naturally under flow control and conditional logic. They help students understand repetition based on condition, not just one-time decisions.
Learn to Code Python – Part 4 – Strings
Welcome to Part 4 of your Python journey! In this part, we will master how Python handles text using strings โ one of the most important data types.
๐ 1. What is a String?
A string in Python is simply a collection of characters inside quotes. You can use:
- Single quotes
' ' - Double quotes
" " - Triple quotes
''' '''or""" """(for multi-line text)
name1 = 'John'
name2 = "John"
name3 = '''John'''
print(name1, name2, name3)
๐ฅ๏ธ Output:
John John John
๐ข 2. String Indexing (Positive & Negative)
Each character has a position (called an index):
- Starts from 0 (left to right)
- Starts from -1 (right to left)
text = 'Python'
print(text[0]) # First character
print(text[-1]) # Last character
๐ฅ๏ธ Output:
P
n
๐ 3. Iterating Through a String
You can loop through strings like a list!
word = 'Hi'
for letter in word:
print(letter)
๐ฅ๏ธ Output:
H
i
๐ 4. String Length & Slicing
len()gives number of characters- Slicing extracts part of the string using
[start:stop]
text = 'Hello World'
print(len(text)) # Length
print(text[0:5]) # Slice from index 0 to 4
๐ฅ๏ธ Output:
11
Hello
๐ 5. Repeating and Concatenating Strings
You can:
- Multiply strings using
* - Add (join) strings using
+
print('Hi' * 3)
print('Hello' + ' ' + 'World')
๐ฅ๏ธ Output:
HiHiHi
Hello World
๐ 6. Membership Operator in Strings
Check if a substring exists inside a string using in:
print('Py' in 'Python')
print('Java' in 'Python')
๐ฅ๏ธ Output:
True
False
๐ 7. Changing Case (Upper/Lower)
Python has many built-in functions to change text case:
text = 'hello PYTHON'
print(text.lower()) # All lowercase
print(text.upper()) # All uppercase
print(text.title()) # Title Case
print(text.capitalize()) # Capitalize first letter
print(text.swapcase()) # Swap cases
๐ฅ๏ธ Output:
hello python
HELLO PYTHON
Hello Python
Hello python
HELLO python
๐ 8. Finding and Replacing Text
Use find() to locate a word and replace() to change it:
text = 'hello python'
print(text.find('python'))
print(text.replace('python', 'world'))
๐ฅ๏ธ Output:
6
hello world
๐ 9. Splitting and Joining Strings
split()converts a string into a listjoin()combines list elements into a string
text = 'a,b,c'
print(text.split(','))
print('-'.join(['a', 'b', 'c']))
๐ฅ๏ธ Output:
['a', 'b', 'c']
a-b-c
๐งช 10. Checking Whatโs Inside (alpha/digit/alnum)
Python provides functions to check string content:
print('abc'.isalpha()) # Only alphabets?
print('123'.isdigit()) # Only numbers?
print('abc123'.isalnum()) # Alphabets + Numbers?
๐ฅ๏ธ Output:
True
True
True
๐ฏ 11. Startswith and Endswith
Used to verify the start or end of a string:
text = 'hello world'
print(text.startswith('hello'))
print(text.endswith('world'))
๐ฅ๏ธ Output:
True
True
๐ Final Words
Youโve just unlocked the power of text manipulation in Python! Strings help us build websites, apps, AI tools, and more.
Learn to Code Python – Part 5 – List, Tuple & Dictionary
Welcome to Part 5 of your Python journey! Today, weโll explore the three essential data containers in Python: list, tuple, and dictionary. Each has its own superpower โ and by the end of this post, you’ll know when and how to use them.
๐ข LISTS: []
โ Key Features of Lists
- Ordered โ elements keep their position.
- Mutable โ change items after creation.
- Dynamic โ grow or shrink as needed.
- Heterogeneous โ can store any data types.
โ๏ธ How to Create a List
a = [1, 2, 3] # Using square brackets
b = list("abc") # Using list() constructor
empty = list() # Empty list
๐ง Basic List Operations
a[1] = 99 # Update
c = a + [4, 5] # Concatenate
d = [0] * 3 # Repeat
print(3 in a) # Membership
๐ Aliasing vs Copy:
e = a # Aliased (both point to same)
f = a.copy() # Independent copy
๐ Useful List Functions
len(a), min(a), max(a), sum(a)
๐ ๏ธ Common List Methods
a.append(10) # Add at end
a.extend([20, 30]) # Add multiple
a.insert(1, 'X') # Insert at index
a.remove('X') # Remove specific item
a.pop() # Remove last item
a.clear() # Empty the list
๐ Searching and Counting
a.index(10) # First position of value
a.count(99) # Number of times 99 appears
๐ช Sorting and Reversing
a.sort() # Ascending order
a.reverse() # Reverse in-place
๐ Slicing, Common Elements, Range, and List Comprehension
first3 = a[:3]
common = [x for x in a if x in b]
r = list(range(1, 6)) # [1, 2, 3, 4, 5]
๐งฉ Nested Lists & Flattening
matrix = [[1, 2], [3, 4]]
flat = [n for row in matrix for n in row]
๐ง TUPLES: ()
โ Key Features of Tuples
- Immutable โ can’t change after creation.
- Ordered & Heterogeneous โ just like lists, but read-only.
โ๏ธ Creating Tuples
t = (1, 2, 3) # Basic
t2 = 4, 5 # Parentheses optional
single = (42,) # Note the comma!
๐ Accessing Tuple Elements
t[1]
len(t)
min(t), max(t)
๐ง Limited Tuple Methods
t.index(2) # Position of 2
t.count(1) # Count of 1
๐ก Tip: To update a tuple, convert it to a list, edit it, then convert back:
lst = list(t)
lst.append(9)
t = tuple(lst)
๐ง DICTIONARIES: {}
โ Key Features of Dictionaries
- Ordered (Python 3.7+)
- Mutable & Dynamic
- Heterogeneous โ flexible keys and values
โ๏ธ Creating Dictionaries
person = {"name": "Ana", "age": 22}
d2 = dict(zip("abc", [1, 2, 3]))
empty = {}
โ Adding and Updating
person["city"] = "Pune" # Add new key
person.update(age=23) # Update value
๐ Reading Values
name = person["name"] # Direct access
phone = person.get("phone") # Safe access
๐๏ธ Getting Keys, Values, Items
keys = list(person.keys())
vals = list(person.values())
items = list(person.items())
โ Deleting Items
person.pop("age") # Remove by key
pair = person.popitem() # Last item
person.clear() # Empty dict
๐ Looping Through a Dictionary
for key, value in person.items():
print(key, value)
๐ง Dictionary Comprehension & Nesting
squares = {x: x**2 for x in range(4)} # {0:0, 1:1, ...}
nested = {
"emp1": {"name": "Ana"},
"emp2": {"name": "Ben"}
}
๐ฏ Final Thoughts
| Data Type | When to Use |
|---|---|
List [] | Ordered collection of items, when you need to modify data |
Tuple () | Fixed group of items, used for read-only or secure data |
Dict {} | Key-value pairs for structured or labeled data |
Mastering these 3 data types will help you solve 80% of Python problems in real-world scenarios.
Learn to Code Python – Part 6 – Functions
Welcome to Part 6 of your Python journey! This chapter introduces you to functions โ the backbone of clean, modular, and reusable code.
๐ 1. What is a Function?
A function is a block of code that performs a specific task. You write it once and use it many times.
โ Key Features:
- Reusability โ No need to repeat the same code.
- Modularity โ Break big programs into manageable parts.
- Scoping โ Controls which variables are visible inside/outside.
โ Advantages:
- Clean and organized code.
- Easier to debug and maintain.
- Reuse without retyping.
โ Disadvantages:
- Requires extra thinking to structure logic.
- Too many functions can make simple scripts hard to trace.
๐ ๏ธ 2. How to Create a Function
Use the def keyword to define a function.
def greet():
print("Hello from a function!")
greet()
๐ฅ๏ธ Output:
Hello from a function!
๐ฏ 3. Parameters vs Arguments
- Parameters are variable names used in the function definition.
- Arguments are actual values passed when calling the function.
def welcome(name): # name = parameter
print(f"Hi {name}")
welcome("Ana") # "Ana" = argument
๐ฅ๏ธ Output:
Hi Ana
๐งฉ 4. Types of Arguments
โ Positional Arguments (Default way)
Values are matched by position.
def add(x, y):
print(x + y)
add(2, 3) # 2 is x, 3 is y
โ Keyword Arguments
You specify which value goes to which parameter.
add(x=5, y=10)
โ Default Arguments
You assign default values in case none are passed.
def greet(name="Guest"):
print("Hello", name)
greet() # Uses default
greet("John") # Overrides
๐ 5. return Statement
Use return to send back a value from the function.
def square(n):
return n * n
result = square(4)
print(result)
๐ฅ๏ธ Output:
16
๐ return vs print
print() | return |
|---|---|
| Displays the result | Gives the result |
| Temporary output | Used for further logic |
| For humans | For computers |
๐ 6. Local vs Global Variables
๐น Local Variable
Defined inside a function โ not accessible outside.
def test():
x = 10 # local
print(x)
test()
# print(x) โ Error
๐น Global Variable
Defined outside and accessible inside functions.
x = 50
def show():
print(x) # accesses global x
show()
๐ธ Modifying Global Variable
Use the global keyword:
count = 0
def increment():
global count
count += 1
increment()
print(count)
๐ 7. Decorators (Beginner View)
A decorator modifies the behavior of a function without changing its code.
def decorator_func(func):
def wrapper():
print("Before function")
func()
print("After function")
return wrapper
@decorator_func
def say_hello():
print("Hello!")
say_hello()
๐ฅ๏ธ Output:
Before function
Hello!
After function
โ๏ธ 8. Generators (Efficient Loops)
Generators generate values one by one using yield instead of return.
def countdown(n):
while n > 0:
yield n
n -= 1
for i in countdown(3):
print(i)
๐ฅ๏ธ Output:
3
2
1
Generators save memory and are perfect for large datasets.
๐ Conclusion
Functions make your code:
- Reusable with
def - Flexible with arguments
- Powerful with decorators & generators
They are the heart of Python programming, and every great script uses them!
Learn to Code Python – Part 7 – Object-Oriented Programming (OOP)
Welcome to Part 7 of your Python journey! This chapter introduces you to Object-Oriented Programming (OOP) โ a powerful way to structure and organize your code.
Letโs break it down in the most beginner-friendly way possible.
๐ง 1. What is OOP and Why Do We Need It?
OOP (Object-Oriented Programming) is a method of programming where we build reusable code using classes and objects.
โ Why Use OOP?
- Modularity โ Keep code clean and structured
- Reusability โ Use the same class multiple times
- Encapsulation โ Protect data inside objects
- Scalability โ Easier to maintain large codebases
โ๏ธ 2. Core OOP Concepts
| Concept | Description |
|---|---|
| Class | Blueprint for creating objects |
| Object | Instance created from a class |
| Attributes | Variables inside the object |
| Methods | Functions inside the class that perform actions |
๐งฉ 3. Evergreen OOP Template in Python
Here is the general structure you can use for creating any class in Python:
# Step 1: Define the class
class ClassName:
def __init__(self, param1, param2):
self.param1 = param1 # Attribute 1
self.param2 = param2 # Attribute 2
def method1(self):
# action or logic here
pass
def method2(self, arg):
# action using argument
return arg
๐ Understanding the Template
| Part | What It Does |
|---|---|
class ClassName: | Creates a new class (blueprint) |
__init__ | Constructor method to initialize attributes |
self.param1 | Instance variable (attribute) |
def method1() | A method that belongs to the class |
pass / return | Placeholder or actual logic |
self | Refers to the current object itself |
โ How to Use the Template
# Step 2: Create objects from the class
obj1 = ClassName("value1", "value2")
# Step 3: Access methods and attributes
print(obj1.param1)
result = obj1.method2("input")
๐ฏ Summary
Now you know the basic structure of OOP in Python! You can check this Blog to Learn OOP in very Detail.
Youโve learned:
- What OOP is and why itโs useful
- The meaning of class, object, attributes, and methods
- A clean, evergreen OOP template you can reuse forever
๐งช In future parts, weโll explore advanced OOP features like inheritance, encapsulation, and polymorphism. But for now, youโve got the foundation.

