Programming: Programming is the process of writing instructions (code) that a computer
can understand and execute to perform specific tasks.
Algorithm: An algorithm is a step-by-step procedure or set of rules for solving a specific
problem or performing a task. It is a well-defined sequence of instructions that takes
input, processes it, and produces an output.
Key Characteristics of an Algorithm
1. Well-Defined Input & Output – It takes some input and produces the desired
output.
2. Finite Steps – It must have a limited number of steps.
3. Unambiguous – Each step should be clear and well-defined.
4. Effectiveness – Every step should be simple enough to be executed.
5. Language-Independent – It is a conceptual approach and can be implemented
in any programming language.
Example: Algorithm to Find the Largest of Two Numbers
1. Start
2. Take two numbers as input (A and B).
3. Compare A and B:
o If A > B, print "A is larger."
o Else, print "B is larger."
4. End
Features of Python:
Python is a high-level, interpreted programming language known for its simplicity,
readability, and versatility. Below are some key features that make Python popular:
1. Easy to Learn and Readable
• Python uses simple English-like syntax, making it easy to read and write.
• Indentation (whitespace) is used to define blocks of code instead of braces {}.
2. Interpreted Language
• Python executes code line by line, making debugging easier.
• No need for compilation before execution.
3. Dynamically Typed
• No need to declare variable types; Python automatically determines the type at
runtime.
x = 10 # Integer
y = "Hello" # String
4. Object-Oriented
• Supports Object-Oriented Programming (OOP) concepts like classes and
objects.
• Also supports procedural and functional programming styles.
5. Extensive Standard Library
• Comes with built-in modules for tasks like handling files, databases, networking,
and more.
• Example: math, os, random, json, etc.
6. Platform-Independent
• Python code can run on multiple platforms (Windows, Linux, macOS) without
modification.
• Requires only Python to be installed on the system.
7. Open Source and Large Community
• Python is free to use and has an active community that contributes to its
development.
• Many libraries and frameworks are available (NumPy, Pandas, TensorFlow, Flask,
Django, etc.).
8. Supports GUI Programming
• Python has libraries like Tkinter, PyQt, and Kivy for creating graphical user
interfaces.
9. High-Level Language
• Developers don’t need to manage low-level details like memory allocation.
10. Multi-Paradigm Support
• Supports procedural, object-oriented, and functional programming styles.
11. Integration and Extensibility
• Can integrate with C, C++, Java, and other languages.
• Can be embedded into other applications.
12. Scalability
• Used for both small scripts and large applications, including AI, ML, web
development, and automation.
Python is Interactive language:
Python is an interactive language because it allows users to write and execute code
directly in an interactive mode (REPL – Read-Eval-Print Loop). This means you can enter
commands one at a time, and Python will immediately execute and display the result
without the need for compilation.
How is Python Interactive?
1. Python Interpreter (REPL Mode)
o You can open a Python terminal (interpreter) and start typing commands.
o Each command is executed instantly, providing immediate feedback.
o Useful for testing and debugging small pieces of code.
Example:
>>> print("Hello, Python!")
Hello, Python!
>>> 5 + 3
2. Jupyter Notebook / IPython
o Python supports interactive environments like Jupyter Notebook and
IPython.
o These tools allow step-by-step execution with visualization, making Python
ideal for data science and machine learning.
3. Command-Line Execution
o You can run Python interactively from the terminal or command prompt:
$ python
o Then type and execute commands in real time.
4. Interactive Debugging
o Python provides an interactive debugger (pdb) that lets you inspect
variables and execute commands during debugging.
5. Dynamic Typing & Immediate Results
o You don't need to declare data types explicitly.
o Python evaluates expressions and displays results instantly.
>>> x = 10
>>> y = 20
>>> x + y
30
How python is Object-oriented:
Python is an object-oriented programming (OOP) language because it supports the
object-oriented paradigm, which organizes code into objects and classes. Objects
encapsulate data (attributes) and behavior (methods), making code reusable, modular,
and scalable.
1. Supports Classes and Objects
• A class is a blueprint for creating objects.
• An object is an instance of a class.
2. Encapsulation (Data Hiding)
• Encapsulation protects data by restricting access to internal variables.
• In Python, private variables use _ or __ prefixes.
3. Inheritance (Code Reusability)
• A class can inherit properties and methods from another class.
4. Polymorphism (Multiple Forms)
• Allows methods to have different behaviors in different classes.
5. Abstraction (Hiding Implementation Details)
• Hides complex implementation and shows only relevant details.
Python is Interpreted:
Python does not require compilation before execution. Instead, the Python Interpreter
executes the code line by line.
How Python Executes Code:
1. Python reads the source code (.py file).
2. It converts it into bytecode (.pyc file).
3. The Python Virtual Machine (PVM) interprets and executes the bytecode.
Example: Python Execution
print("Hello, Python!") # This is executed immediately
x = 5 + 3
print(x) # Output: 8
Python is Platform-Independent
Python code can run on any operating system (Windows, Linux, macOS) without
modification.
Why is Python Platform-Independent?
• Python code is converted to bytecode, which is Operating System-independent.
• Python interpreter is available for multiple platforms.
• Write once, run anywhere (WORA) approach.
Example: Running Python on Different OS
• Write a Python script (hello.py):
print ("Hello, Python!")
• Run on Windows: python hello.py
• Run on Linux/Mac: python3 hello.py
• Same code works on different systems without changes!
Python building blocks -
1. Identifiers
Identifiers are names used to identify variables, functions, classes, and other objects.
• Rules for Identifiers:
o Can contain letters (A-Z, a-z), digits (0-9), and underscores (_).
o Cannot start with a digit.
o Cannot be a Python keyword (e.g., if, for, class, def, else).
o Case-sensitive (Var and var are different).
Example of Identifiers
name = "Alice" # Valid identifier
_age = 25 # Valid identifier (underscore at the beginning is allowed)
totalAmount = 100 # Camel case identifier
2number = 10 # Invalid (Cannot start with a digit)
def = 5 # Invalid (Cannot use a keyword)
2. Keywords
Keywords are reserved words in Python with predefined meanings. They cannot be
used as identifiers.
List of Python Keywords (as of Python 3.10)
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del',
'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Example: Using Keywords (Valid & Invalid)
if True: # Valid (Using "if" in a proper way)
print("Condition is True")
class Car: # Valid (Using "class" to define a class)
pass
def = 5 # Invalid (Cannot use a keyword as a variable name)
3. Indentation
Python uses indentation (spaces or tabs) to define code blocks instead of curly braces
{} like in C or Java.
• Correct indentation is mandatory in Python.
• Typically, 4 spaces per indentation level is recommended.
Example of Proper Indentation
a=2
If (a == 2):
print("Hello!") # Indented properly
print("Welcome to Python!")
Incorrect Indentation (Causes Error)
If (a == 2):
print("Hello!") # IndentationError: expected an indented block
4. Variables
A variable is a named memory location used to store values.
• Variables don’t need explicit declaration (Python is dynamically typed).
• The data type is assigned automatically based on the value.
• Variables can hold integers, floats, strings, lists, tuples, dictionaries, etc.
Example of Declaring Variables
x = 10 # Integer
name = "Bob" # String
pi = 3.14 # Float
is_active = True # Boolean
Multiple Assignments
a, b, c = 1, 2, 3 # Assigning multiple values in one line
x = y = z = "Python" # Assigning the same value to multiple variables
5. Comments
Comments are used to explain code and are ignored by the Python interpreter.
• Single-line comments use #.
• Multi-line comments use ''' (triple single quotes) or """ (triple double quotes).
Example of Comments
# This is a single-line comment
x = 10 # Assigning value to x
'''
This is a multi-line comment.
It spans multiple lines.
'''
"""
Another way to write
multi-line comments.
"""
print("Hello, World!") # This will print a message
Python environment setup –
Step 1: Download Python
Go to the official Python website: https://www.python.org/downloads/
Download the latest Python 3.x version for your OS (Windows, Mac, or Linux).
Step 2: Install Python
• Windows: Run the .exe file and select "Add Python to PATH" before clicking Install
Now.
Step 3: Verify Installation
After installation, open a terminal or command prompt and type:
python --version
If installed correctly, it will show something like:
Python 3.x.x
2. Working with Python IDEs
An IDE (Integrated Development Environment) makes coding easier with features like
debugging, syntax highlighting, and auto-completion.
Popular Python IDEs & Editors
o IDLE (Built-in with Python) – Lightweight, good for beginners.
o PyCharm – Feature-rich IDE for professional development.
o VS Code – Lightweight, supports Python with extensions.
o Jupyter Notebook – Great for data science and interactive coding.
Running Python in IDLE
1. Open IDLE (comes with Python).
2. Click File → New File.
3. Type Python code (e.g., print("Hello, Python!")).
4. Save the file (.py extension).
5. Click Run → Run Module (F5).
3. Running a Simple Python Script
You can run a Python script from a file or directly in the terminal.
Method 1: Run Python in Interactive Mode (REPL)
Open a terminal and type: python
Then enter: print("Welcome to Python!")
Output: Welcome to Python!
Method 2: Run Python Script from a File
1. Open a text editor (Notepad, VS Code, PyCharm, etc.).
2. Write the following code:
# welcome.py
print("Welcome to Python Programming!")
3. Save it as welcome.py.
4. Open a terminal/command prompt and navigate to the file location.
5. Run: python welcome.py
6. Output: Welcome to Python Programming!
Python Data Types:
Python provides different data types to store various kinds of values. The most
commonly used data types are:
• Numbers (int, float, complex)
• Strings (str)
• Tuples (tuple)
• Lists (list)
• Dictionaries (dict)
1. Numbers (int, float, complex)
Declaration of Numbers
Python supports:
• Integers (int) → Whole numbers
• Floating-point (float) → Decimal numbers
• Complex (complex) → Numbers with real and imaginary parts
# Integer
x = 10
print(type(x)) # Output: <class 'int'>
# Float
y = 10.5
print(type(y)) # Output: <class 'float'>
# Complex
z = 3 + 5j
print(type(z)) # Output: <class 'complex'>
Built-in Functions for Numbers
print(abs(-5)) # 5 (Absolute value)
print(pow(2, 3)) # 8 (2^3)
print(round(3.567, 2)) # 3.57 (Rounding to 2 decimal places)
2. Strings (str)
A string is a sequence of characters enclosed in single ('), double ("), or triple (''' """)
quotes.
Declaration of Strings
str1 = 'Hello'
str2 = "Python"
str3 = '''Multiline
String'''
String Operations
# Concatenation
greeting = "Hello" + " World"
print(greeting) # Output: Hello World
# Repetition
print("Python " * 3) # Output: Python Python Python
# Slicing
text = "Programming"
print(text[0:4]) # Output: Prog (0 to 3)
# String length
print(len(text)) # Output: 11
Built-in String Functions
print(text.upper()) # PROGRAMMING
print(text.lower()) # programming
print(text.replace("Prog", "Code")) # Codingramming
print(text.split("g")) # ['Pro', 'rammin', '']
3. Tuples (tuple)
A tuple is an immutable (unchangeable) sequence of elements.
Declaration of Tuples
tup1 = (10, 2, 3, 4)
tup2 = ("apple", "banana", "cherry")
Tuple Operations
print(tup1[0]) # Accessing element (Output: 10)
print(len(tup2)) # Length of tuple
print(tup1 + tup2) # Concatenation
print(tup2 * 2) # Repetition: ('apple', 'banana', 'cherry', 'apple', 'banana', 'cherry')
4. Lists (list)
A list is an ordered, mutable (changeable) collection of elements.
Declaration of Lists
my_list = [10, 20, 30, 40]
fruits = ["apple", "banana", "mango"]
List Operations
# Accessing elements
print(my_list[1]) # Output: 20
# Modifying elements
my_list[2] = 50
print(my_list) # Output: [10, 20, 50, 40]
# Adding elements
my_list.append(60) # Adds 60 at the end
print(my_list) # Output: [10, 20, 50, 40, 60]
# Removing elements
my_list.remove(20) # Removes 20 from the list
print(my_list) # Output: [10, 50, 40, 60]
Built-in List Functions
print(len(my_list)) # List length
print(min(my_list)) # Smallest value
print(max(my_list)) # Largest value
print(sorted(my_list)) # Sorting
5. Dictionary (dict)
A dictionary is an unordered collection of key-value pairs.
Declaration of Dictionary
student = {
"name": "Alice",
"age": 22,
"marks": 85
Dictionary Operations
# Accessing values
print(student["name"]) # Output: Alice
# Modifying values
student["age"] = 23
# Adding new key-value pair
student["city"] = "New York"
# Removing key-value pair
del student["marks"]
Built-in Dictionary Functions
print(student.keys()) # Output: dict_keys(['name', 'age', 'city'])
print(student.values()) # Output: dict_values(['Alice', 23, 'New York'])
print(student.items()) # Output: dict_items([('name', 'Alice'), ('age', 23), ('city', 'New
York')])
Data Type Mutable? Ordered? Example
Numbers No N/A 10, 3.14, 2+3j
Strings No Yes "Hello"
Tuples No Yes (1, 2, 3)
Lists Yes Yes [10, 20, 30]
Dictionaries Yes No {"name": "Alice", "age": 22}
Python Operators
1. Arithmetic Operators
Used for mathematical operations like addition, subtraction, multiplication, etc.
Operator Description Example Output
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
/ Division (float) 5/2 2.5
// Floor Division 5 // 2 2
Modulus
% 5%2 1
(Remainder)
** Exponentiation 2 ** 3 8
a, b = 10, 3
print(a + b) # Output: 13
print(a - b) # Output: 7
print(a * b) # Output: 30
print(a / b) # Output: 3.3333
print(a // b) # Output: 3
print(a % b) # Output: 1
print(a ** b) # Output: 1000 (10^3)
2. Comparison (Relational) Operators
Used to compare values and return a Boolean (True or False).
Operator Description Example Output
== Equal to 5 == 3 False
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 5<3 False
Operator Description Example Output
>= Greater than or equal to 5 >= 3 True
<= Less than or equal to 5 <= 3 False
x, y = 10, 20
print(x == y) # False
print(x != y) # True
print(x > y) # False
print(x <= y) # True
3. Assignment Operators
Used to assign values to variables.
Operator Description Example Equivalent
= Assign x=5 x=5
+= Add and assign x += 3 x=x+3
-= Subtract and assign x -= 3 x=x-3
*= Multiply and assign x *= 3 x=x*3
/= Divide and assign x /= 3 x=x/3
//= Floor divide and assign x //= 3 x = x // 3
%= Modulus and assign x %= 3 x=x%3
**= Exponent and assign x **= 3 x = x ** 3
x=5
x += 3 # Equivalent to x = x + 3
print(x) # Output: 8
4. Logical Operators
Used to combine conditional statements.
Operator Description Example Output
and Returns True if both conditions are true (5 > 3) and (8 > 5) True
or Returns True if at least one condition is true (5 > 3) or (8 < 5) True
not Reverses the result not(5 > 3) False
a, b = True, False
print(a and b) # False
print(a or b) # True
print(not a) # False
5. Bitwise Operators
Used to perform operations at the binary level.
Operator Description Example
& AND 5 & 3 → 00000101 & 00000011 = 00000001 (1)
| OR 3 | 1 → 00000011 | 00000001 = 00000001 (1)
^ XOR 5 ^ 3 → 00000101 ^ 00000011 = 00000110 (6)
~ NOT ~5 → -(5+1) = -6
<< Left Shift 5 << 1 → 00000101 << 1 = 00001010 (10)
>> Right Shift 5 >> 1 → 00000101 >> 1 = 00000010 (2)
a, b = 5, 3
print(a & b) # Output: 1
print(a | b) # Output: 7
print(a ^ b) # Output: 6
print(~a) # Output: -6
print(a << 1) # Output: 10
print(a >> 1) # Output: 2
6. Membership Operators
Used to check if a value exists in a sequence (list, tuple, dictionary, etc.).
Operator Description Example Output
in Returns True if value exists in the sequence "a" in "apple" True
not in Returns True if value does not exist "x" not in "apple" True
fruits = ["apple", "banana", "cherry"]
print("apple" in fruits) # True
print("grape" not in fruits) # True
7. Identity Operators
Used to compare objects' memory locations.
Operator Description Example Output
Returns True if both variables refer to True/Fal
is x is y
the same object se
Returns True if both variables do not refer to True/Fal
is not x is not y
the same object se
x = [1, 2, 3]
y=x
z = [1, 2, 3]
print(x is y) # True (same memory location)
print(x is z) # False (different objects)
print(x == z) # True (same values)
Python Operator Precedence
Operator precedence determines which operations are performed first in an
expression.
Precedence Operators
Highest () (Parentheses)
** (Exponentiation)
+x, -x, ~x (Unary plus, minus, bitwise NOT)
*, /, //, % (Multiplication, Division, Floor division,
Modulus)
+, - (Addition, Subtraction)
<<, >> (Bitwise shift)
& (Bitwise AND)
^ (Bitwise XOR)
| (Bitwise OR)
==, !=, >, <, >=, <= (Comparison)
not (Logical NOT)
and (Logical AND)
or (Logical OR)
Lowest = (Assignment)
Example:
print(5 + 3 * 2) # Output: 11 (Multiplication first)
print((5 + 3) * 2) # Output: 16 (Parentheses first)