MODULE I – PYTHON PROGRAMMING
NOTES
Comprehensive Guide for B.E. 1st Year (I/II Semester)
Course: MVJAIAK203 (Artificial Intelligence & Applications)
MVJ College of Engineering
Generated: 10 April 2026
TABLE OF CONTENTS
1. Introduction to Problem Solving and Programming
1.1 Problem Solving Strategies
1.2 Program Design Tools
1.3 Programming Paradigms
1.4 Features of Object-Oriented Programming (OOP)
1.5 Merits and Demerits of OOP
2. Basics of Python Programming
2.1 Features of Python
2.2 Python IDLE
2.3 Literal Constants
2.4 Variables and Identifiers
2.5 Data Types
2.6 Input/Output Operations
2.7 Comments in Python
2.8 Indentation
2.9 Reserved Words (Keywords)
2.10 Operators and Expressions
2.11 Type Conversion
3. Important Exam Questions with Detailed Answers
1. INTRODUCTION TO PROBLEM SOLVING AND PROGRAMMING
1.1 Problem Solving Strategies
Problem solving is the process of finding solutions to difficult or complex issues. In
computer programming, problem solving means breaking down a complex problem into
smaller, manageable parts and finding logical solutions that can be implemented using
programming languages.
Key Problem Solving Strategies:
Understand the Problem: Read and analyze the problem carefully. Identify inputs,
outputs, and constraints. Ask clarifying questions.
Divide and Conquer: Break the problem into smaller subproblems. Solve each
subproblem independently, then combine solutions.
Dynamic Programming: Store solutions of subproblems to avoid redundant
calculations. Useful for optimization problems.
Greedy Algorithm: Make locally optimal choices hoping to find global optimum. Works
for problems like coin change, activity selection.
Backtracking: Explore all possible solutions by trying one path, and if it doesn't work,
go back and try another path.
Pattern Recognition: Identify patterns in the problem. Similar problems may have
similar solutions.
Iteration and Refinement: Start with a basic solution and refine it. Test and improve
incrementally.
1.2 Program Design Tools
Program design tools are used to plan and design programs before writing actual code.
They help visualize the logic, structure, and flow of the program.
Major Program Design Tools:
Design Tool Description
Flowchart Graphical representation of algorithm
using standardized symbols (rectangles for
processes, diamonds for decisions, etc.)
Pseudocode High-level, human-readable description of
algorithm without actual code syntax.
Data Flow Diagram (DFD) Shows flow of data through the system,
entities, processes, and data stores.
Structure Chart Hierarchical representation showing
modules and their relationships.
Unified Modeling Language (UML) Standardized notation for modeling object-
oriented systems.
Entity-Relationship Diagram (ERD) Shows relationships between entities in a
database system.
Flowchart Symbols:
Symbol Meaning
Oval/Ellipse Start/End or Terminal point
Rectangle Process or action
Diamond Decision (if-else condition)
Parallelogram Input/Output operation
Cylinder Database or storage
Arrow Flow direction
1.3 Programming Paradigms
A programming paradigm is a fundamental approach and methodology of programming. It
represents a style of programming and provides a set of tools and concepts to solve
problems.
Major Programming Paradigms:
Procedural/Imperative
Description: Programs consist of procedures/functions that modify data.
Key Characteristics:
Focuses on HOW to do things
Uses variables and assignments
Has explicit control flow
Languages: C, Pascal, C++, Python
Example: Step-by-step instructions to solve a problem
Object-Oriented
Description: Programs are organized around objects that contain data and methods.
Key Characteristics:
Focuses on objects and classes
Encapsulation, inheritance, polymorphism
Reusable and modular
Languages: Python, Java, C++, C#
Example: Creating classes for Car, Student, Bank Account
Functional
Description: Programs treat computation as the evaluation of mathematical functions.
Key Characteristics:
Avoids changing state
Uses pure functions
Emphasizes immutability
Languages: Lisp, Haskell, Scheme, Python (partial)
Example: Using map, filter, reduce functions
Declarative
Description: Programs specify WHAT should be done, not HOW to do it.
Key Characteristics:
Query-based
Logic-based
Set-theoretic
Languages: SQL, HTML, CSS, Prolog
Example: SQL queries: SELECT * FROM students WHERE age > 18
Comparison of Programming Paradigms:
Paradigm Focus Key Concept Best For
Procedural How to do it Functions & Small to medium
Variables programs
OOP Objects & Classes Encapsulation & Large, complex
Inheritance applications
Functional Pure Functions Immutability Data
transformation,
parallel computing
Declarative What to achieve Constraints Database queries,
configuration
1.4 Features of Object-Oriented Programming (OOP)
OOP is a programming paradigm based on the concept of "objects", which contain data
(attributes) and behavior (methods). It provides a way to structure programs in a modular
and reusable manner.
Core Features of OOP:
Encapsulation
Definition: Bundling data (attributes) and methods (functions) together within a class, and
hiding internal details from the outside world.
Benefits:
Data protection
Controlled access through methods
Reduced complexity
Example: A class Student with private attributes (name, age) accessed through public
methods
Inheritance
Definition: Mechanism where a class (child/derived) inherits properties and methods from
another class (parent/base).
Benefits:
Code reusability
Hierarchical classification
Extensibility
Example: Class Vehicle and classes Car, Truck inheriting from Vehicle
Polymorphism
Definition: Ability of objects to take many forms. Same method name can behave differently
in different classes.
Benefits:
Flexibility
Extensibility
Code reusability
Example: Method draw() in Shape, Circle, Rectangle classes
Abstraction
Definition: Hiding complex implementation details and showing only essential features to
the user.
Benefits:
Simplification
Reduced complexity
Focus on interface not implementation
Example: Using a function without knowing how it works internally
Data Binding
Definition: Tight coupling of data and methods in a class. Objects are self-contained.
Benefits:
Modularity
Independence
Easy to maintain
Example: A BankAccount class contains balance and methods to deposit/withdraw
1.5 Merits and Demerits of Object-Oriented Programming
Merits (Advantages) of OOP:
Modularity: Programs are organized into independent objects, making them easier to
understand and maintain.
Reusability: Classes and objects can be reused in different parts of the program or
different programs.
Maintainability: Changes in one class don't affect other classes, making debugging and
updates easier.
Scalability: OOP makes it easier to build large-scale applications with thousands of
classes.
Security: Encapsulation provides data hiding, preventing unauthorized access to
sensitive data.
Flexibility and Extensibility: Inheritance and polymorphism allow easy extension of
existing code.
Real-World Modeling: Objects represent real-world entities, making code more
intuitive.
Team Development: Multiple programmers can work on different classes
independently.
Reduced Complexity: Abstraction hides complex details, making code easier to
understand.
Code Organization: Clear structure with classes, reducing code redundancy.
Demerits (Disadvantages) of OOP:
Steep Learning Curve: OOP concepts are complex and require significant time to master.
Slower Execution: OOP programs may run slower than procedural programs due to
overhead.
Large File Size: OOP programs may generate larger object files and require more
memory.
Not Suitable for Small Programs: OOP adds unnecessary complexity for simple, small
programs.
Design Complexity: Designing a proper OOP architecture requires careful planning and
experience.
Message Passing Overhead: Communication between objects has computational
overhead.
Difficulty in Designing Classes: Improper class design can lead to poor software quality.
Debugging Difficulty: With many interacting objects, debugging becomes more complex.
Data Management: Managing relationships between objects can become complicated.
Testing Complexity: Testing interdependent objects is more challenging than testing
functions.
2. BASICS OF PYTHON PROGRAMMING
2.1 Features of Python
Python is a high-level, interpreted, object-oriented programming language known for its
simplicity and readability. It was created by Guido van Rossum in 1989 and first released in
1991. Python is widely used in web development, data science, artificial intelligence,
automation, and many other fields.
Key Features of Python:
Simple and Readable: Python syntax is clear and readable, making it easy to learn and
understand. It uses indentation to define code blocks.
Interpreted Language: Python code is executed line-by-line by an interpreter, not
compiled into machine code. Errors are detected at runtime.
Dynamically Typed: No need to declare variable types. Python automatically
determines the type based on the assigned value.
Object-Oriented: Python supports OOP concepts like classes, objects, inheritance, and
polymorphism.
Functional Programming: Python supports functional programming with features like
lambda, map, filter, reduce.
Extensive Libraries: Python has a vast standard library (NumPy, Pandas, Django, Flask,
etc.) for various tasks.
Platform Independent: Python runs on Windows, Mac, Linux, and other operating
systems without modification.
Free and Open Source: Python is free to download, use, modify, and distribute.
Community Support: Large community of developers providing support, tutorials, and
libraries.
Versatile: Python can be used for web development, data science, AI, automation, game
development, etc.
Easy Integration: Python can easily integrate with other languages like C, C++, Java.
Large Standard Library: Comprehensive built-in modules for various tasks without
external dependencies.
2.2 Python IDLE
IDLE stands for "Integrated Development and Learning Environment". It is the default
integrated development environment (IDE) that comes with Python. IDLE provides a simple
interface for writing, testing, and running Python programs.
What is IDLE?
IDLE is a Python-based IDE that allows you to write Python code in a graphical
environment. It includes both a Python shell (interactive interpreter) and a text editor for
writing scripts.
Components of IDLE:
Interactive Shell/Interpreter: Execute Python commands one at a time and see
immediate results.
Text Editor: Write multi-line Python programs and save them as .py files.
Syntax Highlighting: Different colors for keywords, strings, comments, etc.
Debugging Tools: Set breakpoints, step through code, view variables.
File Browser: Navigate and open Python files.
Help System: Access documentation and help.
How to Open IDLE:
1. Windows: Search for "IDLE" in Start menu or double-click on Python installation
2. Mac: Open Terminal and type: idle (or idle3 for Python 3)
3. Linux: Open Terminal and type: idle or idle3
Interactive Mode vs Script Mode:
Interactive Mode Script Mode
Execute one line at a time Write complete program in file
See results immediately Execute entire program at once
Good for learning and testing Good for production programs
>>> prompt shown Save as .py file and run
No need to save Code persists in file
Limited to simple programs Suitable for complex programs
2.3 Literal Constants
A literal constant is a value that remains unchanged throughout the program. It is a fixed
value that appears directly in the code.
Types of Literal Constants:
String Literals
Definition: Sequence of characters enclosed in single, double, or triple quotes.
Examples:
Single quote: 'Hello'
Double quote: "Python"
Triple quote: '''Multi\nline\nstring'''
Numeric Literals
Definition: Fixed numeric values.
Types/Examples:
Integer: 42, -100, 0
Float: 3.14, -2.5, 0.0
Complex: 3+4j, 2-5j
Boolean Literals
Definition: True or False values.
Examples:
True
False
Special Literals
Definition: Special constant values.
Examples:
None (represents absence of value)
Character Literals
Definition: Single character enclosed in quotes.
Examples:
'A'
'$'
'\n' (newline character)
Examples of Literal Constants:
# String Literals
name = "Basavasagar"
message = 'Welcome to Python'
# Numeric Literals
age = 25
height = 5.8
pi = 3.14159
# Boolean Literals
is_student = True
is_employed = False
# Special Literal
value = None
# Character Literal
grade = 'A'
print(name, age, height, pi, is_student, grade)
2.4 Variables and Identifiers
A variable is a named storage location that holds a value. An identifier is the name given to a
variable, function, class, or module.
Variables:
Variables are containers for storing data values. In Python, you don't need to declare the
data type; Python automatically determines it based on the value assigned.
Syntax: variable_name = value
Rules for Naming Variables (Identifiers):
Must start with a letter (a-z, A-Z) or underscore (_), not a number
Can contain letters, numbers, and underscores
Are case-sensitive (Name and name are different)
Cannot contain spaces or special characters (except underscore)
Cannot be a Python keyword/reserved word
Should be meaningful and descriptive
Use lowercase with underscores (snake_case convention): my_variable
Avoid single-letter names except for loop counters
Examples of Variables and Identifiers:
# Valid Variable Names
student_name = "John"
age = 20
_private_var = 100
var123 = "Valid"
PI = 3.14159 # Constant (by convention, use uppercase)
# Invalid Variable Names (will cause error)
# 123var = 50 # Cannot start with number
# var-name = "Invalid" # Hyphen not allowed
# var name = "Invalid" # Space not allowed
# class = "Invalid" # class is a reserved word
# Multiple assignments
x = y = z = 10 # All variables have value 10
a, b, c = 1, 2, 3 # Different values
print(student_name, age, _private_var, var123)
print(x, y, z)
print(a, b, c)
2.5 Data Types
A data type specifies the type of data a variable can hold. Python is dynamically typed,
meaning the type is determined at runtime based on the assigned value.
Built-in Data Types in Python:
Data Type Description Example How to Check
int Integer (whole age = 25 type(age)
numbers)
float Decimal numbers height = 5.8 type(height)
str String (text) name = "Python" type(name)
bool Boolean is_valid = True type(is_valid)
(True/False)
list Ordered collection nums = [1, 2, 3] type(nums)
(mutable)
tuple Ordered collection coords = (4, 5) type(coords)
(immutable)
dict Key-value pairs person = {"name": type(person)
"John"}
set Unordered unique colors = {1, 2, 3} type(colors)
values
NoneType None value result = None type(result)
Detailed Explanation of Each Data Type:
Integer (int):
Represents whole numbers (positive, negative, or zero). No decimal point.
# Integer Examples
age = 25
temperature = -10
zero = 0
big_number = 1000000
print(type(age)) # <class 'int'>
print(age + 5) # 30
Float (float):
Represents decimal numbers. Contains a decimal point.
# Float Examples
height = 5.8
pi = 3.14159
temperature = -2.5
scientific = 1.23e-5 # Scientific notation
print(type(height)) # <class 'float'>
print(height + 1.2) # 7.0
String (str):
Sequence of characters enclosed in quotes. Can be single, double, or triple quotes.
# String Examples
name = "Basavasagar"
message = 'Welcome'
multiline = """This is
a multiline
string"""
print(type(name)) # <class 'str'>
print([Link]()) # BASAVASAGAR
print(len(name)) # 12
print(name[0]) # B (first character)
Boolean (bool):
Represents two values: True or False. Used for conditional operations.
# Boolean Examples
is_student = True
is_employed = False
print(type(is_student)) # <class 'bool'>
print(10 > 5) # True
print(10 < 5) # False
print(10 == 10) # True
List (list):
Ordered, mutable (can be changed) collection. Elements enclosed in square brackets.
# List Examples
numbers = [1, 2, 3, 4, 5]
fruits = ["apple", "banana", "orange"]
mixed = [1, "hello", 3.14, True]
empty = []
print(type(numbers)) # <class 'list'>
print(numbers[0]) # 1 (first element)
numbers[0] = 10 # Change element
[Link](6) # Add element
print(len(numbers)) # 6
Tuple (tuple):
Ordered, immutable (cannot be changed) collection. Elements enclosed in parentheses.
# Tuple Examples
coordinates = (4, 5)
colors = ("red", "green", "blue")
single = (1,) # Note comma for single element
nested = (1, (2, 3), 4)
print(type(coordinates)) # <class 'tuple'>
print(coordinates[0]) # 4
# coordinates[0] = 10 # Error! Cannot modify
print(len(coordinates)) # 2
Dictionary (dict):
Unordered collection of key-value pairs. Keys are unique.
# Dictionary Examples
student = {"name": "John", "age": 20, "city": "Delhi"}
empty = {}
nested = {"person": {"name": "John", "age": 20}}
print(type(student)) # <class 'dict'>
print(student["name"]) # John
print([Link]("age")) # 20
student["city"] = "Mumbai" # Modify value
student["roll"] = "A001" # Add new key-value
print(len(student)) # 4
Set (set):
Unordered collection of unique values. Elements enclosed in curly braces.
# Set Examples
numbers = {1, 2, 3, 4, 5}
colors = {"red", "green", "blue"}
empty = set() # Note: {} creates dict, not set
print(type(numbers)) # <class 'set'>
print(2 in numbers) # True
[Link](6) # Add element
[Link](1) # Remove element
print(len(numbers)) # 5
None Type (NoneType):
Represents the absence of a value. Used as a placeholder.
# None Examples
result = None
value = None
print(type(result)) # <class 'NoneType'>
print(result) # None
def my_function():
pass # Returns None by default
x = my_function()
print(x) # None
2.6 Input/Output Operations
Input/Output operations allow programs to interact with users. Output sends data to the
user (display), and Input receives data from the user.
Output Operation: print() Function
The print() function displays output on the console. It can accept multiple arguments
separated by commas.
# Basic print statements
print("Hello, World!")
print(123)
print(3.14)
print(True)
# Multiple arguments
print("Name:", "John", "Age:", 20)
# Using end parameter (default is newline)
print("A", end=" ")
print("B") # Output: A B
# Using sep parameter (default is space)
print(1, 2, 3, sep="-") # Output: 1-2-3
# Printing variables
name = "Python"
version = 3.9
print(f"Welcome to {name} {version}") # f-string
# String formatting
print("Hello %s, you are %d years old" % ("John", 20))
print("Hello {}, you are {} years old".format("John", 20))
Input Operation: input() Function
The input() function reads a line from the user input. It returns a string, regardless of what
the user enters.
# Basic input
name = input("Enter your name: ")
print("Hello,", name)
# input() returns string
age_str = input("Enter your age: ")
print(type(age_str)) # <class 'str'>
# Taking multiple inputs
a, b = input("Enter two numbers separated by space:
").split()
print(a, b)
# Input with type conversion
age = int(input("Enter your age: ")) # Convert to integer
height = float(input("Enter your height: ")) # Convert to
float
print(type(age), type(height))
# Program example
print("=== Simple Calculator ===")
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum_result = num1 + num2
print(f"Sum: {sum_result}")
2.7 Comments in Python
Comments are lines of text that are not executed by the Python interpreter. They are used to
explain code, make it more readable, and document functionality.
Types of Comments:
Single-line Comments:
Start with # symbol. Everything after # on that line is a comment.
# This is a single-line comment
x = 10 # Inline comment explaining the variable
# Another comment on its own line
print(x) # Print the value
Multi-line Comments:
Use triple quotes (""" or ''') to span multiple lines.
"""
This is a multi-line comment.
It can span multiple lines.
Useful for detailed explanations.
"""
x = 10
y = 20
# Another way
"""
This program calculates the sum of two numbers
and prints the result.
"""
result = x + y
print(result)
Docstrings:
Docstrings are special comments using triple quotes that document functions, classes, or
modules. They can be accessed using the help() function.
def add(a, b):
"""
This function adds two numbers.
Arguments:
a: First number
b: Second number
Returns:
Sum of a and b
"""
return a + b
# Access docstring
print(add.__doc__)
help(add) # Displays the docstring
2.8 Indentation
Indentation is the use of whitespace (spaces or tabs) at the beginning of a line to define code
blocks. It is crucial in Python and determines the scope of loops, functions, classes, and
conditional statements.
Importance of Indentation:
Unlike other languages that use curly braces {}, Python uses indentation to define code
blocks. Incorrect indentation will result in an IndentationError.
# Correct indentation
if 5 > 3:
print("5 is greater than 3") # This line is inside if
block
print("Indentation is important")
print("This is outside if block")
# For loop with correct indentation
for i in range(3):
print(f"Iteration {i}") # Inside loop
print(f"i = {i}")
# Function with indentation
def greet(name):
"""Function with proper indentation"""
message = f"Hello, {name}" # Inside function
print(message)
greet("Python") # Outside function
# Nested indentation (if inside for loop)
for i in range(3):
if i > 0:
print(f"{i} is greater than 0") # Nested
indentation
⚠ IMPORTANT: Always use consistent indentation (either 4 spaces or 1 tab). Python
typically recommends 4 spaces per indentation level. Mixing tabs and spaces will cause
errors.
2.9 Reserved Words (Keywords)
Reserved words (keywords) are words that have special meaning in Python and cannot be
used as variable names, function names, or identifiers. They are part of Python syntax.
Complete list of Python keywords:
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,
Categories of Keywords:
Control Flow
if, elif, else, for, while, break, continue, pass
Functions
def, return, lambda, yield
Classes
class, super
Exceptions
try, except, finally, raise, assert
Modules
import, from, as
Variables
global, nonlocal, del
Logical
and, or, not, is, in
Async
async, await
Other
with, True, False, None
⚠ REMEMBER: Do not use these keywords as variable or function names. If you try,
you will get a SyntaxError.
2.10 Operators and Expressions
Operators are symbols that perform operations on values and variables. Expressions are
combinations of values, variables, and operators that evaluate to a result.
Types of Operators:
Arithmetic Operators:
Used for mathematical calculations.
Operator Name Example Result
+ Addition 10 + 5 15
- Subtraction 10 - 5 5
* Multiplication 10 * 5 50
/ Division 10 / 5 2.0
// Floor Division 10 // 3 3
% Modulus 10 % 3 1
(Remainder)
** Exponentiation 2 ** 3 8
# Arithmetic operations
a = 10
b = 3
print("Addition:", a + b) # 13
print("Subtraction:", a - b) # 7
print("Multiplication:", a * b) # 30
print("Division:", a / b) # 3.333...
print("Floor Division:", a // b) # 3
print("Modulus:", a % b) # 1
print("Exponentiation:", a ** b) # 1000
Comparison Operators:
Used to compare values. Return True or False.
Operator Name Example Result
== Equal 5 == 5 True
!= Not Equal 5 != 3 True
< Less Than 3<5 True
> Greater Than 5>3 True
<= Less Than or Equal 5 <= 5 True
>= Greater Than or 5 >= 3 True
Equal
# Comparison operations
a = 10
b = 5
print("a == b:", a == b) # False
print("a != b:", a != b) # True
print("a < b:", a < b) # False
print("a > b:", a > b) # True
print("a <= b:", a <= b) # False
print("a >= b:", a >= b) # True
Logical Operators:
Used to combine conditional statements.
Operator Description Example
and True if both conditions are (a > 5) and (b > 3)
true
or True if at least one (a > 5) or (b > 3)
condition is true
not Reverses the boolean result not (a > 5)
# Logical operations
a = 10
b = 3
# and operator
print((a > 5) and (b > 2)) # True (both true)
print((a > 5) and (b > 5)) # False (second false)
# or operator
print((a > 5) or (b > 5)) # True (first is true)
print((a < 5) or (b < 2)) # False (both false)
# not operator
print(not (a > 5)) # False (negates True)
print(not (a < 5)) # True (negates False)
Assignment Operators:
Used to assign values to variables.
Operator Example Equivalent to
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
//= x //= 3 x = x // 3
%= x %= 3 x=x%3
**= x **= 3 x = x ** 3
# Assignment operators
x = 10
print(f"x = {x}") # 10
x += 5 # x = x + 5
print(f"After += 5: {x}") # 15
x -= 3 # x = x - 3
print(f"After -= 3: {x}") # 12
x *= 2 # x = x * 2
print(f"After *= 2: {x}") # 24
x //= 5 # x = x // 5
print(f"After //= 5: {x}") # 4
Identity Operators:
Used to check if two objects are the same object (not just equal).
Operator Description Example
is True if both variables point x is y
to same object
is not True if variables point to x is not y
different objects
Membership Operators:
Used to check if a value exists in a sequence.
Operator Description Example
in True if value exists in x in list
sequence
not in True if value does not exist x not in list
in sequence
# Identity operators
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b) # True (same object)
print(a is c) # False (different objects, same value)
# Membership operators
list1 = [1, 2, 3, 4, 5]
print(3 in list1) # True
print(10 in list1) # False
print(10 not in list1) # True
string = "Hello Python"
print("H" in string) # True
print("x" not in string) # True
Operator Precedence:
Operator precedence determines which operations are performed first in an expression.
Higher precedence operators are evaluated first. Use parentheses to control order.
Precedence Level (High to Low) Operators
Exponentiation **
Multiplication, Division, Modulus *, /, //, %
Addition, Subtraction +, -
Comparison Operators ==, !=, <, >, <=, >=
not not
and and
or or
# Operator precedence
# Without parentheses (follows precedence rules)
result = 10 + 5 * 2 # 5*2=10, then 10+10=20
print(f"10 + 5 * 2 = {result}") # 20
# With parentheses (execute inside first)
result = (10 + 5) * 2 # 10+5=15, then 15*2=30
print(f"(10 + 5) * 2 = {result}") # 30
# More complex example
result = 2 + 3 * 4 - 6 / 2
# Step 1: 3 * 4 = 12, 6 / 2 = 3
# Step 2: 2 + 12 - 3 = 11
print(f"2 + 3 * 4 - 6 / 2 = {result}") # 11.0
2.11 Type Conversion
Type conversion is the process of converting one data type to another. Python provides
built-in functions for type conversion.
Types of Type Conversion:
Implicit Type Conversion:
Automatic conversion of one data type to another by Python interpreter. Happens when
operations involve mixed data types.
# Implicit conversion
int_val = 10
float_val = 5.5
# int + float automatically converts to float
result = int_val + float_val
print(result) # 15.5
print(type(result)) # <class 'float'>
# int + float in comparison
print(10 == 10.0) # True (Python considers them equal)
# String + int (if compatible)
str_val = "Hello"
# str_val + int_val # Error! Cannot concatenate str and int
Explicit Type Conversion:
Manual conversion using built-in functions. Programmer explicitly converts data type.
int(): Converts to integer. Truncates decimal part.
float(): Converts to float (decimal number).
str(): Converts to string.
bool(): Converts to boolean (True or False).
list(): Converts to list.
tuple(): Converts to tuple.
dict(): Converts to dictionary.
set(): Converts to set.
# Explicit Type Conversion
# int() conversion
print(int(5.9)) # 5 (truncates, doesn't round)
print(int("123")) # 123
print(int("12.5")) # Error! Must be valid integer string
print(int(True)) # 1
print(int(False)) # 0
# float() conversion
print(float(5)) # 5.0
print(float("3.14")) # 3.14
print(float("inf")) # inf (infinity)
# str() conversion
print(str(123)) # "123"
print(str(3.14)) # "3.14"
print(str(True)) # "True"
# bool() conversion
print(bool(1)) # True
print(bool(0)) # False
print(bool("Hello")) # True
print(bool("")) # False (empty string)
print(bool([])) # False (empty list)
# list() conversion
print(list("ABC")) # ['A', 'B', 'C']
print(list((1, 2, 3))) # [1, 2, 3]
# tuple() conversion
print(tuple([1, 2, 3])) # (1, 2, 3)
print(tuple("ABC")) # ('A', 'B', 'C')
Practical Examples of Type Conversion:
# Example 1: Taking input and converting
age_str = input("Enter your age: ")
age_int = int(age_str)
print(f"Next year you will be {age_int + 1}")
# Example 2: Calculating average
marks1 = "85"
marks2 = "90"
marks3 = "88"
# Convert to int and calculate
total = int(marks1) + int(marks2) + int(marks3)
average = total / 3
print(f"Average: {average}")
# Example 3: Converting list to string
numbers = [1, 2, 3, 4, 5]
str_numbers = str(numbers)
print(str_numbers) # "[1, 2, 3, 4, 5]"
# Example 4: Checking data type and converting
def process_value(value):
if type(value) == str:
value = int(value)
return value * 2
print(process_value(5)) # 10
print(process_value("5")) # 10
⚠ KEY POINTS: Type conversion is essential for proper program execution. Always
convert input strings to appropriate types. Use explicit conversion to avoid errors.
3. IMPORTANT EXAM QUESTIONS WITH DETAILED ANSWERS
1. Explain problem-solving strategies in detail. How is divide and conquer
different from greedy algorithms?
Marks: 10
PROBLEM-SOLVING STRATEGIES:
Problem-solving is the systematic approach to finding solutions to complex issues. In
programming, it involves breaking down problems into manageable components and
implementing logical solutions.
KEY PROBLEM-SOLVING STRATEGIES:
1. UNDERSTAND THE PROBLEM:
- Read the problem statement carefully
- Identify inputs, outputs, and constraints
- Ask clarifying questions
- Analyze examples provided
Example: If asked to find the largest number in a list, understand what "largest" means,
whether duplicates exist, etc.
2. DIVIDE AND CONQUER:
- Break the problem into smaller subproblems
- Solve each subproblem independently
- Combine solutions of subproblems
- Recursive approach often used
Process:
Divide → Conquer → Combine
Example: Merge Sort
- Divide array into two halves
- Sort each half
- Merge sorted halves
3. DYNAMIC PROGRAMMING:
- Store solutions of subproblems (memoization)
- Avoid redundant calculations
- Use results of previous computations
Example: Fibonacci Series
Instead of recalculating fib(n-1) and fib(n-2) multiple times, store them.
4. GREEDY ALGORITHM:
- Make locally optimal choice at each step
- Hope to achieve global optimum
- Does not always guarantee best solution
Example: Coin Change problem - Always pick the largest denomination.
DIFFERENCE BETWEEN DIVIDE AND CONQUER AND GREEDY ALGORITHMS:
DIVIDE & CONQUER | GREEDY ALGORITHM
1. Approach Recursive, breaks | Makes local optimal
problem into parts | choices at each step
2. Decision Combines optimal | Makes choice without
solutions of subproblems| considering future
3. Guarantee Often gives optimal | May not always give
solution (e.g., Merge | optimal solution
Sort)
4. Time Complexity Generally O(n log n) | Usually O(n) or O(n log n)
5. Example Merge Sort, Quick Sort | Activity Selection,
| Huffman Coding
6. When to Use Complex problems | Problems where local
requiring optimal | choices lead to global
solutions | optimum
DETAILED EXAMPLE:
Problem: Find maximum profit from stock prices
Divide & Conquer:
- Would break array into subarrays
- Find max profit in each subarray
- Combine results
Greedy:
- Always buy before price increases
- Sell when price will decrease
- Make profit with each opportunity
CONCLUSION:
Both are important strategies. Divide and conquer works well for problems requiring
optimal solutions through combining subproblem results. Greedy works well for problems
where making the locally best choice leads to globally best solution.
2. Describe program design tools with examples. Draw and explain a flowchart
for finding the largest of three numbers.
Marks: 10
PROGRAM DESIGN TOOLS:
Program design tools help visualize, plan, and structure programs before coding. They
improve communication and reduce errors.
MAJOR PROGRAM DESIGN TOOLS:
1. FLOWCHART:
Visual representation using standardized symbols
SYMBOLS:
- Oval: Start/End (Terminal)
- Rectangle: Process/Action
- Diamond: Decision (If-Else)
- Parallelogram: Input/Output
- Arrow: Flow Direction
ADVANTAGES:
- Visual and easy to understand
- Helps identify logic errors
- Good for documentation
- Shows control flow clearly
2. PSEUDOCODE:
High-level, human-readable description of algorithm
Example:
SET max = 0
FOR each number in list:
IF number > max:
SET max = number
END IF
END FOR
RETURN max
ADVANTAGES:
- Language-independent
- Easier to write than code
- Bridge between problem and code
3. DATA FLOW DIAGRAM (DFD):
Shows movement of data through system
Components:
- Entities: Sources/destinations
- Processes: Transformations
- Data Stores: Storage
- Data Flow: Movement
4. STRUCTURE CHART:
Hierarchical representation of program modules
Top-level module broken into smaller modules
Shows module dependencies and calls
5. UML DIAGRAMS:
Standardized notation for object-oriented design
Types:
- Class Diagram: Classes and relationships
- Sequence Diagram: Message flow
- Use Case Diagram: System functionality
FLOWCHART FOR FINDING LARGEST OF THREE NUMBERS:
START
INPUT: a, b, c
IS a > b?
|----YES----> IS a > c?
| |----YES----> max = a
| |
| |----NO-----> max = c
|----NO-----> IS b > c?
|----YES----> max = b
|
|----NO-----> max = c
(All paths converge)
OUTPUT: max
STOP
PSEUDOCODE:
BEGIN
READ a, b, c
IF a > b THEN
IF a > c THEN
max = a
ELSE
max = c
END IF
ELSE
IF b > c THEN
max = b
ELSE
max = c
END IF
END IF
PRINT max
END
PYTHON CODE:
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
if a > b:
if a > c:
max = a
else:
max = c
else:
if b > c:
max = b
else:
max = c
print(f"Maximum: {max}")
ALTERNATIVE (SIMPLER):
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
max = a
if b > max:
max = b
if c > max:
max = c
print(f"Maximum: {max}")
ADVANTAGES OF USING DESIGN TOOLS:
- Easier to understand program logic before coding
- Helps identify errors before implementation
- Improves communication among team members
- Provides documentation for future reference
- Reduces debugging time
- Shows clear program flow and structure
3. Compare Object-Oriented Programming with Procedural Programming.
Discuss merits and demerits of OOP.
Marks: 10
COMPARISON: OBJECT-ORIENTED PROGRAMMING vs PROCEDURAL PROGRAMMING
OOP | PROCEDURAL
1. FOCUS Objects and classes | Functions and procedures
2. DATA & CODE Grouped in objects | Separate data and functions
3. MODULARITY High (Encapsulation) | Lower modularity
4. REUSABILITY High (Inheritance) | Lower reusability
5. MAINTENANCE Easier to maintain | Harder to maintain
6. EXTENSIBILITY Easy (add new classes) | Difficult (modify existing)
7. APPROACH Bottom-up design | Top-down design
8. SECURITY Better (encapsulation) | Lower security
9. REAL WORLD Models real objects | Linear step-by-step
10. COMPLEXITY Higher learning curve | Easier to learn
11. CODE SIZE May be larger | More compact
12. EXAMPLES Java, Python, C++, C# | C, Pascal, BASIC
OOP FEATURES:
1. ENCAPSULATION:
- Bundle data and methods in class
- Hide internal details
- Control access through public/private
Example:
```
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private
def deposit(self, amount):
self.__balance += amount # Controlled access
```
2. INHERITANCE:
- Child class inherits from parent
- Code reuse
- Hierarchical classification
Example:
```
class Vehicle:
def drive(self): pass
class Car(Vehicle):
def drive(self):
return "Car is driving"
```
3. POLYMORPHISM:
- Same method name, different behavior
- Method overriding
- Flexible code
Example:
```
def draw(shape):
[Link]() # Calls appropriate display
```
4. ABSTRACTION:
- Hide complexity
- Show only essential features
- Interface-based
Example: Using a function without knowing internals
MERITS OF OOP:
1. MODULARITY:
- Code organized into independent objects
- Each object has specific responsibility
- Easy to understand and navigate
2. REUSABILITY:
- Classes can be reused in different programs
- Inheritance promotes code reuse
- Libraries of reusable classes
3. MAINTAINABILITY:
- Changes in one class don't affect others
- Easier to locate and fix bugs
- Clear structure reduces errors
4. SCALABILITY:
- Suitable for large applications
- Can manage thousands of classes
- Team development easier
5. SECURITY:
- Encapsulation hides internal details
- Data protection through access modifiers
- Prevents unauthorized access
6. FLEXIBILITY & EXTENSIBILITY:
- Easy to add new classes
- Inheritance provides extension mechanism
- Polymorphism allows different behaviors
7. REAL-WORLD MODELING:
- Objects represent real entities
- More intuitive to understand
- Easier problem-to-code mapping
8. TEAM DEVELOPMENT:
- Multiple programmers work on different classes
- Clear interfaces between modules
- Reduces coordination issues
9. REDUCED CODE REDUNDANCY:
- Don't Repeat Yourself (DRY) principle
- Common code in base classes
- Less duplication
10. IMPROVED ORGANIZATION:
- Clear hierarchical structure
- Better code organization
- Easier to navigate large codebases
DEMERITS OF OOP:
1. STEEP LEARNING CURVE:
- Complex concepts (inheritance, polymorphism)
- Requires significant time to master
- Difficult for beginners
2. SLOWER EXECUTION:
- OOP overhead (method calls, object creation)
- More memory consumption
- Slower than procedural for small programs
3. LARGE FILE SIZE:
- Object code files are larger
- More memory required at runtime
- Increased storage needs
4. NOT SUITABLE FOR SMALL PROGRAMS:
- Unnecessary complexity
- Overkill for simple tasks
- Procedural approach better
5. DESIGN COMPLEXITY:
- Requires careful architecture planning
- Poor design leads to problems
- Needs experienced designers
6. MESSAGE PASSING OVERHEAD:
- Communication between objects costly
- Method calls have overhead
- Synchronization issues in concurrent systems
7. DIFFICULTY IN CLASS DESIGN:
- Improper design impacts entire system
- Wrong hierarchy causes problems
- Refactoring difficult later
8. DEBUGGING DIFFICULTY:
- Many interacting objects
- Errors difficult to trace
- Complex object relationships
9. DATA MANAGEMENT:
- Complex relationships between objects
- Reference issues and circular dependencies
- Garbage collection overhead
10. TESTING COMPLEXITY:
- Interdependent objects hard to test
- Unit testing more complex
- Integration testing required
WHEN TO USE OOP:
- Large, complex applications
- Team-based development
- Long-term maintenance projects
- Systems with many related entities
- Need for extensibility
WHEN TO USE PROCEDURAL:
- Small, simple programs
- Real-time systems with tight performance
- Linear, sequential processes
- Quick prototyping
- Scripts and automation
CONCLUSION:
OOP provides better organization, reusability, and maintainability for large projects.
However, it adds complexity not needed for simple programs. Choose based on project
requirements, team experience, and project scale.
4. Explain features of Python with suitable examples. Why is Python popular for
beginners?
Marks: 10
FEATURES OF PYTHON:
1. SIMPLE AND READABLE:
- Clear, English-like syntax
- Easier to learn and understand
- Indentation enforces clean code
Example:
```
# Python is readable
if age > 18:
print("Adult")
else:
print("Minor")
# vs C++: More complex syntax with braces, semicolons
```
COMPARISON WITH OTHER LANGUAGES:
Python: 4 lines, very clear
Java: Similar code requires more ceremony
C++: Requires more syntax
2. INTERPRETED LANGUAGE:
- Code executed line-by-line
- No compilation needed
- Errors caught at runtime
- Good for learning (immediate feedback)
Process:
Code → Interpreter → Execution
Advantage: No compilation step saves time
Disadvantage: Slower execution than compiled
3. DYNAMICALLY TYPED:
- No need to declare variable types
- Type determined at assignment
- Flexible but requires care
Example:
```
x = 10 # int
x = "Hello" # str (type changed)
x = 3.14 # float
print(type(x)) # <class 'float'>
```
Python: x = 10 (simple)
Java: int x = 10; (needs type)
C++: int x = 10; (needs type)
4. OBJECT-ORIENTED:
- Supports classes and objects
- Inheritance, polymorphism, encapsulation
- Everything is an object
Example:
```
class Student:
def __init__(self, name, age):
[Link] = name
[Link] = age
def display(self):
print(f"Name: {[Link]}")
```
5. FUNCTIONAL PROGRAMMING:
- Supports lambda, map, filter, reduce
- First-class functions
- Function composition
Example:
```
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
# Result: [1, 4, 9, 16, 25]
```
6. EXTENSIVE STANDARD LIBRARY:
- Rich set of built-in modules
- No need for external libraries for common tasks
- "Batteries included" philosophy
Common Libraries:
- os: Operating system operations
- sys: System-specific parameters
- math: Mathematical functions
- random: Random number generation
- datetime: Date and time handling
- json: JSON data handling
External Libraries (Popular):
- NumPy: Numerical computing
- Pandas: Data analysis
- Django/Flask: Web frameworks
- TensorFlow: Machine learning
7. PLATFORM INDEPENDENT:
- Write once, run anywhere
- Works on Windows, Mac, Linux, etc.
- Same code across platforms
Example:
```
# This code runs on all operating systems
import os
print([Link]()) # Works on all OS
```
8. FREE AND OPEN SOURCE:
- No licensing fees
- Source code available
- Community contributions
- Regular updates and improvements
9. LARGE COMMUNITY SUPPORT:
- Millions of users worldwide
- Abundant tutorials and documentation
- Active forums for help
- Regular conferences and meetups
10. VERSATILE APPLICATION:
- Web development: Django, Flask
- Data Science: NumPy, Pandas, SciPy
- AI/Machine Learning: TensorFlow, Keras, PyTorch
- Automation: Scripts and tools
- Game Development: Pygame
- Scientific Computing
- System Administration
11. EASY INTEGRATION:
- Works with C, C++, Java
- APIs for many tools
- Can embed or extend
Example: Call C functions from Python
12. LARGE STANDARD LIBRARY:
- Comprehensive built-in modules
- Covers most common tasks
- Reduces dependency on external packages
WHY PYTHON IS POPULAR FOR BEGINNERS:
1. LOW BARRIER TO ENTRY:
- Simple syntax doesn't require extensive preparation
- Concepts learned quickly
- Focus on logic, not syntax rules
Learning Curve:
Python: Steep-ish slope, easy start
Java: Very steep, harder to begin
C++: Extremely steep, very difficult
2. IMMEDIATE FEEDBACK:
- Interactive mode (IDLE)
- See results immediately
- Helps understand concepts faster
- Encourages experimentation
3. REAL-WORLD APPLICATIONS:
- Used in major tech companies (Google, Facebook, Netflix)
- Can build real applications while learning
- Not just a "learning language"
- Skills are marketable
4. EXTENSIVE DOCUMENTATION:
- Official documentation is clear
- Thousands of tutorials online
- Stack Overflow community is huge
- Easy to find solutions to problems
5. ACTIVE TEACHING COMMUNITY:
- Used in many universities
- Beginner-friendly courses available
- Books and resources abundant
- Interactive online platforms (CodeAcademy, DataCamp)
6. QUICK SUCCESS:
- Can write useful programs in hours
- Motivates continued learning
- See tangible results quickly
- Boosts confidence
7. DEBUGGING SIMPLICITY:
- Clear error messages
- Stack traces are readable
- Easier to find and fix bugs
- Good debugging tools available
8. FLEXIBILITY IN LEARNING:
- Can start procedural, learn OOP later
- Can mix paradigms
- Not forced into one approach
- Grow with complexity
EXAMPLE: WHY PYTHON > OTHER LANGUAGES FOR BEGINNERS
Task: Print numbers 1 to 5
Python:
for i in range(1, 6):
print(i)
Java:
for (int i = 1; i <= 5; i++) {
[Link](i);
C++:
for (int i = 1; i <= 5; i++) {
cout << i << endl;
Python is clearly the simplest and most readable.
EMPLOYMENT VALUE:
- High demand in job market
- Average Python developer salary competitive
- Companies actively seek Python developers
- Used in startups and large enterprises
CONCLUSION:
Python is ideal for beginners because it combines simplicity with power. The readable
syntax allows focus on logic and concepts rather than language rules. The large community
and extensive resources provide support. The ability to build real applications while
learning is highly motivating. This makes Python the most popular first language for
programming education.
5. Write a Python program to take three numbers as input, find the maximum,
minimum, and calculate their average.
Marks: 5
PROGRAM: FIND MAX, MIN, AND AVERAGE OF THREE NUMBERS
# Method 1: Using if-else statements
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Find maximum
if num1 > num2 and num1 > num3:
maximum = num1
elif num2 > num1 and num2 > num3:
maximum = num2
else:
maximum = num3
# Find minimum
if num1 < num2 and num1 < num3:
minimum = num1
elif num2 < num1 and num2 < num3:
minimum = num2
else:
minimum = num3
# Calculate average
average = (num1 + num2 + num3) / 3
# Display results
print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")
print(f"Average: {average:.2f}")
METHOD 2: USING BUILT-IN FUNCTIONS (RECOMMENDED)
# Most Pythonic approach using built-in functions
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
# Create a list for easier operations
numbers = [num1, num2, num3]
# Find maximum, minimum, and average
maximum = max(numbers)
minimum = min(numbers)
average = sum(numbers) / len(numbers)
# Display results
print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")
print(f"Average: {average:.2f}")
METHOD 3: SINGLE LINE INPUT
# Take all three numbers in one input
numbers = list(map(float, input("Enter three numbers separated by space: ").split()))
maximum = max(numbers)
minimum = min(numbers)
average = sum(numbers) / len(numbers)
print(f"Maximum: {maximum}")
print(f"Minimum: {minimum}")
print(f"Average: {average:.2f}")
SAMPLE OUTPUT:
Input:
Enter first number: 15
Enter second number: 8
Enter third number: 23
Output:
Maximum: 23.0
Minimum: 8.0
Average: 15.33
EXPLANATION OF CODE:
1. INPUT:
- float(input()) converts string input to float
- Allows decimal numbers
2. MAX/MIN FUNCTIONS:
- max(list) returns largest value
- min(list) returns smallest value
- More efficient than nested if-else
3. AVERAGE CALCULATION:
- sum(numbers) adds all values
- len(numbers) returns count (3)
- Division gives average
4. OUTPUT FORMATTING:
- f"..." is f-string formatting
- {average:.2f} shows 2 decimal places
- Makes output clean and readable
KEY CONCEPTS:
1. INPUT CONVERSION:
- input() returns string
- Must convert to float/int
- Use float() for decimal numbers
2. USING BUILT-IN FUNCTIONS:
- max(): Find maximum
- min(): Find minimum
- sum(): Add all elements
- len(): Count elements
3. DATA STRUCTURES:
- List created with []
- Operations on lists are efficient
- Can iterate easily
4. STRING FORMATTING:
- .2f formats to 2 decimal places
- f-strings are modern Python
- Makes output professional
ALTERNATIVE: WITH ERROR HANDLING
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
numbers = [num1, num2, num3]
print(f"Maximum: {max(numbers)}")
print(f"Minimum: {min(numbers)}")
print(f"Average: {sum(numbers)/len(numbers):.2f}")
except ValueError:
print("Error: Please enter valid numbers!")
This handles cases where user enters non-numeric input.
6. Explain data types in Python with examples. Differentiate between mutable
and immutable data types.
Marks: 10
DATA TYPES IN PYTHON:
A data type specifies the type of data a variable can hold. Python is dynamically typed,
meaning the type is determined at runtime based on the assigned value.
BUILT-IN DATA TYPES:
1. NUMERIC TYPES:
INTEGER (int):
- Whole numbers (positive, negative, zero)
- No decimal point
- Unlimited precision
```
age = 25
temperature = -10
big_num = 1000000000000
print(type(age)) # <class 'int'>
```
FLOAT (float):
- Decimal numbers
- Contains decimal point
- Scientific notation supported
```
height = 5.8
pi = 3.14159
scientific = 1.5e-3 # 0.0015
print(type(height)) # <class 'float'>
```
COMPLEX (complex):
- Real and imaginary parts
- Format: a+bj
```
c = 3+4j
print([Link]) # 3.0
print([Link]) # 4.0
```
2. STRING (str):
- Sequence of characters
- Immutable
- Enclosed in quotes
```
name = "Python"
message = 'Hello'
multiline = """Multi
line
string"""
print(type(name)) # <class 'str'>
```
3. BOOLEAN (bool):
- True or False
- Result of comparisons
- Used in conditions
```
is_valid = True
is_empty = False
print(5 > 3) # True
print(type(is_valid)) # <class 'bool'>
```
4. SEQUENCE TYPES:
LIST (list):
- Ordered collection
- Mutable (can change)
- Elements in square brackets
```
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14]
nested = [1, [2, 3], 4]
```
TUPLE (tuple):
- Ordered collection
- Immutable (cannot change)
- Elements in parentheses
```
coordinates = (4, 5)
colors = ("red", "green")
single = (1,) # Note comma
```
RANGE (range):
- Sequence of numbers
- Immutable
- Used in loops
```
r = range(1, 6) # 1, 2, 3, 4, 5
r = range(0, 10, 2) # 0, 2, 4, 6, 8
```
5. SET (set):
- Unordered collection
- Unique values only
- Mutable
```
numbers = {1, 2, 3}
colors = {"red", "green", "blue"}
empty = set() # Note: {} creates dict
```
6. DICTIONARY (dict):
- Key-value pairs
- Unordered (Python 3.7+ maintains order)
- Mutable
```
student = {"name": "John", "age": 20}
empty = {}
nested = {"person": {"name": "John"}}
```
7. NONE TYPE:
- Represents absence of value
- Placeholder
```
result = None
print(type(result)) # <class 'NoneType'>
```
MUTABLE VS IMMUTABLE DATA TYPES:
MUTABLE DATA TYPES (Can be modified):
LIST:
```
numbers = [1, 2, 3]
numbers[0] = 10 # Change element
[Link](4) # Add element
[Link](2) # Remove element
print(numbers) # [10, 3, 4]
```
DICTIONARY:
```
person = {"name": "John", "age": 20}
person["age"] = 21 # Modify value
person["city"] = "Delhi" # Add new key-value
del person["age"] # Remove key
print(person) # {"name": "John", "city": "Delhi"}
```
SET:
```
colors = {"red", "green", "blue"}
[Link]("yellow") # Add element
[Link]("red") # Remove element
print(colors) # {"green", "blue", "yellow"}
```
IMMUTABLE DATA TYPES (Cannot be modified):
STRING:
```
name = "Python"
# name[0] = "J" # ERROR! Cannot modify
# [Link]("!") # ERROR! Strings don't have append
# Create new string instead
name = name + "!" # "Python!"
name = [Link]("Python", "Java")
```
TUPLE:
```
coordinates = (4, 5)
# coordinates[0] = 10 # ERROR! Cannot modify
# [Link](6) # ERROR! No append
# Can reassign variable
coordinates = (10, 5)
```
NUMBER (int, float):
```
x = 10
# x[0] = 5 # ERROR! Cannot index
# [Link] = 20 # ERROR! Cannot modify
# Reassign variable
x = 20
```
COMPARISON TABLE:
MUTABLE | IMMUTABLE
Can modify? Yes | No
Examples list, dict, set | str, tuple, int, float
Change element? list[0] = new_val | Error!
Add element? [Link](val) | Error!
Remove? [Link](val) | Error!
Pass to func? May be modified | Safe, not modified
Use as key? No (in dict) | Yes (in dict)
Hashable? No | Yes
WHY THIS DISTINCTION?
1. PERFORMANCE:
- Immutable types optimized for certain operations
- Can be cached/reused
- Better for dictionary keys
2. SAFETY:
- Immutable types safer in concurrent programs
- No unexpected modifications
- Easier to reason about code
3. DICTIONARY KEYS:
- Only immutable types can be keys
- Ensures consistency
```
# Valid
d = {1: "one", "two": 2, (1, 2): "tuple"}
# Invalid - Lists and dicts cannot be keys
# d = {[1, 2]: "list"} # ERROR!
# d = {{"a": 1}: "dict"} # ERROR!
```
4. INTERNING:
- Small immutable values reused
- Saves memory
```
a = 256 # Same object
b = 256 # a is b → True
a = 257 # Different objects
b = 257 # a is b → False
```
PRACTICAL EXAMPLES:
# When to use list (mutable):
grades = [85, 90, 88]
grades[0] = 95 # Update a grade
[Link](92) # Add new grade
# When to use tuple (immutable):
coordinates = (10, 20)
# Tuple unpacking
x, y = coordinates
# Can't accidentally modify
# When to use string (immutable):
message = "Hello"
message = [Link]("Hello", "Hi")
# Original not changed, new string created
# When to use dict:
student = {"name": "John", "age": 20}
student["age"] = 21 # Update value
student["email"] = "john@[Link]" # Add new key
KEY TAKEAWAYS:
1. Mutable types allow modifications: list, dict, set
2. Immutable types cannot be modified: str, tuple, int, float
3. Immutable types are hashable and can be dict keys
4. Immutable types are safer and more efficient
5. Choose based on whether you need to modify the data
6. Reassigning variable is different from modifying data type
7. Write a program to calculate simple interest. Take principal, rate, and time as
input from user.
Marks: 5
PROGRAM: CALCULATE SIMPLE INTEREST
Formula: SI = (P × R × T) / 100
Where:
P = Principal (initial amount)
R = Rate of interest (per annum)
T = Time period (in years)
SI = Simple Interest
AMOUNT = Principal + Simple Interest
METHOD 1: BASIC APPROACH
# Input from user
principal = float(input("Enter principal amount: "))
rate = float(input("Enter rate of interest (% per annum): "))
time = float(input("Enter time period (in years): "))
# Calculate simple interest
simple_interest = (principal * rate * time) / 100
# Calculate total amount
amount = principal + simple_interest
# Display results
print(f"\n--- Simple Interest Calculation ---")
print(f"Principal: Rs. {principal}")
print(f"Rate of Interest: {rate}% per annum")
print(f"Time Period: {time} years")
print(f"Simple Interest: Rs. {simple_interest}")
print(f"Total Amount: Rs. {amount}")
METHOD 2: WITH INPUT VALIDATION
# Get inputs with validation
while True:
try:
principal = float(input("Enter principal amount (Rs.): "))
if principal <= 0:
print("Error: Principal must be positive!")
continue
break
except ValueError:
print("Error: Please enter a valid number!")
while True:
try:
rate = float(input("Enter rate of interest (% per annum): "))
if rate < 0:
print("Error: Rate cannot be negative!")
continue
break
except ValueError:
print("Error: Please enter a valid number!")
while True:
try:
time = float(input("Enter time period (in years): "))
if time <= 0:
print("Error: Time must be positive!")
continue
break
except ValueError:
print("Error: Please enter a valid number!")
# Calculate simple interest
simple_interest = (principal * rate * time) / 100
amount = principal + simple_interest
# Display results in formatted way
print(f"\n{'='*40}")
print(f"{'SIMPLE INTEREST CALCULATION RESULT':<40}")
print(f"{'='*40}")
print(f"{'Principal Amount':<20}: Rs. {principal:>10.2f}")
print(f"{'Rate of Interest':<20}: {rate:>10.2f}%")
print(f"{'Time Period':<20}: {time:>10.2f} years")
print(f"{'-'*40}")
print(f"{'Simple Interest':<20}: Rs. {simple_interest:>10.2f}")
print(f"{'Total Amount':<20}: Rs. {amount:>10.2f}")
print(f"{'='*40}")
METHOD 3: USING FUNCTION
def calculate_simple_interest(principal, rate, time):
"""
Calculate simple interest
Args:
principal: Initial amount
rate: Interest rate per annum
time: Time period in years
Returns:
Tuple of (simple_interest, total_amount)
"""
simple_interest = (principal * rate * time) / 100
total_amount = principal + simple_interest
return simple_interest, total_amount
# Main program
principal = float(input("Enter principal amount (Rs.): "))
rate = float(input("Enter rate of interest (% per annum): "))
time = float(input("Enter time period (in years): "))
# Calculate using function
si, amount = calculate_simple_interest(principal, rate, time)
# Display results
print(f"\nSimple Interest: Rs. {si:.2f}")
print(f"Total Amount: Rs. {amount:.2f}")
SAMPLE OUTPUT:
Input:
Enter principal amount (Rs.): 5000
Enter rate of interest (% per annum): 8
Enter time period (in years): 2
Output:
========================================
SIMPLE INTEREST CALCULATION RESULT
========================================
Principal Amount : Rs. 5000.00
Rate of Interest : 8.00%
Time Period : 2.00 years
----------------------------------------
Simple Interest : Rs. 800.00
Total Amount : Rs. 5800.00
========================================
EXPLANATION:
1. INPUT:
- float(input()) reads decimal values
- Allows for flexibility (e.g., 8.5% rate)
2. CALCULATION:
- SI = (P × R × T) / 100
- Formula: (5000 × 8 × 2) / 100 = 800
- Amount = Principal + SI = 5000 + 800 = 5800
3. OUTPUT FORMATTING:
- f"..." used for f-string formatting
- :.2f formats to 2 decimal places
- Makes output professional and readable
4. VALIDATION (Method 2):
- Checks if values are valid
- Prevents negative principals
- Handles non-numeric input
5. FUNCTION (Method 3):
- Reusable code
- Easier to test
- Better organization
KEY FEATURES:
✓ Takes user input
✓ Calculates using formula
✓ Displays results clearly
✓ Handles decimal values
✓ Professional formatting
✓ Optional: Input validation
✓ Optional: Function-based approach
DIFFERENT SCENARIOS:
Scenario 1: Loan interest
Principal: Rs. 100,000
Rate: 10% per annum
Time: 3 years
SI = (100000 × 10 × 3) / 100 = Rs. 30,000
Amount = Rs. 130,000
Scenario 2: Bank deposit
Principal: Rs. 50,000
Rate: 5% per annum
Time: 2 years
SI = (50000 × 5 × 2) / 100 = Rs. 5,000
Amount = Rs. 55,000
NOTE:
Simple interest assumes interest is not compounded. For compound interest, use:
A = P(1 + r/100)^t
8. Explain reserved words (keywords) in Python. Why are they important? List
important keywords with their usage.
Marks: 10
RESERVED WORDS (KEYWORDS) IN PYTHON:
Reserved words are words that have special meaning in Python and cannot be used as
variable names, function names, module names, or any other identifier. They are part of
Python syntax.
WHAT ARE KEYWORDS?
Keywords are predefined tokens that perform specific operations or functions in the
language. They are reserved for these specific purposes and cannot be redefined or used for
other purposes.
Example of Keyword Vs Identifier:
if x > 5: # 'if' is keyword, 'x' is identifier
print("Valid") # 'print' is function, not keyword
WHY ARE KEYWORDS IMPORTANT?
1. SYNTAX STRUCTURE:
- Define program flow (if, while, for)
- Control program logic
- Establish program structure
2. CLARITY:
- Clear intention of code
- Standardized meaning
- No ambiguity
3. PARSER UNDERSTANDING:
- Help Python parser understand code
- Distinguish between code and variables
- Proper interpretation of statements
4. ERROR PREVENTION:
- Prevents accidental misuse
- Enforces correct syntax
- Makes code more reliable
5. CONSISTENCY:
- Ensures all Python code follows same rules
- Makes code portable
- Easier for other programmers to understand
COMPLETE LIST OF PYTHON KEYWORDS (36 TOTAL):
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
CATEGORIZED KEYWORDS:
1. CONTROL FLOW KEYWORDS:
IF, ELIF, ELSE:
- Conditional branching
- Execute code based on condition
```
if age > 18:
print("Adult")
elif age == 18:
print("Just turned adult")
else:
print("Minor")
```
FOR:
- Loop iteration
- Iterate over sequence
```
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for item in [1, 2, 3]:
print(item)
```
WHILE:
- Conditional loop
- Execute while condition true
```
i=0
while i < 5:
print(i)
i += 1
```
BREAK:
- Exit loop immediately
```
for i in range(10):
if i == 5:
break # Exits loop when i = 5
print(i) # Prints 0-4
```
CONTINUE:
- Skip current iteration
- Jump to next iteration
```
for i in range(5):
if i == 2:
continue # Skip i = 2
print(i) # Prints 0, 1, 3, 4
```
PASS:
- Null operation (do nothing)
- Placeholder for future code
```
if condition:
pass # Will implement later
class MyClass:
pass # Empty class definition
```
2. FUNCTION DEFINITION KEYWORDS:
DEF:
- Define function
```
def greet(name):
return f"Hello, {name}"
```
RETURN:
- Return value from function
```
def add(a, b):
return a + b # Function returns result
```
LAMBDA:
- Anonymous function
- Single expression function
```
square = lambda x: x ** 2
result = square(5) # 25
```
YIELD:
- Generator function
- Yields values one at a time
```
def count():
for i in range(3):
yield i # Returns value without exiting
```
3. CLASS DEFINITION KEYWORDS:
CLASS:
- Define class
```
class Student:
def __init__(self, name):
[Link] = name
```
4. EXCEPTION HANDLING KEYWORDS:
TRY:
- Start error handling block
```
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
```
EXCEPT:
- Catch specific exception
```
try:
age = int(input("Age: "))
except ValueError:
print("Invalid input")
```
FINALLY:
- Execute regardless of exception
```
try:
file = open("[Link]")
except FileNotFoundError:
print("File not found")
finally:
print("Cleanup code") # Always executes
```
RAISE:
- Raise custom exception
```
if age < 0:
raise ValueError("Age cannot be negative")
```
ASSERT:
- Check condition, raise if false
```
x = 10
assert x > 0, "x must be positive" # Passes
assert x < 0, "x must be negative" # Raises AssertionError
```
5. IMPORT KEYWORDS:
IMPORT:
- Import module
```
import math
import os, sys # Multiple imports
```
FROM:
- Import specific item from module
```
from math import sqrt
from os import getcwd
```
AS:
- Create alias for import
```
import numpy as np
from math import sqrt as square_root
```
6. VARIABLE SCOPE KEYWORDS:
GLOBAL:
- Declare global variable
- Access global scope
```
global x
x = 10
def modify():
global x
x = 20 # Modifies global x
```
NONLOCAL:
- Declare nonlocal variable
- Access enclosing scope
```
def outer():
x = 10
def inner():
nonlocal x
x = 20 # Modifies x in outer()
inner()
return x # 20
```
7. LOGICAL OPERATORS:
AND:
- Logical AND
- Both conditions must be true
```
if age > 18 and name == "John":
print("Eligible")
```
OR:
- Logical OR
- Either condition can be true
```
if age > 18 or age == 18:
print("Adult or just turned adult")
```
NOT:
- Logical NOT
- Negate condition
```
if not is_student:
print("Not a student")
```
8. MEMBERSHIP/IDENTITY KEYWORDS:
IN:
- Check membership
- Check if value in sequence
```
if 5 in [1, 2, 3, 4, 5]:
print("Found")
```
IS:
- Check object identity
- Same object in memory
```
a = [1, 2, 3]
b=a
if a is b:
print("Same object")
```
9. SPECIAL KEYWORDS:
NONE:
- Null value
- Absence of value
```
result = None
```
TRUE, FALSE:
- Boolean values
```
is_valid = True
is_empty = False
```
10. ASYNC/AWAIT KEYWORDS:
ASYNC:
- Asynchronous function
```
async def fetch_data():
await some_async_operation()
```
AWAIT:
- Wait for asynchronous operation
```
async def process():
result = await fetch_data()
return result
```
11. CONTEXT MANAGER:
WITH:
- Context manager statement
- Automatic cleanup
```
with open("[Link]") as f:
content = [Link]()
# File automatically closed
```
DEL:
- Delete object or reference
```
del variable_name # Removes variable
del list[0] # Removes element
```
HOW TO CHECK KEYWORDS IN PYTHON:
import keyword
# Print all keywords
print([Link])
# Check if word is keyword
print([Link]("if")) # True
print([Link]("myvar")) # False
# Count keywords
print(len([Link])) # 36 (Python 3.10+)
COMPARISON: KEYWORD VS IDENTIFIER:
# Valid identifiers (not keywords)
myVariable = 10
_private = 20
CLASS_NAME = "Python" # VALID - not same as 'class'
# Invalid (keywords, cannot use)
# class = "Name" # ERROR - 'class' is keyword
# for = 5 # ERROR - 'for' is keyword
# if = True # ERROR - 'if' is keyword
COMMON MISTAKES:
Mistake 1: Using keyword as variable
# WRONG
class = "MyClass" # Error: class is keyword
# RIGHT
class_name = "MyClass"
Mistake 2: Forgetting proper keyword usage
# WRONG
if x > 5
print("Greater") # Syntax error
# RIGHT
if x > 5:
print("Greater")
Mistake 3: Wrong indentation with keywords
# WRONG
if x > 5:
print("Greater") # IndentationError
# RIGHT
if x > 5:
print("Greater")
KEY TAKEAWAYS:
1. Keywords are reserved and cannot be used as identifiers
2. Understanding keywords is crucial for writing correct Python
3. Each keyword has specific purpose and syntax
4. Keywords help define program structure
5. 36 keywords in Python (may vary by version)
6. Use [Link]() to check if word is keyword
7. Keywords enforce consistent syntax across Python programs
8. Misusing keywords causes SyntaxError
9. Write a program to take a number as input and check if it is positive,
negative, or zero.
Marks: 5
PROGRAM: CHECK IF NUMBER IS POSITIVE, NEGATIVE, OR ZERO
METHOD 1: BASIC IF-ELIF-ELSE
# Input from user
number = float(input("Enter a number: "))
# Check if positive, negative, or zero
if number > 0:
print(f"{number} is a positive number")
elif number < 0:
print(f"{number} is a negative number")
else:
print(f"{number} is zero")
METHOD 2: USING FUNCTION
def check_number(num):
"""
Check if number is positive, negative, or zero
Args:
num: The number to check
Returns:
String describing the number
"""
if num > 0:
return f"{num} is a positive number"
elif num < 0:
return f"{num} is a negative number"
else:
return f"{num} is zero"
# Main program
number = float(input("Enter a number: "))
result = check_number(number)
print(result)
METHOD 3: WITH INPUT VALIDATION
# Input with validation
while True:
try:
number = float(input("Enter a number: "))
break # Valid input, exit loop
except ValueError:
print("Error: Please enter a valid number!")
# Check number
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
else:
print(f"{number} is zero")
METHOD 4: USING CONDITIONAL EXPRESSION (TERNARY)
number = float(input("Enter a number: "))
# Using ternary operator
result = "positive" if number > 0 else ("negative" if number < 0 else "zero")
print(f"{number} is {result}")
METHOD 5: ENHANCED VERSION WITH CATEGORIES
number = float(input("Enter a number: "))
# Categorize number
if number > 0:
if number < 1:
category = "positive (less than 1)"
elif number == 1:
category = "positive (equals 1)"
else:
category = "positive (greater than 1)"
elif number < 0:
if number > -1:
category = "negative (greater than -1)"
else:
category = "negative (less than -1)"
else:
category = "zero"
print(f"{number} is {category}")
SAMPLE OUTPUTS:
Test Case 1:
Input: 25
Output: 25.0 is a positive number
Test Case 2:
Input: -10
Output: -10.0 is a negative number
Test Case 3:
Input: 0
Output: 0.0 is zero
Test Case 4:
Input: 0.5
Output: 0.5 is a positive number
EXPLANATION:
1. INPUT:
- float(input()) allows decimal input
- Converts user input to float
2. CONDITIONAL LOGIC:
- if number > 0: Positive check
- elif number < 0: Negative check
- else: Zero (only option left)
3. OUTPUT:
- f-string formatting for readable output
- Shows the actual number entered
4. FLOW:
- Only one condition executes
- Other conditions skipped
- Order of conditions important
KEY CONCEPTS:
1. COMPARISON OPERATORS:
- >: Greater than
- <: Less than
- ==: Equal to
2. CONDITIONAL FLOW:
- if: First condition
- elif: Alternative condition
- else: Default if no condition met
3. INPUT CONVERSION:
- input() returns string
- float() converts to decimal number
- int() converts to integer
4. STRING FORMATTING:
- f"{variable}" in f-string
- Shows value in message
LOGIC FLOW:
Enter Number
|
V
Is number > 0?
|----YES----> Print "positive"
|
|----NO----> Is number < 0?
|----YES----> Print "negative"
|
|----NO-----> Print "zero"
ERROR HANDLING VERSION:
try:
number = float(input("Enter a number: "))
if number > 0:
print(f"{number} is positive")
elif number < 0:
print(f"{number} is negative")
else:
print(f"{number} is zero")
except ValueError:
print("Error: Invalid input! Please enter a number.")
INTERACTIVE VERSION:
def main():
print("=== Number Checker ===")
while True:
number = float(input("\nEnter a number (or 'q' to quit): "))
print(f"✓ {number} is positive")
if number > 0:
elif number < 0:
print(f"✗ {number} is negative")
else:
print(f"= {number} is zero")
again = input("Check another number? (y/n): ")
if [Link]() != 'y':
break
print("Thank you for using Number Checker!")
if __name__ == "__main__":
main()
NOTES:
- Zero is neither positive nor negative
- Works with decimal numbers (floats)
- Can be extended to categorize further
- Essential for conditional programming
- Foundation for more complex programs
RELATED PROGRAMS:
1. Check even/odd:
if number % 2 == 0: print("even")
else: print("odd")
2. Check if integer:
if number == int(number): print("integer")
3. Check in range:
if 0 < number < 100: print("in range 0-100")
10. Explain operators in Python. Write a program demonstrating different types
of operators.
Marks: 10
OPERATORS IN PYTHON:
Operators are symbols that perform specific operations on values and variables. They are
used to manipulate data, create expressions, and control program flow.
TYPES OF OPERATORS:
1. ARITHMETIC OPERATORS:
Used for mathematical calculations.
Operator | Operation | Example | Result
---------|-------------------|---------|--------
+ | Addition | 10 + 5 | 15
- | Subtraction | 10 - 5 | 5
* | Multiplication | 10 * 5 | 50
/ | Division | 10 / 5 | 2.0
// | Floor Division | 10 // 3 | 3
% | Modulus (Remainder)| 10 % 3 | 1
** | Exponentiation | 2 ** 3 | 8
```python
# Arithmetic Operators Demo
a = 20
b=3
print(f"Addition: {a} + {b} = {a + b}") # 23
print(f"Subtraction: {a} - {b} = {a - b}") # 17
print(f"Multiplication: {a} * {b} = {a * b}") # 60
print(f"Division: {a} / {b} = {a / b}") # 6.667
print(f"Floor Division: {a} // {b} = {a // b}") # 6
print(f"Modulus: {a} % {b} = {a % b}") #2
print(f"Exponentiation: {a} ** {b} = {a ** b}") # 8000
```
2. COMPARISON OPERATORS:
Compare two values and return boolean (True/False).
Operator | Meaning | Example | Result
---------|---------------------|----------|--------
== | Equal to | 5 == 5 | True
!= | Not equal to | 5 != 3 | True
< | Less than | 3 < 5 | True
> | Greater than | 5 > 3 | True
<= | Less than or equal | 5 <= 5 | True
>= | Greater than or equal| 5 >= 3 | True
```python
# Comparison Operators Demo
x = 10
y=5
print(f"{x} == {y}: {x == y}") # False
print(f"{x} != {y}: {x != y}") # True
print(f"{x} < {y}: {x < y}") # False
print(f"{x} > {y}: {x > y}") # True
print(f"{x} <= {y}: {x <= y}") # False
print(f"{x} >= {y}: {x >= y}") # True
```
3. LOGICAL OPERATORS:
Combine boolean expressions.
Operator | Description | Example
---------|--------------------------------|--------------------
and | True if both conditions true | (a > 5) and (b > 3)
or | True if any condition true | (a > 5) or (b > 3)
not | Reverse boolean result | not (a > 5)
```python
# Logical Operators Demo
a = 10
b=3
# AND operator
print(f"({a} > 5) and ({b} > 2): {(a > 5) and (b > 2)}")
# True and True = True
print(f"({a} > 5) and ({b} > 5): {(a > 5) and (b > 5)}")
# True and False = False
# OR operator
print(f"({a} > 5) or ({b} > 5): {(a > 5) or (b > 5)}")
# True or False = True
print(f"({a} < 5) or ({b} < 2): {(a < 5) or (b < 2)}")
# False or False = False
# NOT operator
print(f"not ({a} > 5): {not (a > 5)}")
# not True = False
print(f"not ({a} < 5): {not (a < 5)}")
# not False = True
```
4. ASSIGNMENT OPERATORS:
Assign values to variables.
Operator | Equivalent to | Example | Value
---------|--------------|---------|-------
= | x = value | x = 5 | 5
+= | x = x + value| x += 3 | x = x + 3
-= | x = x - value| x -= 3 | x = x - 3
*= | x = x * value| x *= 3 | x = x * 3
/= | x = x / value| x /= 3 | x = x / 3
//= | x = x // value| x //= 3| x = x // 3
%= | x = x % value| x %= 3 | x = x % 3
**= | x = x ** value| x **= 3| x = x ** 3
```python
# Assignment Operators Demo
x = 10
print(f"Initial value: x = {x}")
x += 5
print(f"After x += 5: x = {x}") # 15
x -= 3
print(f"After x -= 3: x = {x}") # 12
x *= 2
print(f"After x *= 2: x = {x}") # 24
x //= 5
print(f"After x //= 5: x = {x}") # 4
x **= 2
print(f"After x **= 2: x = {x}") # 16
```
5. IDENTITY OPERATORS:
Check if objects are identical.
Operator | Description
---------|-----------------------------------------------------
is | True if both variables reference same object
is not | True if variables reference different objects
```python
# Identity Operators Demo
a = [1, 2, 3]
b=a
c = [1, 2, 3]
print(f"a = {a}, b = {b}, c = {c}")
print(f"a is b: {a is b}") # True (same object)
print(f"a is c: {a is c}") # False (different objects)
print(f"a is not c: {a is not c}") # True
# Demonstrate with numbers
x = 256
y = 256
print(f"x is y: {x is y}") # True (Python caches small integers)
x = 257
y = 257
print(f"x is y: {x is y}") # False (beyond cache range)
```
6. MEMBERSHIP OPERATORS:
Check if value exists in sequence.
Operator | Description
---------|-----------------------------------------------------
in | True if value exists in sequence
not in | True if value does not exist in sequence
```python
# Membership Operators Demo
numbers = [1, 2, 3, 4, 5]
print(f"3 in {numbers}: {3 in numbers}") # True
print(f"10 in {numbers}: {10 in numbers}") # False
print(f"10 not in {numbers}: {10 not in numbers}") # True
# With strings
text = "Hello World"
print(f"'H' in '{text}': {'H' in text}") # True
print(f"'x' not in '{text}': {'x' not in text}") # True
# With dictionaries
person = {"name": "John", "age": 20}
print(f"'name' in person: {'name' in person}") # True
print(f"'email' not in person: {'email' not in person}") # True
```
COMPREHENSIVE DEMONSTRATION PROGRAM:
print("="*50)
print("OPERATOR DEMONSTRATION PROGRAM")
print("="*50)
# Input from user
a = float(input("\nEnter first number: "))
b = float(input("Enter second number: "))
# 1. ARITHMETIC OPERATORS
print("\n1. ARITHMETIC OPERATORS:")
print(f"Addition ({a} + {b}) = {a + b}")
print(f"Subtraction ({a} - {b}) = {a - b}")
print(f"Multiplication ({a} * {b}) = {a * b}")
print(f"Division ({a} / {b}) = {a / b:.2f}")
print(f"Floor Division ({a} // {b}) = {int(a // b)}")
print(f"Modulus ({a} % {b}) = {a % b:.2f}")
print(f"Exponentiation ({a} ** {b}) = {a ** b:.2f}")
# 2. COMPARISON OPERATORS
print("\n2. COMPARISON OPERATORS:")
print(f"{a} == {b}: {a == b}")
print(f"{a} != {b}: {a != b}")
print(f"{a} < {b}: {a < b}")
print(f"{a} > {b}: {a > b}")
print(f"{a} <= {b}: {a <= b}")
print(f"{a} >= {b}: {a >= b}")
# 3. LOGICAL OPERATORS
print("\n3. LOGICAL OPERATORS:")
print(f"({a} > 0) and ({b} > 0): {(a > 0) and (b > 0)}")
print(f"({a} > 0) or ({b} < 0): {(a > 0) or (b < 0)}")
print(f"not ({a} > 0): {not (a > 0)}")
# 4. ASSIGNMENT OPERATORS
print("\n4. ASSIGNMENT OPERATORS:")
x=a
print(f"x = {a}: x = {x}")
x += 5
print(f"After x += 5: x = {x}")
x -= 2
print(f"After x -= 2: x = {x}")
x *= 2
print(f"After x *= 2: x = {x}")
# 5. IDENTITY OPERATORS
print("\n5. IDENTITY OPERATORS:")
list1 = [1, 2, 3]
list2 = list1
list3 = [1, 2, 3]
print(f"list1 is list2: {list1 is list2}") # True
print(f"list1 is list3: {list1 is list3}") # False
print(f"list1 is not list3: {list1 is not list3}") # True
# 6. MEMBERSHIP OPERATORS
print("\n6. MEMBERSHIP OPERATORS:")
numbers = [1, 2, 3, 4, 5]
print(f"3 in [1,2,3,4,5]: {3 in numbers}")
print(f"10 in [1,2,3,4,5]: {10 in numbers}")
print(f"10 not in [1,2,3,4,5]: {10 not in numbers}")
print("\n" + "="*50)
OPERATOR PRECEDENCE (Highest to Lowest):
1. ** - Exponentiation
2. *, /, //, % - Multiplication, Division, Floor Division, Modulus
3. +, - - Addition, Subtraction
4. ==, !=, <, >, <=, >= - Comparison operators
5. not - Logical NOT
6. and - Logical AND
7. or - Logical OR
# Precedence Example
result = 10 + 5 * 2 # 5*2=10, then 10+10=20
print(result) # 20
result = (10 + 5) * 2 # 10+5=15, then 15*2=30
print(result) # 30
KEY POINTS:
1. Arithmetic operators perform mathematical operations
2. Comparison operators return boolean values
3. Logical operators combine boolean expressions
4. Assignment operators modify variable values
5. Identity operators check object identity
6. Membership operators check value presence
7. Operator precedence determines evaluation order
8. Parentheses can override precedence
9. Different operators have different purposes
10. Combining operators creates complex expressions
PRACTICE EXERCISES:
1. Calculate area of rectangle using operators
2. Check if number is even or odd using %
3. Check age group using comparison and logical operators
4. Check if list element exists using membership operator
5. Use assignment operators to update values incrementally