Welcome to our Complete Python Programming Course — your one-stop destination to master Python from the basics to advanced concepts!
In this course, we cover all essential Python topics in a simple, easy-to-understand way. To make your learning more interactive and effective, we’ve introduced two powerful tools:
CodeFlow Visualizer
Our unique CodeFlow Visualizer helps you trace Python code line by line with live explanations. By executing the code, you can visually see how your program flows, along with clear explanations for each line of code.
CodeFlow Visualizer: Demo
Python Code
1
1
def add():
2
2
a = 5
3
3
b = 6
4
4
c = a + b
5
5
print(c)
6
6
7
7
add()
Click "Execute" to start.
Program Output
Output appears here...
This tool is designed to improve your understanding of program logic and execution flow.
CodeAssist AI Compiler
Learn smarter with our AI-powered CodeAssist Compiler! You can:
Write, Execute, and Debug Python code in real-time.
Use the Debug option to let AI analyze your code, identify problems, suggest solutions, and provide detailed explanations.
This means you’re not just writing code — you’re learning to solve coding problems efficiently with instant AI guidance!
Previous
Next: Python Language Uses
Python Language Uses
Lesson 1
Let's start with a simple question: Why is Python the most popular and most used programming language in recent years? The reason is pretty clear. Python has a simple syntax. You'll see, it's really easy to write and read code in Python. That's something many students love!
What I want is for you to understand that Python is a flexible programming language. This means you can use it for all sorts of things—like web development, game development, artificial intelligence, machine learning, and automation. Python can also help with cybersecurity. Based on these possibilities, you can even use Python for multiple domains without having to learn a new programming language every time.
Python is platform independent - it works on any operating system. We'll talk more about what platform independent means later.
Key Features
Simple Syntax: Easy to write and read code
Flexibility: Suitable for web development, AI, automation, and more
Object-Oriented: Built using object-oriented programming principles
Extensive Libraries: Includes NumPy, pandas, and Flask for various tasks
Who and When was Python Created
Mr. Guido van Rossum developed Python. In 1989, he was working at a company called CWI in the Netherlands. His company gave him a new project: develop an operating system using C programming language. He and his team got stuck because C's syntax was too complex. After taking a break, Guido decided to build his own programming language—with simple syntax and platform independence.
Finally he developd his own programming language and ready to publish.His next task is to set name for his programming language. Guido was thinking of multiple names but couldn't settle on one. He turned on his TV and watched his favorite show, Monty Python's Flying Circus. He got inspired and finally named his language "Python." He published Python in 1991.
Keep this in mind: Python is simple, flexible, and powerful, and you can use it anywhere!
Previous
Next: Binary Language Basics
Binary Language Basics
Lesson 2
We all know computers understand only zeros and ones. But do you know why? Let’s understand.
First, let’s understand three key components of our computer: CPU (microprocessor), hard disk, and RAM.
CPU (Microprocessor)
The first part is our microprocessor, the CPU.
It’s built using semiconductor technology. You don’t have to know everything about it—just remember, inside the CPU there are crores and crores of nano transistors. Hope I am clear.
Each transistor operates using voltages. Each transistor acts like an on and off switch, just like a fan switch or a light switch. When I give low voltage to the transistor, the switch is off, and the microprocessor reads this as a zero. When I give high voltage, the switch is on, and the microprocessor reads it as a one. Hope I am clear.
So, what I want is for you to see how we communicate with the computer: by giving high and low voltages to transistors, and the CPU reads these on and off signals as 0s and 1s. Keep this in mind.
RAM (Random Access Memory)
Next, let’s talk about RAM. RAM is a temporary storage device that also uses semiconductor technology, just like the CPU. But here, we have crores of nano capacitors instead of transistors. Each capacitor can store voltage. If I store low voltage, the microprocessor reads it as zero. If I store high voltage, it reads as one. Hope I am clear on that.
Hard Disk Storage
Now, let’s understand the hard disk. The hard disk uses a totally different method called magnetic field pattern technology to store data. With this method, the hard disk works as a permanent storage device. Using magnetic patterns, data is stored as zeros and ones.
You may wonder—if both RAM and the hard disk are storage devices, why is RAM temporary and the hard disk permanent? Let’s understand why.
RAM uses capacitors and depends completely on voltage. If you disconnect the voltage, any data stored in RAM gets deleted. That’s why RAM is called volatile—it loses data when there’s no power. Hard disk, on the other hand, uses magnetic patterns to store data. Even if you disconnect the power, the data stays safe.
Hope I am clear. That’s it for this video. Now you have some answers about why computers use zeros and ones.
Python Overview
Next: High-Level Languages
High Level Languages
Lesson 3
We all already understand why and how computers read zeros and ones—but that’s all at the machine level. Now you might wonder, how does a computer understand high-level languages? Let’s understand how.
First, let’s understand what a compiler is. It’s software. To compile and execute any programming language on your computer, you need to install a compiler. Only with the compiler installed can you compile and execute programs. Hope I am clear.
What I want is for you to get this: A compiler like Eclipse converts high-level language into machine-level code. Then, the microprocessor reads this machine-level code and gives you the output.
So, the compiler’s role is all about converting high-level language code into machine code. This step is called the “compilation process.” When you run the program and see output, that’s the “execution process.” Keep this in mind—we’ll use these words again.
Why Python is High Level language
Let’s understand what a high-level language means. Python, Java, C++, and JavaScript are all high-level languages. Why? Because humans can read and write these languages easily. If you take a low-level language, you can’t easily read or write it as a normal person.
With Python, Java, or C++, anyone can quickly understand and write code. The compiler helps convert this readable code into something the computer can understand.
But for low-level languages, the compiler doesn’t work the same way. Back in the day, they used something called assembler software to convert languages like assembly language (used before the 1950s) into machine code. While compiler is for high-level languages, assembler is for low-level languages.
Hope I am clear so far.
Is Python Platform Independent
Now, let’s understand platform independence. We say Python is platform independent, but what does that really mean?
There are three main operating systems: Windows, Mac, and Linux. Imagine Harish writes and compiles a Python program on his Windows computer. If that same program can be executed on Mac or Linux without modification, then we call Python platform independent. You can learn more about GNU/Linux, a popular operating system.
But now, let’s see a platform dependent case. Imagine you write and compile a C or C++ program on Windows. You can’t execute that same program on Mac or Linux—you can only run it on Windows. That’s what platform dependent means. Keep this in mind.
So, Python is platform independent because a compiled Python program can run on any operating system, like Windows, Mac, or Linux. This isn’t the case with C or C++.
How does Python achieve this? When Mr. Guido van Rossum developed Python, he also introduced the Python interpreter. If you want to compile and execute a Python program, you just need to install the Python interpreter. Based on the address where you write, compile, and execute, the interpreter takes care of platform independence.
Binary Language Basics
Next: Understanding Variables
What is Object in Python
Lesson 4
We've already seen the key features of Python. What I want is for you to remember: Python has a simple syntax, it's flexible, object-oriented, platform independent, and has extensive libraries.
In this lesson, I'm going to talk about object-oriented programming—what it means when we say Python is an object-oriented language.
As a programmer, you need to view everything as an object. You see, my light is an object, my computer is an object, even my cat is an object. The world is really just a collection of objects, especially when we think like programmers.
Object State and Behavior
Now, when you look at something as an object—let's take a car for example—you get two main parts: state and behavior.
Let's understand what those mean. Say, you take a car as an object. The car's state includes things like the brand, price, mileage, and color. These are called the state because they're basically data—the kind we store in RAM or the hard disk while running our program.
Behavior, on the other hand, is about what the object can do. For our car, behaviors are starting the car, accelerating, and braking.
If I take my cat as an object, the breed, name, age, and color of my cat are the state. My cat can eat and walk—these are the behaviors.
Hope I am clear. Now, keep this in mind: states are considered as variables and behaviors are considered as functions.
Example: Car State
Let's write a simple program using just the states—so, variables only.
CodeFlow Visualizer: Variable Assignment
This visualizer shows how we represent object states as variables in Python:
Python Code
Ready
1
1
brand = "Tesla"
Created variable: brand = "Tesla"
2
2
price = 20000
Created variable: price = 20000
3
3
mileage = 100
Created variable: mileage = 100
4
4
print(brand, price, mileage)
Using variables: brand, price, mileage
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here after execution...
When you execute the code above, you'll see the output: Tesla 20000 100.
So, the state of every object is represented as variables in the code. This is just the introduction to object-oriented programming in Python. In the next lesson, we'll get deeper into OOP concepts and see how to work with both variables and functions in real Python programs.
In this lesson, I’m going to talk about the difference between compiler and interpreter. You see, to execute a Python program on your computer, you must install the interpreter first. Only then can you run your Python code.
Understanding Compilers
Let’s understand compilers first. Imagine you have a program with 10 lines of code. When you use a compiler and execute your code, the compiler processes all 10 lines in a single go. It takes the whole program, executes all lines at once, and gives you machine level code. Your microprocessor then reads this machine code and produces the output.
Understanding Interpreters
Now, let’s understand interpreters. If you use an interpreter, it works differently—it executes your code line by line. First, it executes the first line. Then it moves to the second line, then the third, and so on. The interpreter runs every line one after the other, step by step.
Hope I am clear—the main difference is that the compiler runs all code in one go, while the interpreter works through code line by line.
Keep this in mind: Interpreter execution is slower compared to compiler. So, compilers are generally faster than interpreters when running code.
That’s it for this lesson.
In the next lesson, I’ll show you how to install the Python interpreter and the Spyder IDE. Let’s move on and get ready to execute your own Python programs!
Previous: Object Basics
Next: Install Spyder IDE
Install Spyder IDE
Lesson 6
In the last lesson, we saw that if you want to run Python on your computer, you first need to install the Python interpreter. Let’s understand how to do that.
Installing the Python Interpreter
First, open your browser and search for “Python interpreter.” Then click on the python.org website. You’ll see a “Download Python” button—click it. This will download the Python launcher.
Once downloaded, open the Python launcher and start the installation. If you’re using a Mac or Linux, you’ll find the right link on the same page. Hope I am clear.
Don’t forget—check the box that says “Add python.exe to PATH.” Then, click the “Install Now” button.
The installation takes a few minutes. After it’s done, let’s double check if Python is installed.
Verifying the Installation
Open your CMD (the command prompt) on your computer. Just type the command:
python
and press Enter. If you see something like “python 3.13 version installed,” you know it’s done right.
Running Your First Program
Let’s write our first simple program. I’m going to use the print function to print a message. You need to put the message inside double quotes within the print function.
CodeFlow Visualizer: Print Statements
Visualize how print() statements work in Python:
Python Code
Ready
1
1
print("hello world")
Prints the string "hello world" to the output.
2
2
print("I am")
Prints the string "I am" to the output.
Click "Execute" to start. Use navigation buttons to step through each print statement.
Program Output
Output will appear here...
If you want to print anything—like a message or variable—you must use the print function, and the message should be inside double quotes.
Other Ways to Run Python
Now what I’m going to do is show you other ways to run Python programs. You can use an online interpreter. Go to your browser and search for “Python online interpreter.” You’ll find many options.Try it anyone. Try writing and running your code right away at 👉 https://codersnote.com/ai-powered-code-compiler/
Installing Spyder IDE
Next, I’m going to install the Spyder IDE. Make sure to search for “Spyder” (the spelling is s-p-y-d-e-r, not spider). Click the download page, and the site will detect your operating system to offer the right downloads. You can learn more about Spyder from its official documentation.
Once downloaded, install Spyder by clicking “Next,” then “I agree,” and then “Install.” After that, Spyder IDE will be ready to use on your computer.
In the next lesson, we’ll talk about the print function in detail and see more examples. Let’s continue to the next lesson!
Previous: Compiler vs Interpreter
Next: Variable Usage
Variable Usage
Lesson 7
In the last lesson, I showed how to install the Python interpreter and run Python programs on your computer. If you had any trouble, just let me know—I'm here to help. Now, let’s jump in!
This lesson is about how to create a variable, assign a value to it, and see what happens behind the scenes when you run your program.
To show you an example, I want to print my age. I create a variable called age and assign the value 27 to it using the assignment operator (the equal sign). Then, I use the print function to print the age variable.
CodeFlow Visualizer: Integer Variable & Print
Visualize how an integer variable is assigned and then printed in Python:
Python Code
Ready
1
1
age = 27
Assigning integer 27 to variable age.
2
2
print(age)
Printing the value of variable age.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
You see, this equal sign "=" is called the assignment operator in Python. What I want is to assign the value 27 to the variable named age. Then, using print, I display the value.
How Program Execution Happens
Let’s understand how program execution happens in the back end. I’ll write another simple program. If you see, I’m printing a variable a that has the value 12.
a = 12
print(a)
Now imagine Harish is running this on his computer with 8GB RAM. Maybe Chrome, Netflix, YouTube, and another coding site are already open, taking up about 5GB—so 3GB RAM is free.
When Harish executes this Python program, the Python interpreter starts and allocates some memory space in the RAM for the program. In this space, you’ll find four segments: code segment, stack segment, heap segment, and static segment.
The Code, Stack, and Heap Segments
First, let’s understand the code segment. Whatever program you write—even if it’s 100 lines or a thousand—the program itself gets stored in the code segment.
Now for the stack and heap segments. When you run your program, the Python interpreter’s cursor first goes to the right side of the assignment operator. So, for a = 12, the cursor first finds 12. This value 12 gets stored in the heap segment, and Python gives it a random address (for example, 101—just for understanding).
Next, the cursor moves to the left side to look at the variable a. In the stack segment, Python reserves a little space for a and links it to the value stored at address 101. Based on the address, Python knows which variable points to which value. This is how the stack and heap segments work together during program execution.
About the static segment—we’ll discuss that in upcoming lessons, after we cover some more basics. So, stay tuned!
Previous: Install Spyder IDE
Next: Data Types Overview
Data Types Overview
Lesson 8
In this lesson, I'll talk about the four basic data types you’ll use a lot in Python: integer, float, string, and boolean. Let’s understand them one by one.
Basic Data Types
Integer (int): Numbers like 10, 10000, or 10 lakh are all integers.
Float (float): These are real numbers with point values like 99.9, 10.2, or 2000.1.
String (str): Any characters, words, or even "Harish" and "A", are strings.
Boolean (bool): These are yes/no types, meaning True or False.
Let’s write some code to see these in action.
Python Code
# Integer data type
a = 12
print(a)
# Float data type
b = 99.9
print(b)
# String data type
c = "Harish"
print(c)
# Boolean data type
d = True
print(d)
Run Output
12
99.9
Harish
True
In Python, you don’t have to tell the computer what type your variable is. The Python interpreter automatically detects the type based on the value you assign. This is called dynamic typing and is different from languages like Java, where you must specify the data type.
Let’s use the type() function to check our variable types.
CodeFlow Visualizer: Python Data Types with `type()`
This visualizer demonstrates how different data types (integer, float, string, boolean) are assigned, printed, and their types explicitly identified using Python's `type()` function:
Python Code
Ready
1
1
a = 12
Created integer variable: a = 12
2
2
print(a)
Printing variable: a
3
3
print(type(a)) # Output: <class 'int'>
Printing the type of a.
4
4
b = 99.9
Created float variable: b = 99.9
5
5
print(b)
Printing variable: b
6
6
print(type(b)) # Output: <class 'float'>
Printing the type of b.
7
7
c = "Harish"
Created string variable: c = "Harish"
8
8
print(c)
Printing variable: c
9
9
print(type(c)) # Output: <class 'str'>
Printing the type of c.
10
10
d = True
Created boolean variable: d = True
11
11
print(d)
Printing variable: d
12
12
print(type(d)) # Output: <class 'bool'>
Printing the type of d.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
Previous: Variable Usage
Next: Collections Intro
Collections Intro
Lesson 9
Picture yourself in a coding interview. You’re asked to store and print five students' marks. How would you write your code? Try it out—open your compiler and give it a go!
What I want is for you to see that, if you use a separate variable and print statement for each student's mark, your code becomes long and inefficient. Imagine handling 500 or even 1,000 students this way—definitely not the best method.
Let’s see how you might start:
Python Code
# Not efficient for many students
mark1 = 10
mark2 = 20
mark3 = 30
mark4 = 40
mark5 = 50
print(mark1, mark2, mark3, mark4, mark5)
Run Output
10 20 30 40 50
You see, that works, but it isn’t efficient. You’re writing too many lines. If you just combine them into one print statement, the code is shorter, but still not ideal, especially if the list grows larger.
Advanced Data Types (Collections)
Now, let’s understand how advanced data types help. Python gives us list, tuple, set, and dictionary. Using these collections, you can do the same thing in just two lines!
List
First, let’s use a list. With a list, you store all the values in a single variable using square brackets []. Python also assigns index values to each element—starting from 0 (left to right) and -1 (right to left).
CodeFlow Visualizer: Python List Data Type
This visualizer demonstrates how a **list** is assigned in Python, its contents are displayed, and its type is identified using `type()`:
Python Code
Ready
1
1
marks = [10, 20, 30, 40, 50]
Created a list variable: marks.
2
2
print(marks)
Printing the list: marks.
3
3
print(type(marks)) # Output: <class 'list'>
Printing the type of marks.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
Here’s how you print a specific value using its index:
CodeFlow Visualizer: List Indexing
This visualizer shows how to access elements in a list using positive and negative indexes.
Python Code
Ready
1
1
marks = [10, 20, 30, 40, 50]
Created a list variable: marks.
2
2
print(marks[2]) # Outputs 30
Accessing element at positive index 2 (3rd element).
3
3
print(marks[-5]) # Also outputs 10 (because -5 is the first element)
Accessing element at negative index -5 (1st element from end).
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
Keep this in mind—indexing lets you fetch any value from the list directly.
Tuple
Next up is tuple. It’s similar to a list, but you use parentheses () instead of square brackets. Like lists, tuples use index values.
Python Code
Ready
1
1
scores = (10, 20, 30, 40, 50)
Created a tuple variable: scores.
2
2
print(scores)
Printing the tuple: scores.
3
3
print(type(scores)) # Output: <class 'tuple'>
Printing the type of scores.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
Set
Now, let’s look at set. A set is different. You use curly brackets {}, and the values come out unordered—so you can’t access them by index.
CodeFlow Visualizer: Python Set Data Type
This visualizer demonstrates how a **set** is assigned in Python, its contents are displayed, and its type is identified using `type()`. Remember, sets are unordered collections of unique elements.
Python Code
Ready
1
1
marks_set = {10, 20, 30, 40, 50}
Created a set variable: marks_set.
2
2
print(marks_set)
Printing the set: marks_set.
3
3
print(type(marks_set)) # Output: <class 'set'>
Printing the type of marks_set.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
If you try to print a value by its index, it doesn’t work for sets. That’s because set values are unordered, and Python stores them that way too. Hope I am clear on the difference!
Dictionary
Finally, let’s understand the dictionary data type. Imagine Harish wants to print the price of apple, orange, and banana. Using three variables is confusing when you want to remember which price goes with which fruit. What I want is a way to pair keys and values, like "banana": 80. You can do this with a dictionary—using curly brackets {} and separating a key and value with a colon.
CodeFlow Visualizer: Python Dictionary Data Type
This visualizer demonstrates how a **dictionary** is assigned in Python, its contents are displayed, and its type is identified using `type()`. Dictionaries are unordered (since Python 3.7, insertion order is guaranteed), changeable collections that store data in key-value pairs.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
With a dictionary, you can easily pair and print both key and value. This helps store and fetch data more clearly.
For more details on dictionaries, you can check out this
in-depth guide.
Keep this in mind—list and tuple use index values; set and dictionary use curly brackets,
but only dictionary gives you key-value access.
In the next lesson, you’ll get more practice with these data types and learn how to use them in real coding tasks. Stay tuned!
Previous: Data Types Overview
Next: Type Conversion
Type Conversion
Lesson 10
Our next topic is type casting, or type conversion. Both mean the same thing. Type casting is about changing a value from one data type to another.
To help you understand, imagine you’re converting a value from integer to float in Python—that’s type casting. Let’s see how this works in code.
First, let me show what’s not type casting:
Python Code
a = 10
b = a
print(b) # Output: 10
Run Output
10
Explanation:
The value 10 is first assigned to the variable a.
Then, b = a assigns the value of a to b, so b also becomes 10.
This is a basic variable-to-variable assignment — not type conversion.
Explicit Type Casting
Now, let’s see actual type casting. I’m going to convert an integer value to a float value. This is called explicit type casting—where you, the programmer, do the conversion using functions like float() or int().
CodeFlow Visualizer: Explicit Casting (int to float)
This visualizer shows how a programmer explicitly converts an integer to a float using the float() function. This is an example of **explicit type casting**.
Python Code
Ready
1
1
a = 10
Assigned integer 10 to a.
2
2
b = float(a)
Converted a (10) to float and assigned to b.
3
3
print(b)
Printing the value of b.
4
4
print(type(b)) # Output: <class 'float'>
Printing the type of b.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
Implicit Type Casting
There’s another kind called implicit type casting. Here, Python automatically converts the value without you doing anything. This usually happens during operations between different numeric types to avoid data loss.
This visualizer demonstrates how Python automatically handles operations between different numeric types, a process called **implicit type casting** or coercion. When an integer and a float are added, the integer is implicitly converted to a float, and the result is a float.
Python Code
Ready
1
1
a = 10
Assigned integer 10 to a. Type: int.
2
2
b = 8.6
Assigned float 8.6 to b. Type: float.
3
3
c = a + b
Adding an int (a) and a float (b). Python implicitly converts a to float (10.0 + 8.6). Result: 18.6.
4
4
print(c)
Printing the value of c.
5
5
print(type(c)) # Output: <class 'float'>
Printing the type of c.
Click "Execute" to start the visualization. Use the navigation buttons to step through each line of code.
Program Output
Output will appear here...
More Examples of Explicit Casting
Now let’s try converting a float value into an integer. This is explicit type casting again.
Python Code
# Float to Int Conversion
a = 9.6
b = int(a)
print(b) # Output: 9
print(type(b)) # Output: <class 'int'>
Run Output
9
<class 'int'>
Keep this in mind: When you convert float to int, you lose the point value (the decimal part is truncated, not rounded).
Let’s look at changing between strings and integers. If you assign a number in quotes, it's a string. You can convert this string to an int.
Python Code
# String to Int Conversion
a = "12"
print(type(a)) # Output: <class 'str'>
b = int(a)
print(type(b)) # Output: <class 'int'>
Run Output
<class 'str'>
<class 'int'>
Next, let’s try converting a string to a list, and then that list into a tuple. For more conversion examples, you can refer to this handy guide on type conversion.
Python Code
# Convert string to list
a = "harish"
b = list(a)
print(b) # Output: ['h', 'a', 'r', 'i', 's', 'h']
print(type(b)) # Output: <class 'list'>
# Convert list to tuple
c = tuple(b)
print(c) # Output: ('h', 'a', 'r', 'i', 's', 'h')
print(type(c)) # Output: <class 'tuple'>
Hope I am clear about what type casting or type conversion is. Remember, implicit (automatic) and explicit (programmer-directed) are the two types you need to know.
Previous: Collections Intro
Next: Input Handling
Input Handling
Lesson 11
In this lesson, I’m going to discuss the input function. Let’s understand with some simple code.
First, I’m going to create a variable called a and assign 10 to it. Then, I’ll print the value.
Python Code
# Static Assignment
a = 10
print(a) # Output: 10
Run Output
10
This prints 10, just as you’d expect. But what if I want a dynamic input—so the value can change each time, without me editing the code? Right now, if I want a different value, I need to go back, change a to 20, and run the code again.
Python Code
# Changing the Value Manually
a = 20
print(a) # Output: 20
Run Output
20
You see, every time I need a different value, I have to keep rewriting my program. That’s not efficient! What I want is a way to let the user type in a value while the program is running. That’s where the input() function comes in.
Using the input() Function
The input() function asks for user input from the output console. When Python runs the input() line, it pauses, waits for your input, and then assigns that input to the variable. You can also display a message to prompt the user.
Python Code
Ready
1
1
# Prompting for input
2
2
a = input("Enter a value: ")
3
3
print(a)
Code Explanation
Welcome to the Python Input/Output Visualizer! Enter any value above and click "Execute" to begin.
You'll be able to step through the code execution to understand how input and output work in Python.
Step: 0/3
Status: Ready
Program Output
Output will appear here after execution...
Type Casting Input Values
By default, the input() function collects user input as a string, even if the user enters a number like 10 or 99.9. Therefore, to use the input as an integer or float, you must explicitly convert it using type casting (e.g., int() or float()).
Python Code
# Converting input to integer
a = int(input("Enter a value: ")) # User input value 10
print(a) # Output: 10
print(type(a)) # Output: <class 'int'>
Run Output
Enter a value: 10
10
<class 'int'>
Explanation:
The input() function collects user input as a string
int() converts the string to an integer
The converted integer is stored in variable a
When printed, we see the integer value 10
type(a) confirms it's now an integer
Now, if you type 10 in the first example, print(type(a)) shows the type as str (string). But if you use type casting as shown above, it becomes an integer. If you enter a non-numeric value like "Harish" in the integer conversion example, you’ll get an error—because Python can’t convert words into an integer. This is how you use the input() function and type casting together.
Previous: Type Conversion
Next: Output Printing
Output Printing
Lesson 12
I want to help you really understand the print function in Python. You're already familiar with it from our work with data types and type casting, but let's see the extra power it has using its special keywords: separator (sep) and end.
Basic print() Syntax
Inside the print() function, you can print messages—in double quotes, numbers, variable values, and more. For example:
Python Code
# Basic Print Examples
print("harish") # prints harish
print("@") # prints @
print(10) # prints 10
print(" H") # prints space then H
Run Output
harish
@
10
H
You can also use variables. Imagine Harish wants to print his name:
Python Code
# Printing a Variable
name = "harish"
print(name) # Output: harish
Run Output
harish
Using the sep Keyword
Let's understand the sep keyword. Using sep, you can choose what appears between items you print. By default, Python uses a space as the separator.
CodeFlow Visualizer: Using sep
This shows how to use the sep keyword to specify a custom separator.
Python Code
Ready
1
1
name = "harish"
Created variable: name = "harish"
2
2
print("Hi I am", name, "thank you", sep=" @ ")
Using variables: name with custom separator " @ "
Click "Execute" to start.
Program Output
Output appears here...
Combining sep and Newlines
Now, let's mix print, sep, and "\\n" (the newline character). The "\\n" tells Python to jump to the next line. If you want B to start on the next line, you can use sep="\\n".
CodeFlow Visualizer: Using a Newline Separator
This shows how to use the sep="\n" keyword to print each item on a new line.
Python Code
Ready
1
1
print("A", "B", sep="\\n")
The print() function will output "A", then a newline, then "B".
Click "Execute" to start.
Program Output
Output appears here...
Using the end Keyword
The end keyword controls what is printed at the end of a print statement. By default, Python adds a newline (\n), but you can change this behavior.
Python Code
# Using end to change line termination
print("Hello", end=' ')
print("World", end='!')
print(" How are you?")
# Using end with custom characters
print("First line", end=' --- ')
print("Continued on same line")
Run Output
Hello World! How are you?
First line --- Continued on same line
What I want is for you to experiment with sep and end. Try changing them to see how output changes!
Previous: Input Handling
Next: Arithmetic Operators
Arithmetic Operators
Lesson 13
Our next topic is operators. First, let’s look at arithmetic operators. We use these for addition, subtraction, multiplication, division, floor division, and modulus.
I’m not going to explain what addition or subtraction is—we’ve been using them since school. Let’s understand how to actually use these arithmetic operators in a Python program.
First, what I want is to make an addition. For that, we need two variables. I’m going to create variables a and b, assign values, and then store the result in another variable called result. After that, I’ll print it.
CodeFlow Visualizer: Simple Addition
This demonstrates basic variable assignment and arithmetic addition in Python.
Python Code
Ready
1
1
a = 10
Created variable: a = 10
2
2
b = 20
Created variable: b = 20
3
3
result = a + b
Calculated a + b (10 + 20) and assigned to result = 30
4
4
print(result)
Printing the value of result.
Click "Execute" to start.
Program Output
Output appears here...
Hope I am clear about how the assignment and addition works.
# Subtraction, Multiplication, and Division
a = 10
b = 20
# Subtraction
result = a - b
print(result) # Output: -10
# Multiplication
result = a * b
print(result) # Output: 200
# Division
result = a / b
print(result) # Output: 0.5
Run Output
-10
200
0.5
Now, I’m going to change the value of b to 2. What I want is the output to be a round value, not a float. For that, I use floor division.
Python Code
# Floor Division and Modulus
a = 10
b = 2
# Floor Division (rounds down to the nearest whole number)
result = a // b
print(result) # Output: 5
# Modulus (finds the remainder)
result = a % b
print(result) # Output: 0
Run Output
5
0
Keep this in mind: addition ( + ), subtraction ( - ), multiplication ( * ), division ( / ), floor division ( // ), and modulus ( % ) are the basic arithmetic operators.
Previous: Output Printing
Next: Comparison Operators
Comparison Operators
Lesson 14
Now, our next topic in operators is comparison operators. These are used for comparing two variables or two values.
Let’s understand how comparison operators work. The ones you’ll use the most are:
Equal to (==)
Not equal to (!=)
Greater than (>)
Less than (<)
Greater than or equal to (>=)
Less than or equal to (<=)
Let’s write code for these and see what happens. For more examples, you can look at this guide on comparison operators.
Equal To (==) Operator
First, I’m going to use the equal to operator. For this, we need two variables. What I want is to see if both values are the same. If they are, the result will be True. If not, it’ll be False.
CodeFlow Visualizer: Equal To Comparison
This shows how the == operator compares two values and returns a boolean result (True or False).
Python Code
Ready
1
1
a = 10
Created variable: a = 10
2
2
b = 10
Created variable: b = 10
3
3
print(a == b)
Comparing a (10) and b (10) using ==. Result is True.
4
4
b = 20
Updated variable: b = 20
5
5
print(a == b)
Comparing a (10) and b (20) using ==. Result is False.
Click "Execute" to start.
Program Output
Output appears here...
Other Comparison Operators
Now, let’s use the other operators. The logic is the same: the expression returns True if the comparison is valid and False otherwise.
Python Code
a = 20
b = 10
# Not Equal To
print(a != b) # Output: True
# Greater Than
print(a > b) # Output: True
# Less Than
print(a < b) # Output: False
# Greater Than or Equal To
c = 20
print(a >= c) # Output: True
# Less Than or Equal To
print(a <= c) # Output: True
Run Output
True
True
False
True
True
So, using these comparison operators, you can check if two values are equal, not equal, greater or lesser, and so on.
Previous: Arithmetic Operators
Next: Logical Operators
Logical Operators
Lesson 15
Our next topic is logical operators. These help us work with conditions in our code. The three main logical operators are and, or, and not. These are fundamental for controlling program flow, which you can read more about in this guide to Python's logical operators.
The and Operator
First, let’s understand how the and operator works. For and, you need two conditions. It will return True only if both conditions are true. If even one of the conditions is false, the result will be False.
CodeFlow Visualizer: Logical AND Comparison
This shows how the and operator combines boolean results. Both conditions must be True for the overall expression to be True.
Python Code
Ready
1
1
a, b, c = 30, 20, 18
Assigned a = 30, b = 20, c = 18.
2
2
print(a > banda > c)
Evaluates (30 > 20) and (30 > 18). Both are True, so the result is True.
3
3
a = 2
Updated variable: a = 2.
4
4
print(a > banda > c)
Evaluates (2 > 20) and (2 > 18). The first condition is False, so the result is False.
Click "Execute" to start.
Program Output
Output appears here...
The or Operator
Next, let’s look at the or operator. This also needs two conditions. If either one (or both) of the conditions is true, the result is True. If both are false, only then will it return False.
CodeFlow Visualizer: The or Operator
This shows how the or operator evaluates two conditions.
Python Code
Ready
1
1
a, b, c = 30, 20, 18
2
2
print(a > bora < c)
Click "Execute" to start.
Program Output
Output appears here...
The not Operator
Now, let’s move on to the not operator. This one only uses a single condition. It simply reverses the result—if the condition is True, not makes it False. If the condition is False, not makes it True.
CodeFlow Visualizer: The not Operator
This shows how the not operator inverts a boolean value. If a condition is True, not makes it False, and vice-versa.
Python Code
Ready
1
1
a = 2
Created variable: a = 2.
2
2
b = 29
Created variable: b = 29.
3
3
print(nota > b)
Evaluates (2 > 29), which is False. The not operator then inverts this to True.
Click "Execute" to start.
Program Output
Output appears here...
Hope you’ve got 100% clarity on logical operators. Pause the lesson and try these examples!
Previous: Comparison Operators
Next: Assignment Operators
Understanding Assignment Operators in Python
Lesson 15
Our next topic is the assignment operator. Before I explain, let’s write a simple program to increase an existing variable’s value. I’m going to make a variable called count and set it to 1. After that, I’ll add 2 to count and print the result.
CodeFlow Visualizer: Standard Increment
This demonstrates the standard way of incrementing a variable's value.
Python Code
1
1
count = 1
2
2
count = count + 1
3
3
print(count)
Click "Execute" to start.
Program Output
Output appears here...
Using Shorthand Assignment Operators
Now, let’s rewrite that second line using a special assignment operator to make our code shorter. Here’s the shortcut for adding a value to an existing variable:
CodeFlow Visualizer: Augmented Assignment
This shows how to use the += operator as a more efficient shortcut.
Python Code
1
1
count = 1
2
2
count += 2
3
3
print(count)
Click "Execute" to start.
Program Output
Output appears here...
These assignment operators, often called augmented assignment operators, work for more than just addition. Here are some other common examples:
Python Code
x = 10
print(f"Initial x = {x}")
x -= 2 # Subtracts 2 from x (10 - 2 = 8)
print(f"After -= 2: x = {x}")
x *= 4 # Multiplies x by 4 (8 * 4 = 32)
print(f"After *= 4: x = {x}")
x /= 2 # Divides x by 2 (32 / 2 = 16.0)
print(f"After /= 2: x = {x}")
x %= 3 # Modulus: remainder of 16 / 3 is 1.0
print(f"After %= 3: x = {x}")
Run Output
Initial x = 10
After -= 2: x = 8
After *= 4: x = 32
After /= 2: x = 16.0
After %= 3: x = 1.0
Hope I am clear! Try these assignment operators by writing your own code. For a complete list and more examples, you can always refer to the official Python documentation.
Previous: Logical Operators
Next: If Statement
Understanding Modulus (%) and Even/Odd Numbers in Python
Lesson 16
We already saw what arithmetic operators are. Addition, subtraction, multiplication, division — those are basic. But there's also modulus, which a lot of people don't know. Modulus just gives back the remainder of a value.
Let's look at a simple program for this. What I want is to use the modulus operator (%) to print out the remainder value. I'll show you step-by-step, and we'll use the input() function so you can try your own numbers.
First, let's understand how modulus works. The result will always be 0 or 1 if you use % 2. That's what we'll use in the program. Let's execute the code.
Python Code
# User enters a number, e.g., 9
number = int(input("Enter a number: "))
remainder = number % 2
print("Remainder value is", remainder)
Run Output
Enter a number: 9
Remainder value is 1
Some people don't know how to calculate remainder by hand, so let's break it down.
Manual Remainder Calculation
Let's focus on calculating the remainder for a specific number now. For those who want a manual method, here are three steps:
First, divide the number by 2.
Then, use the coefficient (the quotient/whole part from the division) and multiply it by 2.
Finally, subtract that multiplied result from the original number. What's left is the remainder.
For example, if I have 6:
Step one: 6 divided by 2 is 3. The coefficient is 3.
Step two: 3 (coefficient) times 2 is 6.
Step three: 6 minus 6 is 0. That's the remainder. If the remainder is 0, that means the number's even.
Let's see with 9:
Divide 9 by 2. The coefficient is 4 (always use the rounded down value).
4 times 2 is 8.
9 minus 8 is 1, so remainder is 1. If you get 1, that's an odd number.
Automating the Even/Odd Check
Let's automate even and odd checking in Python now. I'm going to update the code to use an if statement. Because this is the complete program for the lesson and it uses input, we will use the full interactive visualizer.
CodeFlow Visualizer: Even or Odd Checker
Python Code
1
1
number = int(input("Enter a number: "))
2
2
remainder = number % 2
3
3
print("Remainder value:", remainder)
4
4
ifremainder == 0:
5
5
print("It is an even number.")
6
6
else:
7
7
print("It is an even number.")
Code Explanation
Enter a number and click "Execute" to begin.
Program Output
Output will appear here...
During my college interview, I actually got this question — to print whether a number is even or odd. I used Java then, but Python makes it so much easier! Hope I am clear.
Previous: Assignment Operators
Next: If Statement
Python Conditional Statements: The If Statement
Lesson 17
In this lesson, I’m going to talk about conditional statements in Python. You’ll learn about the if statement, if-else statement, elif statement, and nested if statement. Let’s understand them one by one.
First, let’s focus on the if statement. Before writing the code, let’s understand the flow:
When the program runs, it will first check the condition inside the if statement. If the condition is true, Python will execute the statements you put under if. If the condition is false, it just skips those lines and ends the program, not running anything under if.
Let me show you an example so you get it 100%.
Imagine Harish wants to make a program to check if someone is eligible to vote. He’ll ask the user to enter their age, and if the age is 18 or older, the program prints that they are eligible for voting.
Here’s what the code looks like:
CodeFlow Visualizer: Voting Eligibility
Python Code
1
1
age = int(input("Enter your age: "))
2
2
ifage >= 18:
3
3
print("You are eligible for voting")
Code Explanation
Enter an age and click "Execute".
Program Output
Output will appear here...
Let’s execute the code.
First, Python runs the input function and prints “Enter your age:”. The user types their age. That input is collected as a string, so we use type casting (int) to turn it into an integer and assign it to the variable age.
Now, the if statement checks: is age greater than or equal to 18? If yes, Python prints “You are eligible for voting.” If not, the program just ends and nothing prints.
Let’s try it out. If you enter 19 as the age, you’ll see the message saying you’re eligible for voting. If you enter 12, nothing prints—the condition is false, so Python skips the print statement and finishes.
Stay tuned for the next lesson where we’ll look at more conditional statements like if-else and elif.
Previous: Modulus Usage
Next: If Else Logic
Python If Else Statement
Lesson 18
Our topic now is the if-else statement. Before we write any code, let’s quickly understand the flow:
When your program starts, Python checks the condition in your if statement. If the condition is true, it only runs the true statement, then finishes—without doing anything in the else part. If the condition is false, it only runs the false (else) statement and ignores the true part. Hope I am clear!
Let’s write the program. We’re still working on the voting eligibility example.
Now, if the user enters an age less than 18, we need to print “You are not eligible for voting.” So, we’ll add the else part to our code:
CodeFlow Visualizer: If-Else Voting Check
Python Code
1
1
age = int(input("Enter your age: "))
2
2
ifage >= 18:
3
3
print("You are eligible for voting")
4
4
else:
5
5
print("You are not eligible for voting")
Code Explanation
Enter an age and click "Execute".
Program Output
Output will appear here...
Let’s test how this works:
If the user types 24, age is 24, and 24 >= 18 is true. Python prints “You are eligible for voting” and skips the else part.
If the user types 12, age is 12, and 12 >= 18 is false. Python skips the print inside if and moves to else, printing “You are not eligible for voting.”
Let’s execute the code. You’ll see, if you enter 34, you get “You are eligible for voting.” If you enter 12, you get “You are not eligible for voting.”
That’s it for the if-else statement. In the next lesson, we’ll keep building on conditionals. Stay tuned!
Previous: If Statement
Next: If-Elif-Else Chain
If Elif Else Statement in Python
Advanced Conditionals
Our next topic is the if elif else statement. Before jumping into code, let’s understand how it works.
When your program starts, it checks the first condition (condition one). If that’s true, Python runs the code for condition one. If the condition is false, it moves to condition two. If condition two is true, it runs the second block. If both conditions are false, Python goes to the else part and runs that code.
It might sound confusing at first, but once you see the code, you’ll get it.
What I want is to write a program that takes your age and prints a message depending on which group you’re in:
If age is above 60, print “Senior citizen.”
If age is above 21, print “Adult.”
If age is above 11 or 12, print “Teenagers.”
For the rest, print “Children.”
Let’s write this step-by-step.
CodeFlow Visualizer: Age Group Classifier
Python Code
1
1
age = int(input("Enter your age: "))
2
2
ifage > 60:
3
3
print("Senior citizen.")
4
4
elifage > 21:
5
5
print("Adult.")
6
6
else:
7
7
print("Teenagers.")
Code Explanation
Enter an age and click "Execute".
Program Output
Output will appear here...
Let’s trace this code. First, the program gets your age as input and stores it in a variable.
First, it checks if age is greater than 60. If yes, it prints “Senior citizen” and stops.
If age isn’t over 60, Python checks if age is greater than 21. If that’s true, it prints “Adult.”
If both of the above are false, it goes to the else part and prints “Teenagers.”
For example:
Enter 62 — output: Senior citizen.
Enter 27 — output: Adult.
Enter 16 — output: Teenagers.
Enter 12 — output: Teenagers.
You see, the program moves step-by-step through the options.
Previous: If Else Logic
Next: Nested If Conditions
Nested If Statement in Python
Lesson 19 |
Our next topic is nested if statements. Nested if means putting one if statement inside another if statement.
Let’s understand the flow first. If the main if statement’s condition is true, Python goes inside and checks the second if statement. If the second if statement is also true, its body will run. If not, Python runs the else part for the second if. If the main if statement is false, it goes straight to its own else part. I know this can be confusing, but once we do the code, it’ll be clear.
Let’s look at an example. Imagine Harish wants to write a program to check if a number is positive, and if it is, also check if it’s even or odd.
Here’s how to do it:
CodeFlow Visualizer: Nested Checks
Python Code
1
1
num = int(input("Enter a number: "))
2
2
ifnum > 0:
3
3
rem = num % 2
4
4
ifrem == 0:
5
5
print("It is an even number")
6
6
else:
7
7
print("It is an odd number")
8
8
else:
9
9
print("Enter a positive value")
Code Explanation
Enter a number and click "Execute".
Program Output
Output will appear here...
Let’s understand how this works:
First, the program asks you to enter a number.
It checks if the number is greater than zero (positive). If yes, it finds the remainder when dividing the number by 2.
If the remainder is zero, it prints "It is an even number". If not, it prints "It is an odd number".
If the first condition (num > 0) is false (so you entered a negative number), it just prints "Enter a positive value" and skips everything else.
Let’s execute the code:
If you enter 12, you’ll see "It is an even number".
If you enter 15, you’ll see "It is an odd number".
If you enter -4, you’ll see "Enter a positive value".
Keep this in mind: Indentation in Python shows which if or else belongs to which statement. If statements and their code are indented under each other.
In the next lesson, we’re going to discuss loops, which is a very important topic. Let’s continue to the next Lesson where we’ll understand how to use loops in Python!
Previous: If-Elif-Else Chain
Next: Iterators & Next
Python Iterator and Next Function
Lesson 20 |
In this lesson, I’m going to talk about iterables, iterators, and the next function in Python.
First, let’s write a simple program with a list. I’m creating a variable called fruit and putting three values in it.
Python Code
fruit = ["apple", "orange", "banana"]
print(fruit)
Run Output
['apple', 'orange', 'banana']
When you run this, you’ll see the output as a group: ['apple', 'orange', 'banana'].
But what I want is to print each value separately—apple, orange, and banana on different lines. To do this, we need to understand iterables, iterators, and how the next function works.
First, let’s understand what an iterable is. Data types like list, set, tuple, dictionary, and string are called iterable data types. So, if someone asks, “What are the iterable data types?” You can say: list, set, tuple, dictionary, and string.
Next, what is an iterator? An iterator helps you fetch one specific value at a time from the list. On the first step, it fetches the first value. On the next, it fetches the next value, and so on. So, the iterator’s job is to fetch one value at a time from the group.
To use an iterator, we call the iter() function. But calling iter() alone doesn’t fetch the next value—you need the next() function for that.
The next() function in Python returns the next value from an iterator each time you call it. If there are no more items to return, it raises a StopIteration error.
Let’s write the code step-by-step for this:
CodeFlow Visualizer: Using Iterators
Python Code
1
1
fruit = ["apple", "orange", "banana"]
2
2
a = iter(fruit)
3
3
print(next(a))
4
4
print(next(a))
5
5
print(next(a))
Click "Execute" to start.
Program Output
Output appears here...
Let’s execute the code.
The first print prints “apple”
The second print prints “orange”
The third print prints “banana”
If you have more values in the list, like numbers from 1 to 5, just put them in the list and keep calling next(a):
But keep this in mind: If you write a really big list, you’d need dozens or hundreds of next() calls. That’s not practical! To solve this, we use loops.
In the next lesson, we’ll discuss loops! You’ll see how they make working with iterators much easier. Let’s continue to the next Lesson where we’ll understand how to write loops in Python!
Previous: Nested If Conditions
Next: For Loop Basics
Python For Loop: Iterating Through Sequences Made Easy
Lesson 21
In the last lesson, we talked about iterables, the iter function, and next function. To print five values using those, we needed five print statements and five next calls. But what if you need to print numbers from 1 to 100? You don’t want to write 100 print functions!
That’s why Python gives us loops. With a for loop, you can do the same thing in just two lines, even for 100 or more values.
First, let me show you the syntax of a for loop:
Python Code
for variable in iterable:
# your code here
The “iterable” can be a list, set, tuple, dictionary, or string—whatever is iterable.
Let’s see how it works step by step. Imagine Harish has a list:
CodeFlow Visualizer: Basic For Loop
Python Code
1
1
count = [1, 2, 3, 4, 5]
2
2
for i incount:
3
3
print(i)
Click "Execute" to start.
Program Output
Output appears here...
When you run this code, the for loop automatically uses the iter and next functions behind the scenes. It starts with the first value in the list, prints it, moves to the next, and keeps going until it runs out of values.
On the first loop: i is 1, so it prints 1.
Next loop: i is 2, it prints 2.
Then 3, 4, and finally 5.
After printing all values, the loop ends.
Let’s try printing a word five times:
You can actually give an iterable data type value straight into a for loop. Let me show you this. I’m going to write a for loop, but instead of making a list or set first, I’ll just put a list right inside the loop.
Python Code
for i in [1, 2, 3, 4, 5]:
print("harish")
Run Output
harish harish harish harish harish
This prints “harish” five times.
Now, let’s create a list with string values:
Python Code
fruits = ["apple", "orange", "banana"]
for fruit in fruits:
print(fruit)
Run Output
apple orange banana
You see, this prints “apple”, then “orange”, and “banana” each on its own line.
You can use a tuple too—just replace the square brackets with parentheses:
Python Code
fruits = ("apple",)
for fruit in fruits:
print(fruit)
Run Output
apple
If you use a string, like "harish", the loop prints each character, one by one:
Python Code
for char in "harish":
print(char)
Run Output
h a r i s h
You’ll get H, A, R, I, S, and H—six characters, so it loops six times.
Keep this in mind: For loops make it easy to go through items in any iterable—lists, tuples, sets, dictionaries, strings—no matter the size.
What if Harish wants to print numbers from 1 to 100? Listing them all would take too long! That’s where the range function helps.
In the next lesson, you’ll learn about the range function. Go ahead and check it out!
Previous: Iterators & Next
Next: Range Function Usage
Python Range Function: Generating Sequences for Loops
Lesson 22
You can actually give an iterable data type value straight into a for loop. Let me show you this. I’m going to write a for loop, but instead of making a list or set first, I’ll just put a list right inside the loop.
Python Code
for num in [1, 2, 3, 4, 5]:
print(num)
Run Output
1 2 3 4 5
Let’s execute the code. You’ll see the output is 1, 2, 3, 4, 5.
But what happens if I try to use a single integer? Let’s try.
Python Code
a = 23
for num in a:
print(num)
Run Output
TypeError: 'int' object is not iterable
When we run this, you’ll see an error: “int object is not iterable.” So, keep this in mind: integers by themselves can’t be looped through like lists, sets, tuples, dictionaries, or strings. Only these five are iterable data types.
Now, let’s understand how the range function works. The range function is an alternative for using an actual list. With range, you can tell Python exactly how many times to loop.
For example, if I want the loop to run four times, I don’t need to make a list with four items. I can use range.
CodeFlow Visualizer: The Range Function
Python Code
1
1
for num inrange(4):
2
2
print("learn to code")
Click "Execute" to start.
Program Output
Output appears here...
Let’s execute the code. This prints “learn to code” four times.
The range() function lets you create a sequence of numbers.
✅ If you write range(100), the values will go from 0 up to 99 — it starts from 0 by default.
✅ If you write range(35), it goes from 0 to 34.
This happens because the stop value is exclusive, meaning Python stops before the stop number and doesn’t include it in the output.
Start Value:
You can also set a start value manually.
✅ Example: range(5, 10) will start from 5 and go up to 9 (10 is not included).
Step Value:
There’s one more thing with range — the step value.
✅ By default, Python increases numbers by 1.
✅ But if you set a step, Python will jump by that number each time.
Quick Summary:
• Start → where the range begins (default is 0).
• Stop (exclusive) → where it ends (not included).
• Step → how much it jumps forward (or backward if negative).
This is how range() helps control the start, stop, and step values in Python!
Improving Code Efficiency: Multiplication Tables with Python
Now, let’s use the for loop to print a multiplication table(Ex: 2 * 1 = 2). What I want is for the user to choose any number, and the program prints its table from that number up to 10 multiples.
In your for loop, each value "i" is just a multiple of num. For every step, if you divide i by num, you get the count for that line.
Let’s write it out:
Python Code
num = int(input("Enter a number: "))
for i in range(num, num * 10 + 1, num):
print(num, X , int(i / num), "=", i)
Let’s execute this program. Give input as 2: 2 X 1 = 2 2 X 2 = 4 2 X 3 = 6 …and so on.
Now, you’ll notice using int(i / num) is typecasting, but we can make this even better. Instead of dividing and converting to int, let’s use floor division (//) to get the rounded-down value right away.
Hope I am clear. Using floor division makes your code efficient and clean.
Now, let’s look back at the count variable we used before, for folks who had questions on it.
Imagine Harish wants to increase a variable step-wise. Here’s how:
Python Code
count = 1
count = count + 2
print(count)
When you run this, count starts as 1. After the addition (1 + 2), count is now 3. When you print, you see 3.
You can do the same using an assignment operator (+=):
Python Code
count = 1
count += 2
print(count)
Let’s execute — you’ll get 3 again.
Want to subtract? Use -=:
Python Code
count = 1
count -= 2
print(count)
This will print -1.
For multiplication, let’s initialize count to 2:
Python Code
count = 2
count *= 2
print(count)
You’ll see 4 as the output.
Keep this in mind: Assignment operators make your code neat and concise.
Keep practicing—interviews are not only about testing your skills, but also about evaluating your logical thinking.
Previous: For Loop Basics
Next: While Loop
Python While Loop
Lesson 23
Welcome back! In this lesson, we’re going to discuss the while loop. In the last lesson, we learned about the for loop and wrote a few programs with it.
Let’s understand how the while loop works. It’s different from a for loop. In a for loop, you use iterable data types like lists, sets, or strings. But in a while loop, you directly give a condition.
Here’s how it goes:
When the program starts, Python checks the condition.
If the condition is true, it runs the loop body.
After running the loop, it checks the condition again.
If still true, the body runs again.
This keeps going until the condition is false, then the loop ends.
Let’s write a basic while loop to print numbers from 1 to 5:
CodeFlow Visualizer: Basic While Loop
Python Code
1
1
count = 1
2
2
whilecount <= 5:
3
3
print(count)
4
4
count = count + 1
Click "Execute" to start.
Program Output
Output appears here...
If you forget to increase the count, the condition always stays true and the output will print 1 forever (an infinite loop). So always remember to update your counter!
Let’s write a program to print numbers from 1 to 10 using the while loop:
If you miss the increment, it will run endlessly! So be careful—always increase the count.
Multiplication Table with a While Loop
Now, let’s use the while loop to print a multiplication table. What I want is for the user to choose any number, and the program prints its table from that number up to 10 multiples.
Imagine the user enters 2. That value gets stored in a variable called num. I created another variable, count, and assigned num’s value to it. So, count is also 2 at first.
CodeFlow Visualizer: While Loop Multiplication Table
Python Code
1
1
num = int(input("Enter a number: "))
2
2
count = 1
3
3
whilecount <= num * 10:
4
4
print(num, "X", count // num, "=", count)
5
5
count = count + num
Code Explanation
Enter a number and click "Execute".
Program Output
Output will appear here...
Hope I am clear! In the next lesson, we’ll write more programs with while loops and introduce the break and continue statements. Stay tuned!
Previous: Range Function Usage
Next: Break Statement
Understanding the break Statement in Python Loops
Lesson 24
In this lesson, I’m going to talk about the break statement and how it works inside a while loop.
First, let’s understand what break does. Imagine you have ten lines inside your while loop. If you put a break statement at the third line, then when your code runs, the loop starts checking its condition. If true, it goes through the loop’s body. The first line runs, then the second. But when the break statement runs at the third line, the whole loop stops — any lines after break inside the loop won’t run.
Hope I am clear. Now let’s see this in action.
First, say I want to print values from 1 to 10 using a while loop:
When break runs, the while loop ends and the “Hi” message prints after that. Keep this in mind—break only stops the loop, not the rest of your code.
Hope I am clear! The break statement helps you stop a loop at any moment, and only affects the current loop it’s in.
In the next lesson, you’ll learn about the continue statement. Stay tuned! Thank you.
Previous: While Loop
Next: Pass Statement
Understanding the pass Statement in Python
Lesson 25
In this lesson, I'm going to explain the pass statement. Hope you remember what we discussed in the last lesson about break.
There are times when you don’t want to write any code inside the body of an if condition—just an empty block. But if you give an if condition without any code inside, Python returns an exception. It says: “expected an indented block after if statement.”
Let me show you what happens. Imagine Harish is writing:
Python Code
if 3 > 2:
# nothing here
Run Output
IndentationError: expected an indented block
If you run this, Python throws an exception because there’s no indented code after the if.
To fix this, you use the pass statement. If you don’t want anything to happen inside your if condition but want to avoid the error, just add pass.
CodeFlow Visualizer: The Pass Statement
Python Code
1
1
if 3 > 2:
2
2
pass
3
3
print("Program continues")
Click "Execute" to start.
Program Output
Output appears here...
Let’s execute this. Now, you won't get any exception from Python. The program runs fine. The pass statement is just a way to tell Python, “do nothing here.”
Hope I am clear. In some scenarios, you might need this, even though it doesn't actually do anything.
Previous: Break Statement
Next: Continue Statement
Understanding the continue Statement in Python
Lesson 26
In this lesson, I’m going to explain the continue statement. Some people get confused between continue and break, but they’re not the same, even though they both help control loops.
First, let’s write a simple program that prints numbers from 1 to 10. I’ll use a for loop with the range function.
Python Code
for i in range(1, 11):
print(i)
Let’s execute the code. You should see numbers 1 to 10 printed.
Now, imagine you don’t want to print the number 3. What I want is to skip printing 3 and continue with the rest. Here’s how the continue statement helps.
Let’s use a condition inside the loop: if i == 3, use continue.
CodeFlow Visualizer: The Continue Statement
Python Code
1
1
for i inrange(1, 11):
2
2
if i == 3:
3
3
continue
4
4
print(i)
Click "Execute" to start.
Program Output
Output appears here...
Keep this in mind: continue just skips the rest of the loop for that value and moves to the next loop cycle. It doesn’t stop the whole loop, which break does.
Previous: Pass Statement
Next: String Multiplication
String Replication in Python
Lesson 27
Our next topic is string replication. It’s all about printing a specific message multiple times. For example, you can have a message and, with string replication, print that message as many times as you want.
Let’s understand how. I’m going to use the print function and inside double quotes, I’ll put a message. Then, I simply multiply the string by a number to replicate it.
Python Code
print("Harish" * 4)
Run Output
HarishHarishHarishHarish
Let’s execute this code. You’ll see “HarishHarishHarishHarish” printed four times. This is not duplication, it’s string replication.
If you want a little space, just add it in the string:
Python Code
print("Harish " * 4)
Run Output
Harish Harish Harish Harish
This prints “Harish” four times with spaces between.
Now, let’s try with a star. I’ll put a star inside double quotes, multiply by 5, and execute:
Python Code
print("*" * 5)
Run Output
*****
You’ll see five stars in a row: *****
This is a basic pattern problem and string replication is super useful for making such patterns.
Keep this in mind when working with loops or patterns—string replication makes things much simpler.
Previous: Continue Statement
Next: Star Pattern Printing
Star Pattern Programs in Python
Lesson 24
In this lesson, I’m going to write some important star pattern programs. These are basic patterns often asked in interviews. Don’t worry—they’re simple!
First, let’s print five stars in a row (horizontally). Here’s how:
Python Code
print("*" * 5)
Run Output
*****
Next, let’s get a value from the user, so they decide how many stars get printed in one row:
Python Code
num = int(input("Enter the number of stars: "))
print("*" * num)
Run Output
(Assuming input is 8)
********
Now, to print stars vertically (one below the other), use a loop:
the underscore _ is commonly used as a “throwaway” or “dummy” variable when you want to ignore a value.
Python Code
num = int(input("Enter the number of stars: "))
for _ in range(num):
print("*")
Run Output
(Assuming input is 5)
*
*
*
*
*
Now, let’s print stars in a pattern: first row has 1 star, second has 2, and so on. Since this is the first complex pattern we are introducing, let's visualize it.
CodeFlow Visualizer: Star Triangle Pattern
Python Code
1
1
num = int(input("Enter the number of rows: "))
2
2
for i inrange(1, num + 1):
3
3
print("*" * i)
Code Explanation
Enter a number and click "Execute".
Program Output
Output will appear here...
Now, let’s align stars so the first row has spaces before the star, second row has fewer spaces, and so on: (The classic right-aligned triangle.)
Python Code
num = int(input("Enter the number of rows: "))
for i in range(1, num + 1):
print(" " * (num - i) + "*" * i)
Run Output
(Assuming input is 5)
*
**
***
****
*****
Let’s create a centered pyramid pattern where each row has both spaces and more stars each time.
Python Code
num = int(input("Enter the number of rows: "))
for i in range(1, num + 1):
print(" " * (num - i) + "*" * (2 * i - 1))
Run Output
(Assuming input is 5)
*
***
*****
*******
*********
In the next lesson, you’ll learn how to print number and alphabet patterns. Stay tuned!
Previous: String Multiplication
Next: Number Patterns
Number Pattern Programs in Python
Lesson 25
First, before we jump into patterns, I want to talk again about the “end” keyword in the print function. We’ve already seen this before, but it’s important for patterns.
Let’s understand how the end keyword works. If I print “A” and then “B” in two print statements, the cursor moves down to the next line after each print. But if I use the end keyword, the cursor stays on the same line.
Python Code
print("A", end="")
print("B")
Run Output
AB
Let’s create a pattern with 5 rows and 5 columns, where each row contains the same number. We need two loops: one outer for rows, and an inner one for columns. Since this is our first nested loop pattern, we will visualize it.
CodeFlow Visualizer: Nested Loop Number Pattern
Python Code
1
1
for i inrange(1, 6):
2
2
for j inrange(1, 6):
3
3
print(i, end="")
4
4
print()
Click "Execute" to start.
Program Output
Output will appear here...
The outer loop runs 5 times (for each row), and the inner loop runs 5 times for each of those rows (for each column). The empty print() moves the cursor to the next line after each row is complete.
Hope I am clear on all these patterns! Pause the lesson and try tracing each code to see how the loops change the patterns.
In the next lesson, you’ll learn about alphabets pattern programs. Let’s continue to the next lesson where we’ll understand how to create those!
Previous: Star Pattern Printing
Next: Alphabet Patterns
Alphabet Patterns in Python
Looping in Python
Let's understand how to print patterns using alphabets in Python. This technique often involves using nested loops combined with functions that convert numbers to characters.
The two key functions we'll use are ord() and chr().
ord('A'): This function returns the ASCII (numerical) value of a character. For example, ord('A') is 65.
chr(65): This function does the opposite; it returns the character represented by a number. For example, chr(65) is 'A'.
You can find a complete list of characters and their corresponding codes on an ASCII table chart.
Let's see how to combine these with loops to create a simple pattern.
Python Code
1 rows = 5
2 for i inrange(rows): # Outer loop for each row
3 for j inrange(i + 1): # Inner loop for columns
4 print(chr(65 + j), end="")
5
6 print() # Move to the next line
Click "Execute" to start the trace.
Program Output
Previous: Number Patterns
Next: Prime Number Logic
Prime Number Program in Python
Lesson 26
In this lesson, I’m going to help you write a Python program that checks if a number is prime or not. This is a common interview question! Before we jump in, let’s do a quick recap on remainders since understanding them is key for prime numbers.
A prime number can only be divided by itself and 1. For example, 7 is prime because 7 divided by 1 and 7 divided by 7 both work, but nothing else divides evenly.
Let's write a factors finder first to help us understand:
Python Code
num = int(input("Enter a number: "))
for i in range(2, num + 1):
if num % i == 0:
print(i)
Run Output
(Assuming input is 6)
2
3
6
Now, let's check if the number is prime. If the first factor found is the number itself, it’s a prime. If you find a factor before then, it’s not a prime. Let’s put it together for a complete prime number check.
CodeFlow Visualizer: Prime Number Checker
Python Code
1
1
n = int(input("Enter a number: "))
2
2
for i inrange(2, n + 1):
3
3
if n % i == 0:
4
4
break
5
5
if n == i:
6
6
print(n, "is prime")
7
7
else:
8
8
print(n, "is not prime")
Code Explanation
Enter a number and click "Execute".
Program Output
Output will appear here...
Hope I am clear! This is how you use loops, modulo, and conditions to find if a number is prime in Python.
Previous: Number Patterns
Next: Classes & Objects
Understanding Functions in Python
Lesson 27
In this lesson, I'm going to explain functions and how you use them as a Python programmer. Think of everything around you as objects. For example, if we take a car as our object, it has two main parts: state and behavior. The state could be the car's brand, price, or mileage—these are data. The behavior, like starting, accelerating, or braking, are actions or functions.
Developers write code within blocks to automate these actions. Each block is given a name and is called a function. For example, to start a Tesla car, the team writes the logic inside a function block called "start." When you need to accelerate, there's another function for "accelerate."
Using functions means you can write code once and call it many times—this is code reuse.
Let’s understand this by writing simple Python functions for addition and multiplication. First, I'm going to define an addition function:
CodeFlow Visualizer: Defining and Calling a Function
Python Code
1
1
def add():
2
2
a = 5
3
3
b = 6
4
4
c = a + b
5
5
print(c)
6
6
7
7
add()
Click "Execute" to start.
Program Output
Output appears here...
Hope I am clear! The main idea: functions are blocks of code you can reuse, just like starting or accelerating a car—they each do one action.
Previous: Prime Number Logic
Next: Variable Scope
Local and Global Variables in Python
Lesson 28
Before we dive into local and global variables, I want to give you a quick look at how variable values are stored in Python, from the perspective of RAM.
Let’s get started. Imagine Harish creates a function using the def keyword, names it num, and inside that function he creates two variables. He assigns 12 to both a and b, and then prints them.
Let’s start with local variables. If you create a variable inside a function, it’s called a local variable. Local variables only exist within the function—they can’t be accessed outside it. Here’s an example:
CodeFlow Visualizer: Local Variables
Python Code
1
1
def num():
2
2
a = 12
3
3
b = 12
4
4
print(a)
5
5
print(b)
6
6
7
7
num()
Click "Execute" to start.
Program Output
Output appears here...
Now let’s talk about global variables. If you create a variable outside any function, it’s called a global variable. You can use global variables anywhere in your code—inside functions or outside:
Python Code
d = 5
def num():
a = 12
print(a)
print(d)
num()
print(d)
Run Output
12
5
5
Previous: Function Introduction
Next: Global Keyword Use
Understanding the global Keyword in Python
Lesson 29
In this lesson, I’m going to discuss the global keyword. The global keyword lets you convert a local variable into a global variable that you can use anywhere in your program.
Let’s see an example. First, I create a function called math. Inside the function, I make a variable a and set it to 5. Then I print a inside the function. Outside the function, I try to print a again.
Python Code
def math():
a = 5
print(a)
math()
print(a)
Run Output
5
NameError: name 'a' is not defined
Now, let’s use the global keyword to convert a into a global variable. Add global a inside the function before assigning a value:
CodeFlow Visualizer: The Global Keyword
Python Code
1
1
def math():
2
2
global a
3
3
a = 5
4
4
print(a)
5
5
6
6
math()
7
7
print(a)
Click "Execute" to start.
Program Output
Output appears here...
Keep this in mind: global keyword is used when you want a variable inside a function to be accessed everywhere.
Previous: Variable Scope
Next: Return Statement
Understanding the return Keyword in Python
Lesson 30
Before diving deeper into functions, I want to talk about the return keyword. The return statement is really important in functions.
Let me show you how it works. I’ll use the same add function as before, but instead of using print inside the function, I’ll use return:
CodeFlow Visualizer: The Return Keyword
Python Code
1
1
def add():
2
2
a = 5
3
3
b = 6
4
4
c = a + b
5
5
returnc
6
6
7
7
rest = add()
8
8
print(rest)
Click "Execute" to start.
Program Output
Output appears here...
Hope I am clear on how return works. The return statement sends the function’s value back to the code that called it, so you can store or use it however you like.
Previous: Global Keyword Use
Next: Custom Functions
Custom Functions in Python
Python Functions
Let's understand how to create your own custom functions. A function is a block of organized, reusable code that is used to perform a single, related action.
We use the def keyword to define a function. In my example, I have a main function called outer. Inside this outer function, I’m creating one more function called inner function.
Python Code
# This function is defined, but it will not run yet.
def add():
print("within add function")
Run Output
But nothing prints yet! That’s because Python only runs a function if you call it. So, here’s how to call the function:
Python Code
1 defadd():
2 print("within add function")
3
4 add() # Calling the function
Click "Execute" to start the trace.
Program Output
Sometimes you need a function definition for syntactical reasons but don't want to add any code yet. For this, you can use the pass statement.
Python Code
def empty_function():
pass # This function does nothing
empty_function() # This runs without error
In many larger programs, it's common practice to put the main execution logic inside a function conventionally named `main()`. This helps organize the code. You can learn more about this practice in this Real Python guide to the main function.
Python Code
def main():
# All main program logic goes here
print("This is the main function.")
# This line starts the program
main()
Run Output
This is the main function.
Previous: Return Statement
Next: Function Arguments
Types of Arguments in Python Functions
Lesson 31
Now let’s understand the types of arguments you can use in Python functions. There are five types:
Positional argument
Keyword argument
Default argument
Variable length argument
Variable length keyword argument
Let’s go through each one with clear examples. For a deep dive, you can always refer to the official Python tutorial on defining functions.
Positional Argument
First, let's see positional arguments. I'm going to do a simple multiplication program.
CodeFlow Visualizer: Positional Arguments
Python Code
1
1
def mul(a, b):
2
2
print(a)
3
3
print(b)
4
4
print(a * b)
5
5
6
6
mul(5, 6)
Click "Execute" to start.
Program Output
Output appears here...
This is a positional argument because the first value goes into the first parameter, and the second value into the second parameter. If I switch the order and write mul(6, 5), now a becomes 6 and b becomes 5.
Keyword Argument
Next, I want to show you keyword arguments. With keyword arguments, I can give the name of the parameter directly when calling the function. Let’s see:
Python Code
def mul(a, b):
print(a * b)
mul(b=6, a=5)
Run Output
30
Default Argument
Now, let’s look at default arguments. Suppose I write the function like this:
Python Code
def mul(a, b=5):
print(a * b)
mul(2)
mul(3)
mul(5, 3)
Run Output
10
15
15
Variable Length Argument
Next up is variable length argument. To accept any number of positional arguments, I use a star * in the parameter. This is often referred to as `*args` in documentation.
Now let’s talk about variable length keyword arguments. To accept any number of keyword arguments, use two stars **. This is commonly known as `**kwargs` and is a staple in flexible function design.
Today, I’m going to show you how to use pre-built functions in Python. Remember, Python is really popular because of its easy syntax, flexibility, and huge library support. The Python libraries have thousands of pre-built functions created by programmers and data scientists. We just reuse these functions.
Using the len() Function
We can make this much easier by using the pre-built len() function. Instead of several lines, you just need one:
CodeFlow Visualizer: The len() Function
Python Code
1
1
a = "string"
2
2
print(len(a))
Click "Execute" to start.
Program Output
Output appears here...
Other Useful Built-in Functions
To add up all the values in a list, use the sum() function. To get the largest value, use max(). To get the smallest value, use min(). To reorder your list, use the sorted() function. These are part of a rich set of Python built-in functions that are always available.
In the next lesson, you’ll learn how to import libraries and use even more pre-built functions in Python. Stay tuned!
Previous: Function Arguments
Next: Import Modules
How to Import Pre-Built Functions in Python
Lesson 33
Let’s say I want to do some math operations: find a factorial, a power, and print the value of pi. I’ll start by importing the math module. These modules are part of the Python Standard Library.
CodeFlow Visualizer: Importing the Math Module
Python Code
1
1
import math
2
2
print(math.sqrt(4))
3
3
print(math.pow(2, 3))
4
4
print(math.factorial(4))
Click "Execute" to start.
Program Output
Output appears here...
Importing Only What You Need
Sometimes, you might only want one function from a module. For example, if you just want factorial, write:
Python Code
from math import factorial
print(factorial(4))
Run Output
24
Previous: Built-in Functions
Next: Create Functions
How to Create and Import Your Own Module in Python
Lesson 34
Now, I’ll show you how to create your own module with custom functions and use them in your main program. Inside module.py, I write a simple addition function.
Python Code (module.py)
def add(a, b):
return a + b
Now, in main.py, I want to use this function from my module file. So, first, I import the module. This concept is fundamental to building larger applications, as explained in tutorials on Python modules and packages.
CodeFlow Visualizer: Custom Modules
Python Code (main.py)
1
1
import module
2
2
print(module.add(5, 6))
Click "Execute" to start.
Program Output
Output appears here...
Module Nicknames (Aliases)
You can also set a nickname (called an alias) for a module. This makes it easier to use, especially if the module name is long. You can do this with the `as` keyword.
Python Code
import math as m
print(m.factorial(4))
Run Output
24
I assigned “m” as a nickname for the math module and used m to call the factorial function.
Previous: Import Modules
Next: Recursion & Factorial
Module Names in Python
Python Functions | Advanced
Let’s understand how Python handles module names and the purpose of the special construct if __name__ == "__main__":. This is one of the most common idioms in Python and is crucial for creating reusable and runnable code.
Every Python file is a module. When a Python file is run, the interpreter sets a few special variables. One of these is __name__. The value of this variable depends on **how** you run the file:
If you run the file directly (e.g., python my_script.py), the interpreter sets __name__ = "__main__".
If you import the file into another module (e.g., import my_script), the interpreter sets __name__ to the name of the file itself (e.g., "my_script").
This allows you to write code that only runs when the file is executed as the main program, but not when it's imported as a module into another script. You can read more in the official documentation for `__main__`.
Let's imagine we have two files. First, a module named module1.py:
File: module1.py
def greet():
print("Hello from module1!")
# This block will ONLY run if module1.py is executed directly
if __name__ == "__main__":
print("module1 is being run directly.")
greet()
Now, let's create a second file, module2.py, that imports and uses `module1`. We can trace its execution below.
File: module2.py
1 import module1
2
3 print("Running code in module2")
4 module1.greet()
Click "Execute" to start the trace.
Program Output
Previous: Create Functions
Next: Recursion & Factorial
Understanding Recursive Functions in Python
Lesson 35
Today, let’s talk about recursive functions. Recursive functions can seem complicated, but they’re not that tough once you get it. Here’s what you need to know:
A recursive function is a function that calls itself directly or indirectly. That’s it in one line. Let’s understand how. The function keeps calling itself until it reaches a stopping point, known as a base case.
Recursive Factorial Program
Now, let’s see a real example with a factorial calculation. Remember, the factorial of a number means multiplying that number by all the smaller numbers down to one. For example, factorial of 5 is 5 × 4 × 3 × 2 × 1, which equals 120.
Let’s write the recursive code for factorial. This is a classic example often used to demonstrate recursion and how a call stack works in programming.
CodeFlow Visualizer: Recursive Factorial
Python Code
1
1
def factorial(n):
2
2
if n == 1:
3
3
return 1
4
4
else:
5
5
return n * factorial(n - 1)
6
6
7
7
value = int(input())
8
8
print(factorial(value))
Code Explanation
Enter a number and click "Execute".
Program Output
Output will appear here...
Hope I am clear. Pause the video and try writing this factorial function in your editor or at 👉 https://codersnote.com/ai-powered-code-compiler/
Previous: Create Functions
Next: Lambda Functions
Lambda Functions in Python
Lesson 36
Now let’s talk about lambda functions. A lambda function is kind of like a shortcut for writing a normal function. First, let’s understand the syntax:
Syntax
lambda arguments : expression
To tell Python you’re writing a lambda, you need to use the lambda keyword first. Then, after lambda, you write your arguments (like a and b). Put a colon, then write your expression (for example, a + b, or any condition). Lambda functions are a core part of what makes Python suitable for functional programming paradigms.
Normal Addition Function
Python Code
def f(a, b):
return a + b
print(f(2, 3))
Run Output
5
This gives the output 5.
Now, let’s convert this to a lambda function. With lambda, you can write the same logic in one line.
Lambda Addition Function
CodeFlow Visualizer: Lambda Addition
Python Code
1
1
rest = lambda a, b: a + b
2
2
print(rest(2, 3))
Click "Execute" to start.
Program Output
Output appears here...
This still prints 5. Here, rest stores the lambda function. Lambda functions don’t have a name, so they’re called anonymous functions. You call them by the variable you assign them to.
Lambda With Multiplication
Python Code
# The expression is changed to a * b
rest = lambda a, b: a * b
print(rest(2, 3))
Run Output
6
Lambda With Conditional (If-Else)
Python Code
# Use a ternary operator for the condition
comp = lambda a, b: "A is greater" if a > b else "A is smaller"
print(comp(2, 3))
print(comp(5, 3))
Run Output
A is smaller
A is greater
Even or Odd With Lambda
Python Code
check_even = lambda a: "even" if a % 2 == 0 else "odd"
print(check_even(200))
# The next line would require user input
# print(check_even(int(input("Enter a number: "))))
Run Output
even
Lambda With For Loop (Multiplying Two Lists)
Let’s say you have two lists, and you want to multiply their matching positions. A great explanation of how `zip` and list comprehensions work together can be found at W3Schools' Python Lambda page.
Python Code
# Using a list comprehension inside a lambda
multi = lambda a, b: [x * y for x, y in zip(a, b)]
print(multi([2, 4, 6], [2, 3, 4]))
Run Output
[4, 12, 24]
Previous: Recursion & Factorial
Next: Reduce Function
Using the Reduce Function
Lesson 37
Welcome back! In this lesson, I'm going to talk about the reduce function. The basic idea: reduce takes a function and a sequence, like a list or a range, and returns a single result by applying that function across the sequence.
The `reduce` function is part of the `functools` module, so it must be imported before use. It's a powerful tool from the world of functional programming, which you can learn more about in resources like Real Python's guide to reduce.
Let’s say I want to calculate the sum of numbers from 1 to 5. Here’s how you write it:
CodeFlow Visualizer: Using Reduce
Python Code
1
1
from functools import reduce
2
2
def add(a, b): return a + b
3
3
num = [1, 2, 3, 4, 5]
4
4
product = reduce(add, num)
5
5
print(product)
Click "Execute" to start.
Program Output
Output appears here...
You can also use reduce to find the factorial of a sequence by changing the operation from `+` to `*`.
Python Code
# Using reduce to calculate factorial of 5 (5*4*3*2*1)
from functools import reduce
print(reduce(lambda a, b: a * b, range(1, 6)))
Run Output
120
Previous: Lambda Functions
Next: Filter Function
Using the Filter Function
Lesson 38
Let’s understand how the filter function works in Python. I’ve found that it’s an easy way to filter items from a list (or other sequences) based on some condition. The filter function takes a function and a sequence. To show you an example, I’m going to start with a simple list. What I want is to print the odd numbers from this list.
CodeFlow Visualizer: Using Filter
Python Code
1
1
a = [1, 2, 3, 4, 5]
2
2
num = filter(lambda x: x % 2 == 1, a)
3
3
print(list(num))
Click "Execute" to start.
Program Output
Output appears here...
Let me explain how filter works step by step: First, filter fetches a value from the list and passes it to the lambda function. The lambda checks if the number is odd (modulus two equals one). If true, the number is included in the result. This check repeats for all numbers. More examples can be found at resources like W3Schools.
If you want to get even numbers instead, you just change the condition to `x % 2 == 0`.
Previous: Reduce Function
Next: Map Function
Using the Map Function
Lesson 39
First, let’s understand how the map function works in Python. What I want is to take each value from a list and transform it with a function. You see, map is different from filter. Map gives you back the same number of items as your list, but transformed. Filter only keeps the ones that fit your condition. Map changes every item in your sequence. For more details, you can refer to the official Python documentation for map.
Let’s write a program to print the square of every number in a list.
CodeFlow Visualizer: Using Map
Python Code
1
1
a = [1, 2, 3, 4, 5]
2
2
num = map(lambda x: x ** 2, a)
3
3
print(list(num))
Click "Execute" to start.
Program Output
Output appears here...
But map returns an object—you have to type cast it to a list first to see the real values. That’s why I use list(num) inside print.
Previous: Filter Function
Next: Reduce vs Filter
Difference Between Map, Filter, and Reduce Functions in Python
Lesson 40
Let’s understand how the map, filter, and reduce functions are different, and when to use each one. What I want is to make it easy for you to see their purpose and usage. These three functions are powerful tools in functional programming, a style you can explore more in resources like this guide from freeCodeCamp.
First, keep this in mind: if you’re using the reduce function, you need to import it from the functools module. Without this import, reduce won’t work.
Now, here’s how they compare:
Map Function
The purpose of the map function is to transform each element in an iterable. Imagine you have a list with five values — if you apply map, it goes through each value one at a time, transforms it (like squaring it), and gives you back all the transformed values in the same-sized sequence.
Filter Function
The filter function is used to filter elements based on a condition. You give it a sequence and an expression (like to print only the odd numbers). It checks your condition for each value. If it’s true, that value stays; if it’s false, it’s skipped. For example, if your expression is only true for values 1, 3, and 5, only those are included in your result.
Reduce Function
Reduce takes your whole sequence and combines it into a single value. If you put in [1, 2, 3, 4, 5], it will keep adding pairs of numbers until there’s just one result—like 1+2=3, then 3+3=6, then 6+4=10, and finally 10+5=15. The output is always one value.
Summary of Differences
All three functions take a function (that’s your logic or operation) and a sequence (like a list or set). For a detailed side-by-side comparison with examples, you can check out this article on Map, Filter and Reduce in Python.
Inputs and Outputs:
Map and filter return special objects that you usually convert to a list or set.
Reduce returns a single value and doesn’t need type casting.
What each one does:
Map: Applies your function to every element in the sequence.
Filter: Only keeps elements where your function returns true.
Reduce: Combines elements into one final value, step by step.
When should you use each?
Use map when you want to change every value in your sequence (like squaring everything). Use filter when you’re including or skipping items based on a condition. Use reduce when you want one summary value (such as the total or product).
Previous: Map Function
Next: List Basics
Deep Dive into List, Set, Tuple, and Dictionary: List Data Type
Lesson 41
Let’s understand how the list data type works in Python. I’m going to start simple and step by step show you what you can do with a list. A list is one of Python's most versatile data structures.
First, let’s create a list with some values. What I want is a list with 10, 20, 30, 40, 50. So I use square brackets and put my numbers inside:
CodeFlow Visualizer: Creating and Modifying a List
Python Code
1
1
a = [10, 20, 30, 40, 50]
2
2
print(a)
3
3
a.append(90)
4
4
print(a)
5
5
print(a.pop(1))
6
6
print(a)
Click "Execute" to start.
Program Output
Output appears here...
Let’s execute the code. You’ll see that all values are printed in the same order.
Now, every list in Python has positions called indexes.
Positive Index
→
0
1
2
3
4
List (a)
→
10
20
30
40
50
Negative Index
→
-5
-4
-3
-2
-1
The first item is at index 0, the next at 1, and so on (this is the positive index). Negative indexes start from -1 at the end and go backward. When you run your code, Python puts these list values in memory and assigns index values to each one.
Using append, the new value always goes to the last position.
You can also use a negative index inside pop. For example, to get the first value using its negative index (-6):
Python Code
a = [10, 20, 30, 40, 50]
print(a.pop(-5)) # Removes and returns item at index -5 (which is 10)
Run Output
10
Let’s execute this—it prints the value at that negative index.
Keep this in mind: append adds just one value. If you want to add several values at once, use the extend function. Extend lets you add iterables (like another list or tuple):
Python Code
a = [10, 20, 30]
a.extend([60, 70, 80]) # Extends list 'a' with elements from another list
print(a)
Run Output
[10, 20, 30, 60, 70, 80]
Now if you want, you can also extend with a tuple.
Next, to remove a value by its actual value (not index), use the remove function. What I want is to remove 20 from my list:
Python Code
a = [10, 20, 30, 40, 50]
a.remove(20) # Removes the first occurrence of value 20
print(a)
Run Output
[10, 30, 40, 50]
After removing 20, the items shift so there are no empty spaces.
Let’s check: if I use pop(1), it now gives me the value that moved into that position.
Duplicates are allowed in lists! Try adding another 50:
Python Code
a = [10, 20, 30]
a.append(50)
a.append(50) # Adds 50 again
print(a)
Run Output
[10, 20, 30, 50, 50]
You see 50 shows twice.
A neat feature is that lists can store different data types. For example, let’s add a float, a string, and a boolean:
Python Code
a = [10, 99.9, "Harish", True, 20] # A heterogeneous list
print(a)
Run Output
[10, 99.9, 'Harish', True, 20]
Here, you see integers, floats, strings, and booleans all together. If a list has all the same type, that’s called a homogeneous list. Mixed types are a heterogeneous list.
Let’s talk about how data gets stored. Each value in your list has its own address in memory, and the list itself has an address too. Your variable (like a) points to this address.
Sometimes, you’ll want to insert a value at a certain index. For that, use the insert function. Imagine I want to add "hello" at position 1:
Python Code
a = [10, 20, 30]
a.insert(1, "hello") # Inserts "hello" at index 1
print(a)
Run Output
[10, 'hello', 20, 30]
Now "hello" is at index 1, and the other values shift forward.
To do concatenation (joining two lists), use +. Imagine Harish has two lists:
Python Code
a = [10, 20, 30]
b = [40, 50, 60]
c = a + b # Concatenates list 'a' and 'b' into new list 'c'
print(c)
Run Output
[10, 20, 30, 40, 50, 60]
Both lists are now together in c.
If you want to count how many times a value appears, use count:
Python Code
a = [10, 30, 10, 40, 10, 50]
print(a.count(10)) # Counts occurrences of 10
Run Output
3
This will print how many 10s are in the list.
Next, Sort function. What I want is to sort a list in ascending order.
Python Code
a = [20, 10, 30, 25]
a.sort() # Sorts the list in-place
print(a)
Run Output
[10, 20, 25, 30]
You see, lists keep the order of your values, just like you type them in. Lists also support both homogeneous and heterogeneous data. And you can modify the list at any time with append, extend, insert, or remove.
Note: lists are mutable—you can change them later. I will discuss mutable and immutable in the next lesson.
Previous: Reduce vs Filter
Next: Mutable vs Immutable
Mutable and Immutable Data Types in Python
Lesson 42
Types of Mutable and Immutable Data
Mutable data types: list, set, dictionary
Immutable data types: int, float, str (string), tuple
First, let’s understand, theoretically, what mutable is. Mutable data types can be changed without creating a new object. For example, with lists, you can add or remove items from the same list.
Immutable data types can’t be changed once made. If you set an integer, string, float, or tuple, you can’t modify the existing value; instead, a new value is created if you assign a new one.
Let’s show this with code.
CodeFlow Visualizer: Mutability Check with id()
Python Code
1
1
a_list = [10, 20] # Mutable list
2
2
print(id(a_list))
3
3
a_list.append(30)
4
4
print(id(a_list)) # Address remains the same
5
5">
6
6
b_int = 100 # Immutable integer
7
7
print(id(b_int))
8
8
b_int = b_int + 1
9
9
print(id(b_int)) # Address changes
Click "Execute" to start.
Program Output
Output appears here...
This proves Python creates new memory for each value, so int is immutable. See, for immutable types, if you assign the same value to two variables, they point to the same address if the value is already in the heap.
Python Code
a = 10
b = 10
print(id(a)) # Same ID
print(id(b)) # Same ID
You see, their addresses are different. For mutable types, Python doesn’t check if a value is already there in memory; every list gets its own address. This fundamental difference is crucial for understanding Python's data model and how variables are handled.
Keep this in mind:
For mutable, existing object changes (like list).
For immutable, new object created when you reassign (like int).
Previous: List Basics
Next: Tuple Overview
Tuple Data Type in Python
Lesson 43
Let’s understand how to use the tuple data type in Python. I’m going to show step by step, so you get every part.
First, to create a tuple, you use parentheses. What I want is to give the values inside ( ):
CodeFlow Visualizer: Creating and Accessing a Tuple
Python Code
1
1
a = (10, 20, 30, 40, 50)
2
2
print(a)
3
3
print(a[1])
Click "Execute" to start.
Program Output
Output appears here...
The tuple elements get index values too, starting from 0, 1, 2, and so on. Based on the index, you can access items directly.
So, you can access a value directly by its index, just like with a list, but you don’t need the pop function here.
Python Code
a = (10, 20, 30)
print(a[1]) #The value at index 1 will be printed.
Run Output
20
Now, what happens if you want to add a value? For example, I want to add 90 to this tuple. You see, tuple is an immutable data type, so we can't add or remove items. Let’s check what happens if you try:
Python Code
a = (10, 20, 30)
a.append(90) # This will cause an error
Run Output
AttributeError: 'tuple' object has no attribute 'append'
You’ll see an error: 'tuple' object has no attribute 'append'. So, it's not possible to add or remove values in a tuple.
Hope I am clear.
Tuples also support heterogeneous data types. Want to see? Here’s an example where I mix a string and a number:
Python Code
a = ("Harish", 10, 99.9, True) # A heterogeneous tuple
print(a)
Run Output
('Harish', 10, 99.9, True)
You’ll see different types of values inside the tuple, printed together.
Tuples also support duplicate values. Let’s add 99.9 twice to show that:
Python Code
a = (10, 99.9, 99.9, 40)
print(a)
Run Output
(10, 99.9, 99.9, 40)
You’ll see duplicates are allowed and get printed as you write them. For more information, you can read about the differences between tuples and lists in Python.
Key points to keep in mind:
Tuple elements keep their order
Tuples allow both homogeneous and heterogeneous data
Tuples are immutable: you can’t change, add, or remove values once created
Previous: Mutable vs Immutable
Next: Set Overview
Set Data Type in Python
Data Structures
Let’s understand how to use the set data type. I’m going to show you step by step how sets work in Python. A set is one of the built-in data types in Python used to store collections of unique data. You can learn more from the official Python documentation on sets.
To create a set, you use curly brackets { } and put values inside:
Python Code
# A set is created using curly braces {}
a = {20, 30, 40}
print(a)
Run Output
{40, 20, 30}
Let’s execute this code. You’ll see a set, but notice the order is not the same as you typed. Sets print values in an unordered way. Keep this in mind—a set returns output in any order, not in the order you typed.
Because sets are unordered, there are no indexes. This means you can't access specific values by position. If you try:
Python Code
a = {20, 30, 40}
# Trying to access an element by index raises an error
print(a[1])
Run Output
TypeError: 'set' object is not subscriptable
You’ll get an error: 'set' object is not subscriptable. So, in sets, there’s no way to print a specific value using indexes.
Sets are mutable—you can change them after creation. To add a value, use the add function:
Python Code
a = {20, 30, 40}
# The add() method inserts a new element
a.add(50)
print(a)
Run Output
{40, 50, 20, 30}
Now 50 is added to the set, but remember, the order is not fixed.
If you need to add multiple values at once, use the update function, and give it an iterable like a list:
Python Code
a = {20, 30, 40}
# The update() method adds all items from an iterable
a.update([60, 70, 90])
print(a)
Run Output
{90, 70, 40, 20, 60, 30}
Now you see more values are added, all at once. Update only accepts iterables.
If you want to remove a specific value, use remove. Let’s say I want to remove 20:
Python Code
a = {20, 30, 40}
# The remove() method deletes a specified element
a.remove(20)
print(a)
Run Output
{30, 40}
The value 20 is no longer in the set.
Keep this in mind: sets do not allow duplicates. If you try to add the same value again, it’s ignored. No error, but it won’t appear twice.
Python Code
# Duplicate values (40) are automatically removed
a = {10, 20, 40, 40, 30}
print(a)
Run Output
{10, 20, 30, 40}
You see only one 40 appears.
Sets support heterogeneous data types. That means you can mix integers, floats, and strings together:
Python Code
# Sets can contain elements of different data types
a = {10, 99.9, "Harish"}
print(a)
Run Output
{99.9, 10, 'Harish'}
All different types are part of the set, printed in any order.
Here’s the summary:
Sets are unordered, so order always changes
Sets don’t support indexing
Sets are mutable (you can add or remove values)
Sets allow both homogeneous and heterogeneous data
No duplicate values in a set
Previous: Tuple Overview
Next: Dictionary Overview
Dictionary Data Type in Python
Data Structures
Let’s understand how to work with dictionaries in Python. I’ll start from scratch so you can see every step clearly. To learn more, you can always refer to the official Python documentation on dictionaries.
To create a dictionary, use curly braces { } and write key-value pairs inside. Each key is followed by a colon and its value. The keys themselves must be of a hashable type. Here’s how:
Python Code
# A dictionary is created with key-value pairs
a = {"name": "Harish", "age": 27}
print(a)
Run Output
{'name': 'Harish', 'age': 27}
Let’s execute this code. You see both the key ("name" and "age") and their values get printed.
If you just want to print the keys, use the keys() function:
Python Code
a = {"name": "Harish", "age": 27}
# The keys() method returns a view of all keys
print(a.keys())
Run Output
dict_keys(['name', 'age'])
You’ll see only the keys: 'name' and 'age'.
To print only the values, use the values() function:
Python Code
a = {"name": "Harish", "age": 27}
# The values() method returns a view of all values
print(a.values())
Run Output
dict_values(['Harish', 27])
Now, you see the values: 'Harish' and 27.
Since dictionaries are mutable, you can add new key-value pairs any time. What I want is to add a contact to the existing dictionary:
Python Code
a = {"name": "Harish", "age": 27}
# A new key-value pair is added
a["contact"] = +91 8681869893
print(a)
Now the dictionary has the new key "contact" with its value.
If you want to get just the value of a given key, use the get() function. For example, to get the age:
Python Code
a = {"name": "Harish", "age": 27}
# The get() method retrieves the value for a given key
print(a.get("age"))
Run Output
27
You’ll get 27 as output.
Let’s understand how dictionaries store things in memory. Both keys and values are stored in the heap segment, and your variable (like a) just has the addresses pointing to them.
If you try adding the same key twice, no error comes up, but only the last value for that key is kept. Dictionaries don’t allow duplicate keys; each must be unique. Duplicate keys will overwrite the previous one.
Dictionaries are unordered before Python 3.7; now they keep insertion order.
They store both keys and values.
Keys must be unique (no duplicates allowed).
Dictionaries are mutable: you can add or change key-values any time.
Previous: Set Overview
Next: Nested Lists
Copy Function and Nested List in Python
Data Structures
Now, let’s discuss the nested list. A nested list is a list inside another list—like a sub-list.
Python Code
Ready
1
1
a = [10, 20, 30, [40, 50], 60]
A list containing integers and another list is created.
2
2
print(a)
The content of list 'a' is sent to the output.
Click "Execute" to start.
Program Output
Output appears here...
Here, [40, 50] is a list within the main list. This is called a nested list.
Previous: Dictionary Overview
Next: Shallow Copy
Shallow Copy in Python
Data Structures
Watch the video above before getting into the next topic to understand the meaning of shallow and deep.
Let’s understand how shallow copy works in Python.
First, think about how learning works. If you just read or watch and don’t practice, you get shallow learning. What I want is for you to try things, not just watch. Actual understanding comes only when you use what you’ve learned. Hope I am clear.
What is a shallow copy? When you perform a shallow copy, you create a new list object, but the elements inside are just references to the objects in the original list. This is especially important for nested lists.
Let’s see how to create a shallow copy using the `copy.copy()` function. First, you need to import the `copy` module.
Python Code
Ready
1
1
import copy
Imports Python's standard `copy` module to get access to copy functions.
2
2
a = [[10, 20], [30, 40]]
The original list `a` is created. It holds two other list objects inside it.
3
3
b = copy.copy(a)
A shallow copy of `a` is created. This means `b` is a new list, but the inner lists (`[10, 20]` and `[30, 40]`) are the exact same objects referenced by `a`.
Click "Execute" to start.
Program Output
Output appears here...
Here, `a` is your original nested list. `b` is your shallow copy. You’ll see they both look the same, but there's something going on under the hood.
If you print the address of both `a` and `b`, they are different. But their inside lists—`[10, 20]` and `[30, 40]`—are still shared by both `a` and `b`.
Now what I’m going to do is `append` a new nested list to `a`:
Python Code
import copy
a = [[10, 20], [30, 40]]
b = copy.copy(a)
# Appending to the top-level list of 'a' only affects 'a'
a.append([50, 60])
print(a)
print(b)
You see, only `a` gets the new `[50, 60]`. It does NOT appear in `b`. That’s because the top-level list was copied.
But let’s change a value inside the nested list:
Python Code
import copy
a = [[10, 20], [30, 40]]
b = copy.copy(a)
# Modifying an element inside a shared nested list affects both
a[0][0] = 99
print(a)
print(b)
Run Output
[[99, 20], [30, 40]]
[[99, 20], [30, 40]]
Now both `a` and `b` show `99` in the nested lists! That’s because both share the inner lists.
Let’s understand why. When you use a shallow copy, Python creates a new main list in memory, but the nested lists inside are not copied. They are linked. Changes inside those nested lists happen in both `a` and `b`. If you just add or remove a whole list at the top level, only the one you changed is affected.
To show you visually: a = [ [99, 20], [30, 40], [50, 60] ] b = [ [99, 20], [30, 40] ]
Both are different top-level lists—but `[99, 20]` and `[30, 40]` are actually the same lists inside memory for both `a` and `b`.
Keep this in mind. Shallow copy just copies the outside. Anything inside a nested list stays connected. If you want a fully separate copy, you’ll need something more. But that’s for the next lesson.
Pause the lesson and step through the code yourself or try it out at 👉 an online compiler to see the reference in action.
In the next lesson, you’ll learn all about deep copy—how to totally separate everything inside the lists. Let’s continue to the next Lesson where we’ll understand how deep copying works!
Previous: Nested Lists
Next: Deep Copy
Deep Copy in Python
Data Structures
Hope you will have 100% clarity on shallow copy. Now I’m moving to the next topic—deep copy. Let’s understand how to turn a shallow copy into a deep copy.
First, let’s understand how to use deep copy. It’s so simple. All you need to do is change the function you use. Instead of `copy.copy()`, there’s a function called `copy.deepcopy()` in the `copy` module.
Here’s what I mean:
Python Code
Ready
1
1
import copy
Imports the `copy` module.
2
2
a = [[10, 20], [30, 40]]
The original list `a` is created.
3
3
b = copy.deepcopy(a)
A deep copy is created. `b` is a new list, and the inner lists inside `b` are also new, completely separate copies.
4
4
a[0][0] = 99
The value in `a`'s inner list is changed. Because `b` is a deep copy, this modification will not affect `b`.
5
5
print(a)
Prints the modified list `a`.
6
6
print(b)
Prints the list `b`, which is completely unchanged.
Click "Execute" to start.
Program Output
Output appears here...
Let’s execute the code. Now, if you see the output, when I change the `10` to `99` in `a`, you’ll notice the modification doesn’t show up in `b`. The change I make to `a` doesn’t affect `b` at all.
First, let’s understand how this works behind the scenes, based on the notes about shallow copy. In shallow copy, Python only copies the main list; the nested lists are shared. So, if you change something inside a nested list, both variables see the change.
With deep copy, Python copies the main list and each nested list too. Each piece gets its own copy. When you use `deepcopy`, both `a` and `b` have their own main list and their own nested lists. The changes in `a` don’t appear in `b`—even the inside lists are fully separate.
You see, when you append a new nested list to `a` or `b`, it only affects that one variable. If you change a value inside `a`’s nested list, it will not show in `b`. That’s the power of deep copy!
One more quick detail: Even when I use deep copy, there’s a thing about memory. Python is smart and efficient with memory. If an object still has a reference (like if the old value 10 is still used somewhere), the garbage collector won’t delete it. It stays until nothing is using it.
Hope I am clear. Now you can see the big difference between shallow copy and deep copy. If you want a full, independent copy, always go for `deepcopy`.
Previous: Shallow Copy
Next: List Slicing
Python Slicing Explained
Data Structures
Our next topic isn’t potato… Just kidding! We’re really talking about slicing in Python. Think about slicing as chopping up a vegetable—cutting it into parts. Just like that, Python lets us “slice” out parts of a list.
First, let’s understand how slicing works. Imagine you have a list—the “vegetable” you want to slice. You can use slicing to grab just the piece you want.
Let’s create a list first:
Python Code
# A simple list of numbers
a = [1, 2, 3, 4, 5, 6, 7]
Run Output
Now what I want is to print only the values from `3` to `6`. Using slicing, I can do this right inside the print function.
Positive Index
→
0
1
2
3
4
5
6
List (a)
→
1
2
3
4
5
6
7
Negative Index
→
-7
-6
-5
-4
-3
-2
-1
Python Code
Ready
1
1
a = [1, 2, 3, 4, 5, 6, 7]
Creates the list that we will slice.
2
2
print(a[2:6])
This slices the list. It starts at index `2` (value `3`) and ends just before index `6` (value `7`), creating a new list with the result.
Click "Execute" to start.
Program Output
Output appears here...
Let’s understand how this works: The starting index is `2` (because index 0 is 1, index 1 is 2, and index 2 is 3). The stopping index is `6`, but, like the `range()` function, slicing’s stop value is exclusive. Hope I am clear.
So, when you write `a[2:5]`, it gives values at index 2, 3, and 4. If you want to print up to the value `6`, you need to give index `6` (since index 6 is value 7).
Try this:
Python Code
a = [1, 2, 3, 4, 5, 6, 7]
print(a[2:6])
Run Output
[3, 4, 5, 6]
Just like `range`, slicing also allows a step value. Now what I want is to print values starting at `2`, up to `6`, with a step of `2`.
Let’s write the code:
Python Code
a = [1, 2, 3, 4, 5, 6, 7]
# The third parameter is the step value
print(a[1:6:2])
Run Output
[2, 4, 6]
The index value of `2` is `1`, so the start is `1`, the stop is `6` (exclusive), and the step is `2`. You see the output: 2, 4, 6.
Let’s understand how slicing works with other data types. Sets don’t work with slicing, because sets have no index. If you try this with a set, Python will give an error: “`TypeError: 'set' object is not subscriptable`.” You can learn more about built-in error types in the official documentation.
But if you use a string with slicing, it works just fine!
Python Code
s = "yay"
# Slicing works on strings too
print(s[0:2])
Run Output
ya
So, except for sets, you can use slicing with iterables like lists and strings.
Previous: Deep Copy
Next: String Basics
Understanding Strings in Python
String Handling
Let’s talk about strings in Python. You see, we can make a string using either single quotes, double quotes, or even triple quotes for multi-line strings. First, let’s see how to create a multi-line string:
Python Code
Ready
1
1
name = """This is Harish
From CodersNote.com by Amend Ed Tech"""
A multi-line string is created using triple-quotes and assigned to the variable `name`.
2
2
print(name)
The content of `name`, including the line break, is printed to the output.
Click "Execute" to start.
Program Output
Output appears here...
Now, let’s look at simple strings too:
Python Code
name = "Harish"
print(name)
Run Output
Harish
Strings are iterable. That means you can move through them, letter by letter. Lists, tuples, dictionaries, sets, and strings are all iterables. Strings are also immutable. This means you cannot change a character inside a string directly. You can learn more about immutable sequences from the official Python documentation.
Each letter in a string has an index, starting at zero. So, if you want to get the 'a' in "Harish", you’d use index `1`.
Python Code
name = "Harish"
print(name[1])
Run Output
a
Keep this in mind—because strings are immutable, you can’t change them in place. For example, if you try to reassign a character like this:
Python Code
name = "Harish"
name[4] = "R"
Run Output
TypeError: 'str' object does not support item assignment
You get an error: 'object does not support item assignment.'
Let’s see an example of memory optimization. Imagine two strings:
Python Code
name = "Harish"
company = "Learn"
# Print memory address of 'a' in both strings
print(id(name[1]))
print(id(company[1]))
Run Output
140722122827184
140722122827184
Both addresses are the same, showing both 'a's point to the same object in memory.
You can use negative indexing too. To get the '2' in the string "alpha123":
Python Code
value = "alpha123"
print(value[-2])
Run Output
2
Slicing lets you get more than one letter. To get 'earn' from "learn to code":
Python Code
s = "learn to code"
print(s[1:5])
Run Output
earn
You can also use step values. To print every second letter up to the tenth letter:
Python Code
s = "learn to code"
print(s[0:10:2])
Run Output
ler t
Now let’s see how to make substrings using a loop. Suppose you want all substrings that are 3 characters long:
Python Code
name = "Harish"
for i in range(len(name)-2):
print(name[i:i+3])
Run Output
Har
ari
ris
ish
This prints every set of 3 characters in the string. To stop the loop when two characters are left, we use `len(name)-2`.
Previous: List Slicing
Next: String Methods
Pre-Built String Functions in Python
String Handling
Let’s understand how to use the pre-built functions in Python strings. Using these functions will make your work so much easier – try them out! You can find a complete list in the official Python documentation.
First, let’s create a string and turn all the letters into uppercase using `upper()`:
Python Code
Ready
1
1
n = "harish"
The string "harish" is assigned to the variable `n`.
2
2
print(n.upper())
The `upper()` method is called on the string. It returns a new string with all characters converted to uppercase.
Click "Execute" to start.
Program Output
Output appears here...
The `lower()` function will do the opposite:
Python Code
n = "HArISH"
print(n.lower())
Run Output
harish
The `swapcase()` function flips the case for every letter:
Python Code
n = "HaRiSh"
print(n.swapcase())
Run Output
hArIsH
The `capitalize()` function makes the first character uppercase and the rest lowercase:
Python Code
n = "harish"
print(n.capitalize())
Run Output
Harish
The `title()` function makes the first character of every word uppercase:
Python Code
n = "harish hello ravi"
print(n.title())
Run Output
Harish Hello Ravi
The `find()` function returns the starting index of a substring:
Python Code
n = "hi hello hi Harish"
print(n.find("hi"))
print(n.find("Harish"))
Run Output
0
12
The `replace()` function returns a new string with specified replacements:
Python Code
n = "hi hello hi Harish"
print(n.replace("hello", "how"))
Run Output
hi how hi Harish
The `join()` method joins the elements of an iterable with a specified separator:
Python Code
n = "hi"
print("*".join(n))
Run Output
h*i
The `split()` method breaks a string into a list of words:
Python Code
n = "hi hello Harish"
print(n.split())
Run Output
['hi', 'hello', 'Harish']
The `isalpha()` method returns `True` if all characters are alphabetic:
The `isalnum()` method returns `True` if all characters are alphanumeric (letters or numbers):
Python Code
print("harish123".isalnum())
print("learn to code".isalnum())
Run Output
True
False
The `startswith()` method checks the beginning of a string:
Python Code
n = "#Harish"
print(n.startswith("#"))
Run Output
True
The `endswith()` method checks the end of a string:
Python Code
n = "#Harish#"
print(n.endswith("#"))
Run Output
True
These are just some of the pre-built string functions in Python. Try all of them in your practice, because they’ll save you a ton of time!
Previous: String Basics
Next: Format Strings
String Format in Python
String Handling
Our next topic is string format. Before we start, let’s think about a real scenario. Imagine Harish is building a website. If someone enrolls in a Java course, the message should say: “Thank you for enrolling Java course.” If the user picks Python, it should say: “Thank you for enrolling our Python course.” What I want is to print dynamic messages in Python!
To do this, let’s understand the format() method. Using string format, you can embed user-provided values right inside your string messages.
First, let’s write a welcome message with a spot for a name. I’ll use curly brackets `{}` in my string where the name should appear. Here’s how it looks:
Python Code
1
msg = "Welcome { }, you enrolled our Learn to Code Python course."
2
name = input("Enter your name: ")
3
final = msg.format(name)
4
print(final)
Code Explanation
Enter a name and click "Execute".
Program Output
Output will appear here...
Let’s execute the code. When you enter your name (say, “Harish”), you see: “Welcome Harish, you enrolled our Learn to Code Python course.”
Now, what I want is to also make the course name dynamic. Here’s how to do it with two inputs:
Python Code
# Using two placeholders for two inputs
msg = "Welcome { }, you enrolled our Learn to Code { } course."
name = input("Enter your name: ")
course = input("Enter course name: ")
final = msg.format(name, course)
print(final)
Run Output
Enter your name: Jeevan
Enter course name: Java
Welcome Jeevan, you enrolled our Learn to Code Java course.
You can also control the order with positional arguments. Zero is the first value, one is the second:
Python Code
msg = "Welcome {1}, you enrolled our {0} course."
# Note: 'course' is the first argument (index 0), 'name' is second (index 1)
final = msg.format("Python", "Harish")
print(final)
Run Output
Welcome Harish, you enrolled our Python course.
Let’s understand keyword arguments. You can give keys instead of just positions. Like this:
Python Code
msg = "Welcome {n}, you enrolled our {c} course."
# Assign values to the keywords 'n' and 'c'
final = msg.format(n="Harish", c="Python")
print(final)
Run Output
Welcome Harish, you enrolled our Python course.
Another tip: you can reuse a value more than once by using the same key or index:
Python Code
msg = "Welcome {n}, you enrolled our {c} course. Thank you, {n}!"
final = msg.format(n="Harish", c="Python")
print(final)
Run Output
Welcome Harish, you enrolled our Python course. Thank you, Harish!
Previous: String Methods
Next: F-Strings
F-Strings in Python
String Handling
Now, let’s understand f-strings in Python. F-strings are an alternative to the format() function. They let you easily put variables and calculations right inside a string and were introduced in Python 3.6.
First, let’s understand the syntax. Just put the letter f (or F) before your string, then use curly brackets `{}` for the values you want to show.
Python Code
Ready
1
a = 5
2
b = 6
3
msg = f"The sum of {a} and {b} is {a+b}"
4
print(msg)
Click "Execute" to start.
Program Output
You can do arithmetic right inside the curly brackets. If you want to multiply:
Python Code
a = 5
b = 6
# The expression is calculated inside the f-string
msg = f"The multiplication of {a} and {b} is {a*b}"
print(msg)
Run Output
The multiplication of 5 and 6 is 30
So, what I want is—just use the `f` at the start of your string, then put any variable or calculation you need in `{ }`. Hope I am clear. F-strings make your code short and super easy to read!
Previous: String Format
Next: Regex Functions
Pre-Built Functions in Python Modules
String Handling | Advanced
In this lesson, let’s understand some pre-built functions from a Python module. I’m going to show how to search for keywords inside a string using Regular Expressions.
First, let’s import the module. We’re using `re`.
Python Code
import re
Let’s start with the search() function to find if a specific pattern is inside a string. If it’s there, `search()` returns a match object.
Python Code
1 import re
2 input_str = "gun one"
3 pattern = "one"
4 result = re.search(pattern, input_str)
5 print(result)
Click "Execute" to start.
Program Output
You can use bool() to check if a match was found:
Python Code
import re
result = re.search("one", "gun one")
print(bool(result))
Run Output
True
To get just the matched text, use the group() function:
Python Code
import re
result = re.search("one", "gun one")
if result:
print(result.group())
Run Output
one
Here is an example with user input:
Python Code
import re
pattern = input("Enter keyword to search: ")
input_str = input("Enter your string: ")
result = re.search(pattern, input_str)
if result:
print("Keyword match:", result.group())
else:
print("Keyword not match")
Run Output
Enter keyword to search: hi
Enter your string: hello hi there
Keyword match: hi
Now, let’s talk about the match() function. This only checks if the pattern is at the very start of the string.
Python Code
import re
result = re.match("one", "gun one") # "gun one" does NOT start with "one"
if result:
print("Keyword match")
else:
print("Keyword not match")
Run Output
Keyword not match
Next is fullmatch(). This only matches if the entire string is exactly the pattern.
Python Code
import re
result = re.fullmatch("gun one", "gun one") # The strings are identical
if result:
print("Keyword match")
else:
print("Keyword not match")
Run Output
Keyword match
Now, let’s understand sub(). This is like find and replace.
Python Code
import re
input_str = "done union"
result = re.sub("un", "open", input_str)
print(result)
Run Output
done openion
Previous: F-Strings
Next: Classes & Objects
Understanding Objects in Python
Object-Oriented Python
Finally, we are at objects! As I said before, as a programmer you need to think of everything as an object. You might wonder why—that answer will come in upcoming lessons.
Let’s understand how objects work, using cars as examples. Every car is an object. It has states (like variables) and behaviors (like functions). If you line up a few cars, they all belong to the “Car” type. In programming, that “type” is what we call a class.
Based on its address in memory, each object is unique—even if they’re all “Car” objects. Let’s see how to write this in code.
First, I’ll create a class called `car`. The code inside the class is executed when the class is first defined.
Python Code
class car:
print("within class")
Run Output
within class
Now, what I want is to add a function inside this class:
Python Code
class car:
def ev_car():
print("within function and class")
Run Output
But nothing prints yet! That’s because Python only runs a function if you call it. What if you try to call it from outside like this? ev_car() You'll get an error because you must first create an object (an instance of the class).
To do this, create an object by calling the class name:
Python Code
c = car() # This creates an object of the car class
Run Output
Now, when you try to call the method using the object, `c.ev_car()`, you get a `TypeError`. Why? Python secretly passes a reference to the object (`c`) as the first argument to the method. The method needs a parameter to receive it. Let’s add one, which we'll call `n`:
Python Code
1 classcar:
2 defev_car(n):
3 print("within function and class")
4 print(n)
5
6 c = car()
7 c.ev_car()
Click "Execute" to start.
Program Output
The function now prints the object's memory address. To confirm the object `c` and the parameter `n` are the same, let's check their `id()`s.
Python Code
class car:
def ev_car(n):
print(f"ID inside method: {id(n)}")
c = car()
print(f"ID outside method: {id(c)}")
c.ev_car()
Run Output
ID outside method: 2125588320848
ID inside method: 2125588320848
Both `id`s match! By convention, programmers call this special first parameter `self`. This function is called an instance method because it belongs to an instance (object) of the class.
Now let's use `self` to create an instance variable that belongs to the object.
Python Code
class car:
def ev_car(self):
self.name = "Harish" # 'self.name' is an instance variable
print(self.name)
c = car()
c.ev_car()
print(c.name) # We can access it outside too!
Run Output
Harish
Harish
Keep this in mind: you use `self` inside methods to work with variables that belong to the object. Outside the class, you use your object reference (like `c`).
Previous: Regex Functions
Next: Class Examples
Tracing Object Creation in Python
Object-Oriented Python
Now, let’s write another program and trace what happens in memory as it runs. Let’s use a “Dog” as our example.
Here’s how the code looks:
Python Code
1 classdog:
2 defdog(self):
3 self.name = "John"
4 self.breed = "Husky"
5 print(self.name)
6 print(self.breed)
7
8 defstart():
9 c = dog()
10 c.dog()
11 print(c.name)
12 print(c.breed)
13
14 start()
Click "Execute" to start the trace.
Program Output
I want you to keep this in mind: The object is made in the heap memory. `self` and `c` both point to the same object in memory, so you can use either to get the name or breed.
Previous: Classes & Objects
Next: __new__ Method
Arguments and Parameters in Python Objects
Object-Oriented Python
Let’s recall what arguments and parameters are, and see how we use them with objects. This helps you make your Python classes work with different values!
Here’s what I want: When calling a function, I send two arguments. The function takes those with its parameters.
Python Code
1 classdog:
2 defdog(self, name, breed):
3 self.name = name
4 self.breed = breed
5 print(self.name)
6 print(self.breed)
7
8 defstart():
9 dog1 = dog()
10 dog1.dog("John", "Husky")
11 print(dog1.name)
12 print(dog1.breed)
13
14 start()
Click "Execute" to start the trace.
Program Output
Keep this in mind: Arguments are what you pass in (like `"John"`, `"Husky"`) and parameters are what the function receives (like `name`, `breed`).
Previous: Class Examples
Next: The __new__ Method
The __init__ Method
Object-Oriented Python
Let’s understand the __init__ method (pronounced “dunder init” because it has double underscores). This is a special method in Python that runs automatically when you create a new object from a class. It's often called a "constructor."
Syntax
To define the __init__ method, use this format:
Python Code
# A dunder method has double underscores at the beginning and end.
def __init__(self):
# initialization code
Example: Using __init__ in a Class
Let’s write a simple example using the __init__ method:
Python Code
1 classDog:
2 def__init__(self):
3 print("Inside the __init__ method")
4 self.name = "John"
5 self.breed = "Husky"
6
7 defstart():
8 d = Dog()
9 print("Inside the start function")
10
11 start()
Click "Execute" to start the trace.
Program Output
Notice that we never called __init__() directly. But when we created an object with d = Dog(), Python automatically ran the __init__ method for us.
You do not need to call the __init__ method manually. Python takes care of it every time you create a new object.
Previous: __new__
Next: __init__ with Args
Understanding the dunder __init__ method
Object-Oriented Python
In this lesson, I’m going to write a program using the __init__ method with parameters. We’ve already seen what the __init__ method is. Now let's see how to pass data to it.
Here, you can pass an argument inside the parenthesis when you create the object, and `__init__` will receive it.
Python Code
1 classStudent:
2 def__init__(self, name):
3 self.name = name
4 print(self.name)
5
6 student1 = Student("Harish")
Click "Execute" to start the trace.
Program Output
Now, let’s confirm the object's address is passed to `self`.
Python Code
class Student:
def __init__(self, name):
self.name = name
print(f"Address of self: {id(self)}")
yes = Student("Harish")
print(f"Address of yes reference: {id(yes)}")
Run Output
Address of self: 2475459383696
Address of yes reference: 2475459383696
Now I’m going to create one more function called `display`. Let’s check whether we can print or access this instance variable from the `display` function.
Python Code
class Student:
def __init__(self, name):
self.name = name
print(f"Address in __init__: {id(self)}")
def display(self):
print(f"Name: {self.name}")
print(f"Address in display: {id(self)}")
yes = Student("Harish")
print(f"Address of reference: {id(yes)}")
yes.display()
Run Output
Address in __init__: 2475459383888
Address of reference: 2475459383888
Name: Harish
Address in display: 2475459383888
You see, all the addresses are the same. The instance variable is stored within the object, and any method of that class can access it using `self`.
Previous: __init__ Method
Next: Class Variables
Static Method in Python
Object-Oriented Python | Advanced
In this lesson, I’m going to talk to you about static methods in Python. Earlier, we discussed class methods, but now let’s see how a static method works. A static method is a method that belongs to a class rather than an instance of the class and doesn't receive any implicit first argument (like `self`).
First, I’ll create a class called student. Inside this class, I’ll define a function named staticone. If I try to call this like an instance method, Python will automatically pass the object as the first argument, leading to an error if the function doesn't expect it.
Python Code
class student:
# This function doesn't accept the automatic 'self' argument
def staticone():
print("Within function")
obj = student()
obj.staticone() # This causes the error
Run Output
TypeError: student.staticone() takes 0 positional arguments but 1 was given
To convert this method into a true static method, we use the @staticmethod decorator. This built-in decorator tells Python that the method does not take an implicit first argument. You can read more about them in the excellent guide on instance, class, and static methods. After converting, I don’t need the `self` parameter anymore.
To show you an example with arguments, I’ll pass two values while calling the `staticone` function.
Python Code
1 classstudent:
2 @staticmethod
3 defstaticone(a, b):
4 print(a + b)
5
6 obj = student()
7 obj.staticone(5, 3)
Click "Execute" to start the trace.
Program Output
What I want is for you to remember—@staticmethod is a built-in decorator. For now, just keep this in mind. We’ll cover closures and other decorators in a future lesson.
Previous: Class Variables
Next: Super Function
Super Function in Python
Object-Oriented Python | Advanced
Today, I'm going to talk about the super() function. Using this, we can call a parent class method from a child class, which is essential for extending functionality in inheritance.
First, let's look at the code. I’ll create a Parent class and a Child class that inherits from it. Both will have an `__init__` method (the constructor).
Python Code
1 classParent:
2 def__init__(self, name):
3 self.name = name
4 print(self.name)
5
6 classChild(Parent):
7 def__init__(self, name, age):
8 super().__init__(name)
9 self.age = age
10 print(self.age)
11
12 obj = Child("Harish", 27)
Click "Execute" to start the trace.
Program Output
When the `Child` object is created, its `__init__` method calls `super().__init__(name)`. This delegates the `name` initialization to the `Parent` class. Then, the `Child` class handles its own specific initialization for `age`. You can find more examples of `super()` in the W3Schools Python tutorial.
Now, let’s say I want to change the method name from `__init__` to `data`. The same principle applies.
Python Code
class Parent:
def data(self, name):
self.name = name
print(f"Parent sets name: {self.name}")
class Child(Parent):
def data(self, name, age):
super().data(name) # Call parent's data method
self.age = age
print(f"Child sets age: {self.age}")
obj = Child()
obj.data("Harish", 27)
Run Output
Parent sets name: Harish
Child sets age: 27
Previous: Static Method
Next: Inheritance Basics
Program to Store Multiple Students’ Values in Python
Object-Oriented Python | Advanced
Let’s understand how to store multiple students’ details like name, gender, and school using classes in Python.
Version 1: Using Only Instance Variables
First, we can store all data in instance variables, which belong to each specific object.
You see, the same values might be stored multiple times (like `"Tagore"`). This wastes memory.
Version 2: Using a Class Variable
To use memory more efficiently, we can create a single class variable for `school` so it isn’t repeated in every object. A class variable is shared by all instances of a class. You can read more about the difference in this DigitalOcean tutorial.
Python Code
1 classStudent:
2 school = "Tagore"
3
4 defdata(self, name, gender):
5 self.name = name
6 self.gender = gender
7
8 g1 = Student()
9 g1.data("Harish", "male")
10 print(g1.name, g1.gender, Student.school)
Click "Execute" to start the trace.
Program Output
Viewing Object and Class Data
All the instance variables inside each object are stored in a special dictionary. You can view it with __dict__.
Python Code
class Student:
school = "Tagore"
def data(self, name, gender):
self.name = name
self.gender = gender
g1 = Student()
g1.data("Harish", "male")
# The object's __dict__ only contains instance variables
print(g1.__dict__)
Run Output
{'name': 'Harish', 'gender': 'male'}
To see the class variable, you can print the class's `__dict__`:
Python Code
# Continuing from the previous example...
# The class's __dict__ contains class variables and methods
print(Student.__dict__)
Keep this in mind: using a class variable saves memory if the information is the same for every student object. You can try these code snippets on an online platform like CodersNote Compiler to experiment further.
Previous: init with Args
Next: Static Methods
Program Using Two Classes and Introduction to Inheritance
Object-Oriented Python | Advanced
First, let’s write a program with two independent classes, class A and class B.
Python Code
class A:
def a_fun(self):
print("within a function")
class B:
def b_fun(self):
print("within B function")
a = A()
b = B()
a.a_fun()
b.b_fun()
Run Output
within a function
within B function
In this example, each class is separate, and to use their methods, we must create a separate object for each one (a for class A, b for class B).
Inheritance allows you to reuse the functions and variables from one class (the parent or base class) in another class (the child class). This means you don't have to rewrite the same code again and again.
To inherit, you just put the parent class name inside parentheses next to the child class name.
Python Code
1 classA:
2 defa_fun(self):
3 print("within a function")
4
5 classB(A):
6 defb_fun(self):
7 print("within B function")
8
9 b = B()
10 b.a_fun()
11 b.b_fun()
Click "Execute" to start the trace.
Program Output
In the next lesson, you’ll learn about the different types of inheritance. Go ahead and check it out!
Previous: Super Function
Next: Inheritance Types
Types of Inheritance in Python
Object-Oriented Python | Advanced
Let’s look at the different types of inheritance in Python. I’ve found that understanding the examples makes it much easier.
Single Inheritance
Here, we have one parent class and one child class. The child class inherits the state and behavior of the parent class.
Python Code
1 classA:
2 defmessage(self):
3 print("within function")
4
5 classB(A):
6 pass
7
8 b = B()
9 b.message()
Click "Execute" to start traceback...
Program Output
Multiple Inheritance
For multiple inheritance, a child class inherits from two or more parent classes.
Python Code
class A:
def message(self): print("within function A")
class B:
def message1(self): print("within message B")
class C(A, B): pass
c = C()
c.message()
c.message1()
Run Output
within function A
within message B
Multi-level Inheritance
In multi-level inheritance, a child class inherits from a parent, which itself inherits from a grandparent class.
Python Code
class A:
def message(self): print("within function A")
class B(A):
def message1(self): print("within function B")
class C(B): pass
c = C()
c.message() # Inherited from A through B
c.message1() # Inherited from B
Run Output
within function A
within function B
Hierarchical Inheritance
In hierarchical inheritance, multiple child classes inherit from a single parent class.
Python Code
class A:
def message(self): print("message from A")
class B(A): pass
class C(A): pass
b, c = B(), C()
b.message()
c.message()
Run Output
message from A
message from A
Hybrid Inheritance and the Diamond Problem
Hybrid inheritance mixes different types of inheritance hierarchies. This can lead to the diamond problem, where a class inherits a method from the same ancestor through multiple paths. Python solves this ambiguity using the Method Resolution Order (MRO). For a technical deep-dive, see this guide to MRO.
Python Code
class S:
def run(self): print("S run")
class A(S): pass
class B(S): pass
class C(A, B): pass
c = C()
c.run()
# The __mro__ attribute shows Python's method lookup order
print(C.__mro__)
Run Output
S run
(, , , , )
Previous: Inheritance Basics
Next: Method Overriding
Method Overriding in Python
Object-Oriented Python | Advanced
Let’s understand what method overriding means. Method overriding is all about changing or replacing an inherited method in a child class with a a new implementation.
By defining a method in the child class with the exact same name as in the parent class, the child's version takes precedence.
Python Code
1 classA:
2 defmessage(self):
3 print("within A function")
4
5 classB(A):
6 defmessage(self):
7 print("within B function")
8
9 b = B()
10 b.message()
Program Output
When we call b.message(), it prints "within B function." Even though `B` inherited `message()`, its own version took over. Read more about overriding on this GeeksForGeeks article.
Previous: Inheritance Types
Next: Special Methods
Specialization Method in Python
Object-Oriented Python | Advanced
Let’s understand what a specialization method is. This happens when you inherit a parent class into a child class, and then **add a new method** in the child class that doesn't exist in the parent. This lets the child class "specialize" and have unique behaviors.
First, we show simple inheritance to demonstrate the baseline.
Python Code
class A:
def a_fun(self):
print("within function A")
class B(A):
pass # B is currently identical to A
b = B()
b.a_fun()
Run Output
within function A
Now, to show specialization, I add a new function inside `class B`.
Python Code
1 classA:
2 defa_fun(self):
3 print("within A function")
4
5 classB(A):
6 defb_fun(self):
7 print("within B's special function")
8
9 b = B()
10 b.a_fun()
11 b.b_fun()
Program Output
The new method `b_fun` is the specialization method because it's unique to the `B` class. This allows you to build powerful, layered class structures. You can learn more about creating modular code in this guide to modules and packages
Previous: Method Overriding
Next: Polymorphism
Zomato App Example: Inheritance, Overriding, and Specialization
Object-Oriented Python | Advanced
Let's write a program using the Zomato food delivery application as our example. Imagine there is the main Zomato app, a special veggie app, a non-veg app, and a grocery (Blinkit) app. For more on how real-world systems are designed, you can read about Service-Oriented Architecture.
First, I create a main class called `Zomato`. Then, I make three more classes—`VegZomato`, `NonVegZomato`, and `Blinkit`—that all inherit from `Zomato`. I use method overriding to customize the `menu()` method in each child class and add a specialization method (`gold_pos`) to `Blinkit`.
Python Code
1 classZomato:
2 defmenu(self):
3 print("food listed")
4
5 deforder(self):
6 print("ordered")
7
8 defdeliver(self):
9 print("order delivered")
10
11 classVegZomato(Zomato):
12 defmenu(self):
13 print("veg food listed")
14
15 classNonVegZomato(Zomato):
16 defmenu(self):
17 print("non-veg food listed")
18
19 classBlinkit(Zomato):
20 defmenu(self):
21 print("grocery listed")
22
23 defgold_pos(self):
24 print("you are eligible for free delivery")
25
26 veg = VegZomato()
27 nonveg = NonVegZomato()
28 blinkit = Blinkit()
29
30 veg.menu()
31 veg.order()
32 veg.deliver()
33
34 nonveg.menu()
35 nonveg.order()
36 nonveg.deliver()
37
38 blinkit.menu()
39 blinkit.order()
40 blinkit.deliver()
41 blinkit.gold_pos()
Click "Execute" to start the trace.
Program Output
Keep this in mind: Inheritance lets each specialized class reuse Zomato’s features, method overriding customizes them, and specialization adds new ones.
Previous: Special Methods
Next: Polymorphism
Polymorphism in Python
Object-Oriented Python | Advanced
Let’s talk about polymorphism. When you hear “polymorphism,” just remember it means "many forms"—so one function can have many different behaviors depending on which object it is used with.
What I want is: If I create a single calling function that can give multiple outputs (one for veg, one for non-veg, one for grocery), then I achieve polymorphism.
Python Code
1 # Zomato, VegZomato etc. classes defined above...
2 def display(ref):
3 ref.menu()
4 ref.order()
5 ref.deliver()
6 if type(ref) == Blinkit:
7 ref.gold_pos()
8
9 veg = VegZomato()
10 display(veg)
Click "Execute" to start the trace.
Program Output
This is polymorphism: a single function (`display`) handles many forms (different objects) and gives different outputs. Learn more about this powerful concept from freeCodeCamp's guide to Polymorphism.
Previous: Inheritance Examples
Next: Override vs Overload
Polymorphism: Method Overriding and Method Overloading
Object-Oriented Python | Advanced
Let’s dive into two key topics in polymorphism: method overriding and method overloading.
Method Overriding with Polymorphism
I inherited the `Zomato` class into `VegZomato` and `NonVegZomato`. Each time, I overrode the `menu` function. This is polymorphism in action.
veg food listed
ordered
order delivered
----------
non-veg food listed
ordered
order delivered
Method Overloading in Python
In Python, we can’t achieve true method overloading like in Java, but we can use default arguments to get similar behavior.
Python Code
1 class Math:
2 def add(self, a=0, b=0, c=0):
3 print(a + b + c)
4
5 m = Math()
6 m.add(10, 20)
7 m.add(10, 20, 30)
Click "Execute" to start.
Program Output
One function gives many outputs—this is also a form of polymorphism. This is a common pattern for creating flexible functions and you can learn more about Python function arguments here.
Previous: Polymorphism
Next: Encapsulation
Encapsulation in Python
Object-Oriented Python | Advanced
Let’s understand encapsulation with a simple example. Using encapsulation, we can restrict direct access to some of an object's components, which is a fundamental principle of object-oriented programming. This is typically done by making variables private.
To make an instance variable private in Python, you prefix its name with a double underscore (e.g., self.__amount). This tells Python to "mangle" the attribute name, making it harder to access from outside the class.
First, let’s see what happens when we try to access a private variable directly.
Python Code
class BankAccount:
def __init__(self, amount):
# The __ makes this variable private
self.__amount = amount
# Creating an object with 1000 balance
b = BankAccount(1000)
# This will not work and will cause an error
print(b.__amount)
Run Output
AttributeError: 'BankAccount' object has no attribute '__amount'
To access and modify this private data safely, we use public methods, often called getters and setters.
Python Code
1 classBankAccount:
2 def __init__(self, amount):
3 self.__amount = amount# Private variable
4
5 def get_amount(self): # Getter
6 returnself.__amount
7
8 def set_amount(self, amount): # Setter
9 self.__amount = amount
10
11 b = BankAccount(1000)
12
13 print(b.get_amount())
14
15 b.set_amount(500)
16 print(b.get_amount())
Click "Execute" to start the trace.
Program Output
What I want is for you to remember:
Private variables protect data from being accessed or changed directly from outside the class.
You can only interact with private data through public methods (getters and setters) inside the class. Learn more from this GeeksForGeeks guide on encapsulation.
Previous: Override vs Overload
Next: Abstraction
Abstraction in Python
Object-Oriented Python | Advanced
Let’s understand what abstraction means. Abstraction is about hiding the complex implementation details and showing only the essential features of the object. A key part of this in Python is the concept of an Abstract Base Class (ABC).
An abstract class can define methods that do not have any implementation. These are called abstract methods. Any child class that inherits from this abstract class is then **forced** to provide its own implementation for these methods. This acts like a contract or a blueprint for all child classes.
To create an abstract class, we use the `ABC` class and `@abstractmethod` decorator from the `abc` module.
Python Code
1 from abc import ABC, abstractmethod
2
3 classLearnToCode(ABC):
4 @abstractmethod
5 def course_list(self):
6 pass
7
8 classKids(LearnToCode):
9 def course_list(self):
10 print("kids course listed")
11
12 # ... Other child classes like NonIT and Professionals would also be defined ...
13
14 k = Kids()
15 k.course_list()
Click "Execute" to start the trace.
Program Output
What I want is for you to see that, with abstraction, we hide the implementation details in the parent and force every child class to handle the logic in its own way. You can't even create an object of `LearnToCode` directly anymore, because it has an unimplemented abstract method. Read more on the official Python `abc` module documentation.
Previous: Encapsulation
Next: File Read Methods
File Handling in Python
File Handling
Let’s understand how file handling helps you. When you want to access a text file, whether it’s on your computer or a server, file handling lets your Python program read from or write to that file. To see all the available modes, you can check out the official documentation for the `open()` function.
In my example, I have a text file called textfile.txt with the message: “Thank you for enrolling”. To read this file, we use the `open()` function with the mode `"r"` for "read".
Python Code
1 r = open("textfile.txt", "r")
2 print(r.read())
3 r.close() # Good practice to close the file
Click "Execute" to start the trace.
Program Output
Next, you can use readline(). If you use `r.readline()`, it only prints the first line inside your text file.
Python Code
# Reading only the first line
r = open("textfile.txt", "r")
print(r.readline())
r.close()
Run Output
This is Harish.
If you want to print just the first 10 characters of the first line, you can pass a size argument: `r.readline(10)`.
Python Code
# Reading the first 10 characters of the first line
r = open("textfile.txt", "r")
print(r.readline(10))
r.close()
Run Output
This is Ha
If you call `readline()` multiple times, it will read subsequent lines.
Python Code
# Printing the first and second lines
r = open("textfile.txt", "r")
print(r.readline())
print(r.readline())
r.close()
Run Output
This is Harish.
Please give your honest feedback...
There’s also readlines(). When you use `r.readlines()`, it returns a list, with each line from your file as an item.
Python Code
# Reading all lines and returning as a list
r = open("textfile.txt", "r")
print(r.readlines())
r.close()
Run Output
['This is Harish.\n', 'Please give your honest feedback...']
Keep this in mind when you work with files—you’re working with lists if you use `readlines()`, and strings if you use `read()` or `readline()`.
Previous: Abstraction
Next: File Write Methods
Write and Writelines Functions in Python File Handling
File Handling
Let’s understand how you can write to files in Python. To add a message to your text file, you’ll use the write() function.
First, you open your file with open("textfile.txt", "w"). The `"w"` mode means write. When you use this mode, it deletes anything that was in the file before and puts your new message.
Python Code
1 w = open("textfile.txt", "w")
2 w.write("Thank you for enrolling")
3 w.close()
Click "Execute" to start the trace.
textfile.txt (after execution)
Now, what if you want to keep your old message and add something to it? You’ll use append mode, which is `"a"`.
Python Code
# Appending a message to an existing file
w = open("textfile.txt", "a")
w.write(" by Harish")
w.close()
What I want is to show you how to create a duplicate file and copy content to it. Using a `for` loop, you can copy each line from your original to your new file. This is a common pattern for file processing and you can learn more about it in this Real Python guide.
Python Code
# Create a duplicate file and copy contents
w = open("newfile.txt", "w") # Create or overwrite the new file
r = open("textfile.txt", "r") # Open the source file to read
for i in r:
w.write(i) # Write each line from source to destination
w.close()
r.close()
Don’t forget: if a file doesn’t exist, the Python interpreter will create it when you try to write (`"w"`) or append (`"a"`). If the file does exist, it just writes or appends as you asked.
Previous: File Read Methods
Next: Closures
Closer and Decorator: Understanding Nested Functions
Closures & Decorators | Advanced
First, let’s understand how nested functions work. A nested function is simply a function that is defined inside another function.
Python Code
1 defouter():
2 definner():
3 print("within inner function")
4
5 inner()
6
7 outer()
Click "Execute" to start the trace.
Program Output
Keep this in mind: A function won’t execute unless you call it. You can learn more about function definitions from the official Python tutorial.
Previous: File Write Methods
Next: Closures
Closures in Python
Closures & Decorators | Advanced
Let’s understand closures with a simple example. A closure exists when a nested function remembers and has access to variables from its containing (enclosing) scope, even after the outer function has finished executing. We can use this to call an `inner` function from outside the `outer` function.
Python Code
1 defouter():
2 definner():
3 print("within inner function")
4 return inner
5
6 add = outer()
7
8 add() # Call the inner function via the 'add' reference
Click "Execute" to start the trace.
Program Output
To confirm that `add` and `inner` are the same function object, you can check their memory address with `id()`. Read more on this in this GeeksForGeeks article on closures.
Previous: Nested Functions
Next: Decorators
Decorators in Python
Closures & Decorators | Advanced
Now let’s understand how decorators work. A decorator is a function that takes another function as an argument, adds some functionality, and then returns another function, all without altering the source code of the original function. It's syntactic sugar for a closure.
Python Code
def mul(a, b):
print(a * b)
mul(10, 20)
mul(10, 0)
Run Output
200
0
Now, let’s use the @ syntax to apply a decorator that adds input validation.
Exception Handling: Syntax Error vs Runtime Exception
Exception Handling
Let’s understand the difference between a syntax error and a runtime exception.
A SyntaxError happens when your code violates the rules of the Python language. The program won't run at all. This can be caused by a missing parenthesis or colon.
Python Code
# Missing close parenthesis
print("Harish"
Run Output
SyntaxError: unexpected EOF while parsing
A runtime exception occurs while the program is running. The code is syntactically correct, but an error occurs during execution. The program will run up until the line that causes the error.
Python Code
# Accessing an index that doesn't exist
my_list = [1, 2, 3]
print(my_list[5])
Run Output
IndexError: list index out of range
Another common example is a `ValueError` when trying to convert an invalid input.
Python Code
# Entering a string when an integer is expected
a = int(input("Enter a value: "))
print(a)
Run Output
Enter a value: Harish
ValueError: invalid literal for int() with base 10: 'Harish'
Previous: Decorators
Next: Try Except Else
Exception Handling in Python
Exception Handling
Let’s understand how exception handling works in Python. This lets your app handle errors gracefully without crashing.
To avoid crashes, we use a try...except block. You place the lines that could cause errors inside the `try` block. For an in-depth reference, see the official Python tutorial on Errors and Exceptions.
Python Code
1 print("I")
2 try:
3 num = int(input())
4 except ValueError as e:
5 print("Give int value")
6 print(e)
7 else:
8 print(num)
9 print("Thank you")
Code Explanation
Enter a value and click "Execute".
Program Output
Now, what I want is to catch multiple specific errors.
Python Code
try:
num = int(input("Enter a value: "))
mylist = [1, 2, 3]
print(mylist[num])
except ValueError:
print("Give int value")
except IndexError:
print("Enter a right index value")
Previous: Error Types
Next: Finally & Raise
Manual Exception Raising and the Finally Block
Exception Handling | Advanced
Let’s understand how to generate exceptions manually and how the `finally` block works.
No matter if your `try` block has an exception or not, the `finally` block always executes. This is useful for cleanup actions, like closing a file.
Python Code
try:
num = int(input("Enter value: "))
except ValueError as e:
print("Please give an int value")
else:
print(num)
finally:
print("Thank you") # This always runs
Now, imagine you want to create your own error conditions. You can do this with the `raise` keyword.
Python Code
1 def voting(a):
2 if a >= 18:
3 print("eligible for voting")
4 else:
5 raise ValueError("Not eligible")
6
7 voting(11)
Click "Execute" to start the trace.
Program Output
Previous: Try Except Else
Next: Custom Exceptions
Custom Exceptions in Python
Exception Handling | Advanced
Let’s understand custom exceptions. Using encapsulation, we can create our own error types to make our code more readable and specific. When a variable is private, you can’t directly access or change it from outside the class.
To create a custom exception, you simply define a new class that inherits from Python's base Exception class. You can learn more about the exception hierarchy from the official Python documentation.
Python Code
1 classMyError(Exception):
2 pass
3
4 def voting(a):
5 if a >= 18:
6 print("Eligible for voting")
7 else:
8 raise MyError("You are not eligible")
9
10 try:
11 voting(11)
12 except MyError as e:
13 print(e)
Click "Execute" to start the trace.
Program Output
Previous: Finally & Raise
Next
CodeAssist AI Compiler
Write, execute, and debug code in python languages with AI-powered assistance
Code Editor
Output & Results
Execution Output
// Output will appear here after code execution
// Use AI Debug to get detailed error explanations