MODULE 01

Python Basics

Introduction, Setup, Syntax, Variables & Data Types
A step-by-step learning page designed to explain every concept from beginner level, with practical examples, coding practice and theory revision.

5 Major TopicsDetailed Subtopics25 Coding Questions30 Theory Q&A

📚 Module Contents

01

1. Introduction to Python

Step-by-step explanation

1.1 What is Python?

Step 1 — Understand the meaning

Python is a high-level, general-purpose programming language. High-level means the syntax is designed for humans to read and write more easily than low-level machine instructions.

Step 2 — Understand what a programming language does

A programming language lets us give instructions to a computer. For example, we can tell Python to calculate a value, store data, read a file, process a dataset, or display a message.

Step 3 — Why Python is different

Python emphasizes readable code and uses indentation to organize blocks. Many common tasks can be expressed with relatively few lines of code.

Step 4 — Where Python is used

Python is used for automation, web development, APIs, data analysis, data science, AI and machine learning, cybersecurity, testing, DevOps, scripting and education.

Example

print("Hello, Python!")

Here print() is a built-in Python function that displays text.

1.2 Features of Python

Readable syntax

Python code is designed to be easy to read. This helps beginners understand programs and helps teams maintain code.

Interpreted execution model

With the standard CPython implementation, source code is compiled to bytecode and then executed by the Python virtual machine. You normally run the program directly with the Python interpreter.

Dynamically typed

You do not normally declare a variable's type before assigning a value. The object referenced by the name has a type.

Object-oriented

Python supports classes, objects, inheritance, polymorphism and other object-oriented programming concepts.

Cross-platform

Python programs can run on Windows, macOS and Linux when the required Python version and dependencies are available.

Large ecosystem

Python includes a standard library and a huge collection of third-party packages.

1.3 Python program execution — step by step

Step 1

You write Python source code in a file such as hello.py.

Step 2

You start Python and ask it to run that file, for example python hello.py.

Step 3

CPython parses the source and compiles it to bytecode internally.

Step 4

The Python runtime executes the bytecode and performs the requested operations.

Step 5

The program produces output, changes data, reads input, writes files or performs another task.

1.4 First Python program

Step 1

Create a file named hello.py.

Step 2

Write: print("Hello World").

Step 3

Save the file.

Step 4

Open a terminal in that folder.

Step 5

Run python hello.py.

Expected output

Hello World

What happened?

Python called print(), evaluated the string value, and displayed it on the screen.

1.5 Python applications

Automation

Rename files, process folders, generate reports, send notifications and automate repetitive tasks.

Data analysis

Use libraries such as pandas and NumPy to clean, transform and analyze data.

AI and machine learning

Python is widely used with libraries and frameworks for machine learning and AI.

Web and APIs

Frameworks such as Flask, FastAPI and Django can be used to build web applications and APIs.

Cybersecurity

Python is useful for scripting, log analysis, automation, testing and defensive security tooling.
02

2. Python Setup

Step-by-step explanation

2.1 Install Python — step by step

Step 1

Go to the official Python download page and select Python 3 for your operating system.

Step 2

Run the installer.

Step 3

On Windows, enable the option to add Python to PATH when it is available in the installer.

Step 4

Complete the installation.

Step 5

Open Command Prompt or PowerShell.

Step 6

Run python --version. If your system uses the alternative command, try python3 --version.

Step 7

If a Python version is displayed, the command is available from your terminal.

2.2 Understanding Python PATH

What is PATH?

PATH is an operating-system environment variable containing folders where executable programs can be found.

Why does it matter?

If Python is on PATH, you can type python in a terminal without entering the full installation path.

Common issue

If python is not recognized, Python may not be installed correctly, may not be on PATH, or your system may use python3 instead.

2.3 Python interactive shell

Step 1

Open a terminal.

Step 2

Run python or python3.

Step 3

You will see a prompt such as >>>.

Step 4

Type an expression: 10 + 20.

Step 5

Python immediately displays 30.

When to use it

The interactive shell is excellent for testing a small expression, checking a method, experimenting with types or learning syntax.

2.4 Writing and running a .py file

Step 1

Create a folder for your project.

Step 2

Create main.py.

Step 3

Write Python code.

Step 4

Save it.

Step 5

Open the terminal in that folder.

Step 6

Run python main.py.

Step 7

Read the output or error message.

2.5 Editor vs IDE

Text editor

A code editor such as VS Code provides syntax highlighting, extensions, terminal integration and debugging features.

IDE

An integrated development environment combines coding, project navigation, debugging and other development tools in one application.

Beginner recommendation

Use an editor or IDE you are comfortable with. The most important skill is understanding the Python code, not memorizing a particular editor.

2.6 Virtual environment — step by step

Step 1

Open the project folder.

Step 2

Create an environment with python -m venv .venv.

Step 3

Activate it using the command appropriate for your operating system.

Step 4

Install project-specific packages with pip.

Step 5

Keep the environment associated with that project.

Why?

Different projects may require different package versions. A virtual environment prevents many dependency conflicts.

2.7 pip and packages

Step 1

Confirm your Python environment is active.

Step 2

Run python -m pip --version.

Step 3

Install a package, for example python -m pip install requests.

Step 4

Import it in Python using import requests.

Important

Install packages only from trusted sources and understand the dependencies you add to a project.
03

3. Python Syntax

Step-by-step explanation

3.1 Basic syntax

Step 1

Python reads instructions from your source code.

Step 2

Statements are generally written one per line.

Step 3

Indentation groups related statements into blocks.

Step 4

Expressions calculate or produce values.

Example

x = 10
y = 20
print(x + y)

The first two lines assign values. The third line evaluates x + y and prints the result.

3.2 Indentation — very important

Why indentation matters

Python uses indentation to define blocks instead of relying on braces such as { }.

Step 1

Start a block after a statement such as if, for, while or def.

Step 2

End that line with a colon :.

Step 3

Indent the statements belonging to the block.

Example

age = 20
if age >= 18:
    print("Adult")

Common error

Mixing tabs and spaces or using inconsistent indentation can cause indentation errors. Four spaces is the common convention.

3.3 Comments

Single-line comment

Use # before the comment text.

Example

# Calculate the total
total = price * quantity

Good comments

Explain why something is done when the reason is not obvious. Avoid comments that merely repeat the code.

3.4 Identifiers

Definition

An identifier is a name used for a variable, function, class or other program object.

Valid examples

student_name, total_marks, age2, _count.

Invalid examples

2name is invalid because an identifier cannot begin with a digit.

Naming tip

Use meaningful names instead of vague names such as x when a more descriptive name improves readability.

3.5 Keywords

Definition

Keywords are reserved words that have special meaning in Python.

Examples

if, else, for, while, def, class, return, True, False, None.

How to see keywords

import keyword
print(keyword.kwlist)

3.6 print() — step by step

Step 1

Write print().

Step 2

Put the value you want to display inside the parentheses.

Step 3

Use quotes for text.

Examples

print("Python")
print(100)
name = "Naveen"
print(name)

Multiple values

print("Age:", 26) displays both values separated by a space by default.

3.7 input() — step by step

Step 1

Call input().

Step 2

Optionally provide a prompt.

Step 3

Python waits for the user to type something and press Enter.

Step 4

The returned value is a string.

Example

name = input("Enter your name: ")
print("Hello", name)

Important

If the user enters 25, input() returns "25", not the integer 25.

3.8 Type conversion

String to integer

age = int(input("Age: "))

String to float

salary = float(input("Salary: "))

Number to string

text = str(100)

Step-by-step example

a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b)

Both inputs are converted to integers before addition.

3.9 Operators

Arithmetic

+ - * / // % ** perform arithmetic operations.

Comparison

== != > < >= <= compare values and produce Boolean results.

Logical

and, or, not combine or invert Boolean conditions.

Assignment

=, +=, -=, *= and similar operators assign/update values.
04

4. Variables

Step-by-step explanation

4.1 What is a variable?

Simple explanation

Think of a variable name as a label that refers to an object/value.

Step 1

Create or obtain a value.

Step 2

Bind a name to that value using =.

Step 3

Use the name later to access the referenced object.

Example

age = 26
print(age)

4.2 Assignment operator =

Important

= means assignment; it does not mean mathematical equality.

Step-by-step

x = 10

Python evaluates 10 and binds the name x to that integer object.

Comparison

For equality testing, Python uses ==, for example x == 10.

4.3 Dynamic typing

Step 1

Assign an integer: x = 10.

Step 2

Reassign the same name: x = "Python".

Step 3

Now x refers to a string object.

Meaning

The variable name does not have a permanently declared type in this example; the referenced object has a type.

4.4 Multiple assignment

Multiple values

a, b, c = 10, 20, 30

Same value

x = y = 0

Swap

a = 10
b = 20
a, b = b, a

Why useful

Multiple assignment can make related assignments and swapping concise and readable.

4.5 Naming variables correctly

Use descriptive names

student_name is clearer than sn.

Use snake_case

For ordinary variables and functions, names such as total_marks are conventional.

Avoid keywords

Do not name a variable class, for or another reserved keyword.

Avoid shadowing

Avoid replacing important built-in names such as list, str or sum unless you have a specific reason.

4.6 type(), id() and identity

type()

type(x) tells you the object's type.

id()

id(x) returns an identity value for the object during its lifetime.

is

a is b checks whether two references refer to the same object.

==

a == b checks value equality.

Best practice

Use == for normal value comparisons and reserve is for identity checks, especially comparisons with singleton values such as None.

4.7 Constants

Python convention

Python does not enforce a constant declaration keyword. Developers commonly use uppercase names for values intended not to be reassigned.

Example

PI = 3.141592653589793
MAX_RETRIES = 3

4.8 del

Example

x = 100
del x

Meaning

del x removes the name binding. It does not guarantee immediate destruction of the object if other references still exist.
05

5. Data Types

Step-by-step explanation

5.1 Why data types matter

Step 1

Every Python object has a type.

Step 2

The type determines what operations are supported and how the value behaves.

Step 3

Choosing the right type makes programs easier to design and maintain.

Example

You can add integers, concatenate strings, access list elements by index and look up dictionary values by key.

5.2 int

Definition

The int type represents whole numbers.

Examples

0, 25, -100.

Example

age = 26
print(type(age))
print(age + 4)

Important

Python integers can represent arbitrarily large integers subject to available memory.

5.3 float

Definition

The float type represents floating-point numbers.

Examples

3.14, -0.5, 10.0.

Example

price = 99.50
print(type(price))

Important

Binary floating-point representation can create small rounding effects. Do not assume every decimal fraction is represented exactly.

5.4 complex

Definition

Complex numbers contain real and imaginary components.

Example

z = 2 + 3j
print(z.real)
print(z.imag)

Use

Complex numbers are useful in scientific and mathematical applications.

5.5 bool

Definition

A Boolean value is either True or False.

Example

is_logged_in = True
print(is_logged_in)

Conditions

Comparison expressions such as 10 > 5 produce Boolean results.

5.6 str

Definition

A string is an immutable sequence of Unicode characters.

Creating strings

Use single quotes, double quotes or triple quotes.

Indexing

text = "Python"
print(text[0])
print(text[-1])

Slicing

print(text[0:3])

This returns characters from index 0 up to, but not including, index 3.

Useful methods

Common methods include upper(), lower(), strip(), replace(), split() and join().

f-strings

name = "Naveen"
age = 26
print(f"{name} is {age} years old")

5.7 list

Definition

A list is an ordered, mutable collection.

Create

numbers = [10, 20, 30]

Access

print(numbers[0])

Modify

numbers[0] = 100
numbers.append(40)

Why use it?

Use a list when you need an ordered collection that can change.

5.8 tuple

Definition

A tuple is an ordered, immutable collection.

Create

point = (10, 20)

Unpack

x, y = point

Why use it?

Tuples are useful for fixed groups of values and can communicate that the collection should not be modified.

5.9 set

Definition

A set is a collection of unique elements.

Create

numbers = {10, 20, 10, 30}
print(numbers)

Result

Duplicate values are removed.

Operations

Common set operations include union, intersection, difference and symmetric difference.

5.10 dictionary

Definition

A dictionary stores key-value pairs.

Create

student = {
    "name": "Ravi",
    "age": 21
}

Access

student["name"] retrieves the value associated with the key name.

Update

student["age"] = 22.

Why use it?

Use dictionaries when data is naturally represented as named fields or key-value mappings.

5.11 None

Definition

None represents the absence of a value or a null-like state.

Example

result = None
if result is None:
    print("No result yet")

Important

Use is None rather than == None for the standard identity check.

5.12 Mutable vs immutable

Immutable examples

int, float, bool, str, tuple and frozenset are immutable.

Mutable examples

list, dict and set are mutable.

Simple test

If an operation changes a mutable object in place, the same object can contain the changed data. Immutable objects instead require a new value/object when a different value is needed.

Why important

Mutability affects assignment, function arguments, aliases and program design.

5.13 Type conversion

String to int

int("25") → 25.

String to float

float("3.14") → 3.14.

Number to string

str(25) → "25".

List to set

set([1,1,2]) → a set containing unique values.

Caution

Conversions can raise exceptions when the source value cannot be converted, such as int("abc").

5.14 Checking types with type()

Example

items = [10, 3.14, "Python", True, [1, 2]]
for item in items:
    print(item, type(item))

Purpose

This is useful during learning and debugging when you need to confirm what type of object you are working with.

25 Python Coding Questions

First try each question yourself. Then open the solution. These exercises cover the exact concepts taught in this module.

01

Print a simple welcome message

02

Store and display your name, age and city

03

Add two numbers

04

Calculate the area of a rectangle

05

Calculate simple interest

06

Convert Celsius to Fahrenheit

07

Swap two variables

08

Display the type of different values

09

Take a name as input and greet the user

10

Take two integers and print their sum

11

Calculate total and average of three marks

12

Create and display a list

13

Access first and last list items

14

Slice a string

15

Find the length of a string

16

Convert input to an integer and multiply it

17

Create a tuple and unpack it

18

Remove duplicates from a list using set

19

Create a dictionary and access values

20

Update a dictionary value

21

Demonstrate arithmetic operators

22

Compare two numbers

23

Demonstrate mutable list behavior

24

Create a student profile from input

25

Demonstrate == versus is

30 Theory Questions with Answers

Click any question to reveal its answer.

← Back to Course Syllabus