Course Overview

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!

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

A diagram titled 'Python's Core Strengths' shows five key features contributing to 'Python's Versatility': Simple Syntax, Flexibility, Object-Oriented, Platform Independent, and Extensive Libraries.
  • 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!

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.


An infographic titled 'How a Microprocessor Works' explains the basic operation of a CPU using a question-and-answer format between two cartoon characters.

On the left side, representing the 'OFF' state (0):
A red 'OFF' switch is shown, connected to a battery and a 'V' (voltage) symbol, indicating low voltage. An arrow points from this setup to a CPU icon, which then points to the number '0', signifying that low voltage corresponds to an OFF state or a 0.

On the right side, representing the 'ON' state (1):
A green 'ON' switch is shown, also connected to a battery and a 'V' (voltage) symbol, indicating high voltage. An arrow points from this setup to a CPU icon, which then points to the number '1', signifying that high voltage corresponds to an ON state or a 1.

In the center, a conversation takes place between a male character (left) and a female character (right):

Male character asks: 'What is the CPU made of?'
Female character replies: 'It's built using semiconductor technology and contains crores of nano transistors.'

Male character asks: 'How do transistors work?'
Female character replies: 'They act like on/off switches. Low voltage means off (0), and high voltage means on (1).'

Male character asks: 'So, how do we communicate with the computer?'
Female character replies: 'By giving high and low voltages to transistors, which the CPU reads as 0s and 1s.'

The infographic uses a blue background with white, green, and red elements for clarity.

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.

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

A diagram illustrating the state and behavior of an object, using a car as an example. The image shows a car icon at the top, branching into two main categories:

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.

Key takeaway: Variables represent object states, while functions represent object behaviors.

Compiler vs Interpreter

Lesson 5

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.

A diagram illustrating the difference between a compiler and an interpreter. The top section, labeled

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!

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:


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!

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!

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...

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.

An infographic titled

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

An image displaying a list python variable

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.

Python Code

Ready
1
1
fruit_prices = {"apple": 130, "orange": 110, "banana": 80}
Created a dictionary variable: fruit_prices.
2
2
print(fruit_prices)
Printing the dictionary: fruit_prices.
3
3
print(type(fruit_prices)) # Output: <class 'dict'>
Printing the type of fruit_prices.
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!

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.

CodeFlow Visualizer: Implicit Casting (int + float)

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'>

Run Output

['h', 'a', 'r', 'i', 's', 'h'] <class 'list'> ('h', 'a', 'r', 'i', 's', 'h') <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.

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.

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!

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.

Other Arithmetic Operations

Let’s look at a few more arithmetic operations. For more detail, you can refer to the official documentation on operators.

Python Code

# 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.

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.

Logical Operators

Lesson 15


An educational infographic titled

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 > b and a > 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 > b and a > 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 > b or a < 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(not a > 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!

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.

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


A graphic titled

Let's focus on calculating the remainder for a specific number now. For those who want a manual method, here are three steps:

  1. First, divide the number by 2.
  2. Then, use the coefficient (the quotient/whole part from the division) and multiply it by 2.
  3. 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
if remainder == 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.

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:

A flowchart titled 'If Statement Flowchart' depicts the decision-making process of an 'If Statement' in Python programming. 

On the left, a flowchart begins with 'Start,' leading to 'Condition True?'. An arrow from 'Condition True?' points to a hand illustration. Below the hand, 'Execute Statements' is written, with an arrow leading to 'End Program.' An alternative path from 'Condition True?' directly leads to 'End Program.'

Above the hand, two thought bubbles illustrate outcomes:

A green bubble labeled 'Condition is True' states 'Execute statements under if.'

A red bubble labeled 'Condition is False' states 'Skip statements under if.'

On the right, a dialogue titled 'Understanding the If Statement' explains the concept through a conversation:

Question (blue bubble): 'What happens when the program runs and encounters an if statement?'

Answer (green bubble): 'It checks the condition. If true, it executes the code under if. If false, it skips the code and ends the program.'

Question (blue bubble): 'Can you give me an example?'

Answer (green bubble): 'Imagine a program checking voting eligibility. It asks for age, and if it's 18 or older, it prints that they are eligible.

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
if age >= 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.

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:

A flowchart titled

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
if age >= 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!

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.


A flowchart titled

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
if age > 60:
3
3
    print("Senior citizen.")
4
4
elif age > 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.

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
if num > 0:
3
3
    rem = num % 2
4
4
    if rem == 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!

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

Python Code

numbers = [1, 2, 3, 4, 5]
a = iter(numbers)
print(next(a))
print(next(a))
print(next(a))
print(next(a))
print(next(a))

Run Output

1
2
3
4
5

This prints 1, 2, 3, 4, 5 each on a new line.

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!

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!


A flowchart titled

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 in count:
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!

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 in range(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.

For example:
range(1, 10, 2) → prints: 1, 3, 5, 7, 9
range(10, 0, -2) → prints: 10, 8, 6, 4, 2

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.

Here’s the more efficient version:

CodeFlow Visualizer: Efficient Multiplication Table

Python Code

1
1
num = int(input("Enter a number: "))
2
2
for i in range(num, num * 10 + 1, num):
3
3
    print(num, "X", i // num, "=", i)

Code Explanation

Enter a number and click "Execute".

Program Output

Output will appear here...

Let’s execute for a few numbers:

Type 2 and see: 2 X 1 = 2, up to 2 X 10 = 20

Type 4, you’ll get: 4 X 1 = 4, … 4 X 10 = 40

Try 120! The logic still works perfectly.

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.

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.


A flowchart titled

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
while count <= 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:

Python Code

count = 1
while count <= 10:
    print(count)
    count = count + 1

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
while count <= 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!

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:

Python Code

count = 1
while count <= 10:
    print(count)
    count += 1

Let’s execute — it prints 1 to 10. Simple.

Now, suppose I want to print numbers from 1, but stop when I hit 3. Here’s what I do inside the while loop:

CodeFlow Visualizer: The Break Statement

Python Code

1
1
count = 1
2
2
while count <= 10:
3
3
    if count == 3:
4
4
        break
5
5
    print(count)
6
6
    count += 1
Click "Execute" to start.

Program Output

Output appears here...

Let’s execute this. You see, only “1,2,3” gets printed. After that, break ends the loop, even though the while condition is still true.

Next, let’s try printing something outside the loop. I move a print statement out of the loop and give a message:

Python Code

count = 1
while count <= 10:
    print(count)
    count += 1
    break
print("Hi")

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.

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.

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 in range(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.

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.

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 in range(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!

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 in range(1, 6):
2
2
    for j in range(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!

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 in range(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.

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.

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

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.

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
    return c
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.

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.

Python Code

def student_marks(*marks):
    print(marks)

student_marks(10, 20, 30, 40, 50)

Run Output

(10, 20, 30, 40, 50)

Variable Length Keyword Argument

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.

Python Code

def student_marks(**marks):
    print(marks)

student_marks(Ram=10, Andrew=20, Jivan=30)

Run Output

{'Ram': 10, 'Andrew': 20, 'Jivan': 30}

Hope I am clear.

Programs Using Pre-Built Functions in Python

Lesson 32

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.

Python Code

a = [10, 34, 53, 54, 97, 45, 41, 19]
print(sum(a))
print(max(a))
print(min(a))
print(sorted(a))

Run Output

353
97
10
[10, 19, 34, 41, 45, 53, 54, 97]

In the next lesson, you’ll learn how to import libraries and use even more pre-built functions in Python. Stay tuned!

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

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.

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/

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]

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

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`.

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.

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

A diagram illustrating the difference between high-level and low-level languages. The top section, labeled

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

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.

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

Run Output

140732853382496 (example address)
140732853382496 (example address, same)

But if we take mutable list the address stays the same after we append 90. That shows the original list changed—no new object.

If you create two lists with the same values:

Python Code

a = [10, 30, 40, 50]
b = [10, 30, 40, 50]
print(id(a)) # Different ID
print(id(b)) # Different ID

Run Output

2466037703872 (example address)
2466037703904 (example address, different)

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

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

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