0% found this document useful (0 votes)
23 views106 pages

Python Basics

This document is a comprehensive guide to Python programming, covering topics such as data types, conditional statements, looping, file handling, and exception handling. It also includes an introduction to Python's history, programming style, and documentation practices. The guide emphasizes Python's versatility as a high-level, interpreted language suitable for various applications including web development and data science.

Uploaded by

sai vivek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views106 pages

Python Basics

This document is a comprehensive guide to Python programming, covering topics such as data types, conditional statements, looping, file handling, and exception handling. It also includes an introduction to Python's history, programming style, and documentation practices. The guide emphasizes Python's versatility as a high-level, interpreted language suitable for various applications including web development and data science.

Uploaded by

sai vivek
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 106

✏️

Python
Created @June 25, 2025 4:19 PM

Class programming

TABLE OF CONTENT
1. Introduction to Python
What is Python?

Identifiers and Variables

Data Types

Operators

Comments

Type Conversions

Keywords

Built-in Functions

Input and Output in Python

2. Conditional Statements
if Statement

if-else Statement

if-elif-else Statement

Nested if

Shorthand if

Ternary Operator

match-case Statement

3. Looping Statements
Entry and Exit Controlled Loops

Python 1
for Loop

while Loop

Nested Loops

4. File Handling
File Modes

Opening and Reading Files

Writing and Creating Files

Checking Existence and Deleting Files

5. Python Exception Handling


try-except Block

Nested try Blocks

finally Clause

Raising Exceptions

6. Strings
Introduction to Strings

Indexing

Slicing

Concatenation

Repetition

Membership

String Formatting

String Methods

7. Lists
Introduction to Lists

Creating Lists

List Methods

8. Tuples
Introduction to Tuples

Tuple Properties

Python 2
Tuple Operations

Tuple Methods

Tuple Functions

9. Dictionaries
Introduction to Dictionaries

Dictionary Operations

Creating Dictionaries

Accessing Elements

Membership Testing

Iteration over Dictionaries

Dictionary Methods

Dictionary Functions

10. Sets
Set Properties

Set Operations

Set Methods

INTRODUCTION TO PYTHON
Python
Python is a high-level, interpreted, general-purpose programming language
known for its simplicity, readability, and versatility.

Feature Description

Abstracts low-level machine details, easy


High-level
for humans to understand

Executes code line-by-line (no need for


Interpreted
compilation)

You don't need to declare variable types;


Dynamically typed
they are inferred at runtime

Used for web development, data science,


General-purpose
AI, scripting, automation, etc.

Supports classes and objects for modular


Object-oriented
and reusable code

Python 3
Free to use and has a large developer
Open-source
community

Applications of Python:
Web development (Django, Flask)

Data science and machine learning (Pandas, NumPy, scikit-learn)

Artificial Intelligence

Automation and scripting

Game development

Desktop applications

IoT and embedded systems

History of Python
Year Event

Python was conceived by Guido van


Late 1980s Rossum at Centrum Wiskunde &
Informatica (CWI) in the Netherlands.

Guido van Rossum began working on


1989 Python as a hobby project over the
Christmas holidays.

Python 0.9.0 was released — it already


1991 included classes, functions, exception
handling, and core data types (list, dict, str).

Python 1.0 was officially released.


1994 Introduced new features like lambda, map,
filter, and reduce.

Python 2.0 released with new features like


list comprehensions and garbage
2000
collection based on reference counting and
cyclic garbage collection.

Python 3.0 (also called “Python 3000” or


“Py3k”) was released. This was a major
2008
revision, not backward compatible with
Python 2.

Python gained huge popularity due to its


2010s use in data science, AI, web development,
and education.

Python 4
Python 2 reached end of life on January 1,
2020 2020. The community fully shifted to
Python 3.

Latest versions include Python 3.11 and


2023–2024 3.12, offering faster execution and modern
syntax improvements.

Programming Style and Documentation in Python

1. Programming Style in Python


Python emphasizes clean, readable, and consistent code. Good programming
style improves readability, maintainability, and collaboration.

Style Element Recommendation

Indentation Use 4 spaces per indentation level (no tabs).

Use lowercase_with_underscores for


Variable names
variables and functions.

Class names Use CapitalizedWords style (PascalCase).

Line length Keep lines ≤ 79 characters.

Use blank lines to separate functions and


Blank lines
classes.

Import statements Place at the top of the file, one per line.

Write meaningful comments. Use # for inline


Comments
comments.

Use triple quotes ( """ """ ) for documenting


Docstrings
functions, classes, and modules.

2. Documentation in Python
Documentation explains what your code does, how to use it, and why it was
written that way.

Type Description

Short # comments within code to explain


Inline comments
tricky logic.

Descriptive strings used at the start of


Docstrings
functions, classes, and modules.

Markdown or .txt files to explain larger


External docs
projects, often named README.md .

Helps others understand and use your code

Makes debugging and updating easier

Python 5
Follows professional and academic standards
Identifier and Variables
1. Identifier
An identifier is the name used to identify a variable, function, class, module, or
object.

Rules for Identifiers:


Can contain letters (a–z, A–Z), digits (0–9), and underscores (_)

Cannot start with a digit

Cannot be a Python keyword (like if , while , class , etc.)

Python is case-sensitive, so Var and var are different

2. Variable
A variable is a named memory location used to store data.

The name of the variable is an identifier, and the value can change during
program execution

3. Assignment Statement
An assignment statement is used to assign a value to a variable using the
assignment operator = .

Difference Between Variable and Identifier


Aspect Variable Identifier

A variable is a named An identifier is the name


Definition memory location used to used to identify variables,
store data. functions, classes, etc.

Holds values (like numbers, Gives a name to program


Purpose
strings, lists, etc.) elements

No, it's the actual storage or Yes, it's a name/label given


Is it a name?
reference to a value to the variable

x = 10 , name = "Alice" → x , In x = 10 , x is an identifier


Examples
name are variables used to name the variable

Naming variables, functions,


Used for Storing data
classes, etc.

Occupies memory space to Does not occupy memory


Memory
store a value by itself

Python 6
All variables must be named using identifiers, but not all identifiers are
variables.

For example, function names, class names, and module names are identifiers —
but they are not variables.

city = "Mumbai"
population = 20400000

Name Type Reason


city Variable Stores the value "Mumbai"

Stores the number


population Variable
20400000

They are the names used to


city , population Identifiers
refer to the variables

Data Types in Python


In Python, data types represent the kind of value a variable holds. Python is
dynamically typed, which means you don’t need to declare data types explicitly
— they are determined at runtime.

1. Numeric Types

Type Description Example


int Integer numbers 10 , -5 , 0

Decimal (floating-point)
float 3.14 , -0.01
numbers
complex Complex numbers 2 + 3j

# Integer
int_num = 10
print("Integer:", int_num, "| Type:", type(int_num))
# Float
float_num = 3.14
print("Float:", float_num, "| Type:", type(float_num))
# Complex
complex_num = 2 + 3j
print("Complex:", complex_num, "| Type:", type(complex_num))

2. Text Type
Type Description Example
str A string of characters "hello"

Python 7
text = "hello"
print("String:", text, "| Type:", type(text))

3. Boolean Type
Type Description Example
bool Logical values True , False

is_true = True
is_false = False
print("Boolean True:", is_true, "| Type:", type(is_true))
print("Boolean False:", is_false, "| Type:", type(is_false))

4. Sequence Types

Type Description Example


list Ordered, mutable collection [1, 2, 3]

Ordered, immutable
tuple (1, 2, 3)
collection

Sequence of numbers (used


range range(1, 10)
in loops)

# List
my_list = [1, 2, 3]
print("List:", my_list, "| Type:", type(my_list))
# Tuple
my_tuple = (1, 2, 3)
print("Tuple:", my_tuple, "| Type:", type(my_tuple))
# Range
my_range = range(1, 5)
print("Range:", list(my_range), "| Type:", type(my_range)) # Converted to list

5. Set Types
Type Description Example

Unordered, mutable
set {1, 2, 3}
collection of unique values
frozenset Immutable version of a set frozenset([1, 2, 3])

Python 8
# Set
my_set = {1, 2, 3}
print("Set:", my_set, "| Type:", type(my_set))
# FrozenSet
my_frozenset = frozenset([1, 2, 3])
print("FrozenSet:", my_frozenset, "| Type:", type(my_frozenset))

6. Mapping Type
Type Description Example
dict Collection of key-value pairs {"name": "Alice", "age": 25}

# Dictionary
my_dict = {"name": "Alice", "age": 25}
print("Dictionary:", my_dict, "| Type:", type(my_dict))

7. None Type
Type Description Example

Represents absence of a
NoneType None
value

# None
nothing = None
print("NoneType:", nothing, "| Type:", type(nothing))

How to Check a Data Type?

x = 10
print(type(x)) # Output: <class 'int'>

Operators in Python
An operator is a symbol or keyword that performs an operation on one or more
operands (values or variables). Operators are essential for performing
calculations, comparisons, and logical operations in Python.

Types of Operators:
Category Description

1. Arithmetic Operators Perform mathematical calculations

Python 9
2. Relational (Comparison) Operators Compare values

3. Assignment Operators Assign values to variables

4. Logical Operators Perform logical operations (AND, OR, NOT)

5. Bitwise Operators Operate at the binary (bit) level

6. Identity Operators Compare object identities

Check membership in sequences like list,


7. Membership Operators
str

1. Arithmetic Operators
Operator Meaning Example Output
+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/2 2.5

// Floor Division 5 // 2 2

% Modulus 5%2 1

** Exponentiation 2 ** 3 8

# Addition
print("5 + 3 =", 5 + 3) # Output: 8
# Subtraction
print("5 - 3 =", 5 - 3) # Output: 2
# Multiplication
print("5 * 3 =", 5 * 3) # Output: 15
# Division (returns float)
print("5 / 2 =", 5 / 2) # Output: 2.5
# Floor Division (returns integer part)
print("5 // 2 =", 5 // 2) # Output: 2
# Modulus (returns remainder)
print("5 % 2 =", 5 % 2) # Output: 1
# Exponentiation (power)
print("2 ** 3 =", 2 ** 3) # Output: 8

2. Relational (Comparison) Operators

Operator Meaning Example Output


== Equal to 5 == 5 True

Python 10
!= Not equal to 5 != 3 True

> Greater than 5>3 True

< Less than 5<3 False

Greater than or
>= 5 >= 5 True
equal
<= Less than or equal 3 <= 5 True

print("5 == 5:", 5 == 5) # True


print("5 != 3:", 5 != 3) # True
print("5 > 3:", 5 > 3) # True
print("5 < 3:", 5 < 3) # False
print("5 >= 5:", 5 >= 5) # True
print("3 <= 5:", 3 <= 5) # True

3. Assignment Operators
Assignment operators are used to assign values to variables. Python supports
several types of assignment operators.

Operator Meaning Example Equivalent to


= Assign x=5 —
+= Add and assign x += 2 x=x+2

-= Subtract and assign x -= 2 x=x-2

*= Multiply and assign x *= 2 x=x*2

/= Divide and assign x /= 2 x=x/2

Floor divide and


//= x //= 2 x = x // 2
assign
%= Modulus and assign x %= 2 x=x%2

**= Power and assign x **= 2 x = x ** 2

x=5
print("Initial x:", x)
x += 2
print("x += 2:", x) # 7
x -= 2
print("x -= 2:", x) # 5
x *= 2
print("x *= 2:", x) # 10
x /= 2
print("x /= 2:", x) # 5.0

Python 11
x=5
x //= 2
print("x //= 2:", x) # 2
x=5
x %= 2
print("x %= 2:", x) # 1
x=2
x **= 3
print("x **= 3:", x) # 8

4. Logical Operators
Logical operators are used to combine conditional (Boolean) statements.

Operator Meaning Example Output


and True if both are True True and False False

True if at least one is


or True or False True
True
not Inverts the result not True False

print("True and False:", True and False) # False


print("True or False:", True or False) # True
print("not True:", not True) # False

5. Bitwise Operators
Bitwise operators operate on the binary representation of integers.

Operator Meaning Example Output (Binary)


& Bitwise AND 5&3 1 (0101 & 0011)

| Bitwise OR 5|3 7
^ Bitwise XOR 5^3 6

<< Left Shift 5 << 1 10

>> Right Shift 5 >> 1 2

print("5 & 3:", 5 & 3) # 1 (0101 & 0011)


print("5 | 3:", 5 | 3) # 7 (0101 | 0011)
print("5 ^ 3:", 5 ^ 3) # 6 (0101 ^ 0011)
print("5 << 1:", 5 << 1) # 10 (binary 1010)
print("5 >> 1:", 5 >> 1) # 2 (binary 0010)

Python 12
6. Identity Operators
Operator Meaning Example Output

True if both refer to


is x is y True/False
same object

True if not same


is not x is not y True/False
object

a = [1, 2]
b=a
c = [1, 2]

print("a is b:", a is b) # True (same object)


print("a is c:", a is c) # False (same content, different objects)
print("a is not c:", a is not c) # True

7. Membership Operators
Operator Meaning Example Output

True if value exists


in 'a' in 'apple' True
in sequence

True if value does


not in 'z' not in 'apple' True
not exist

print("'a' in 'apple':", 'a' in 'apple') # True


print("'z' not in 'apple':", 'z' not in 'apple')# True

Operator Precedence in Python


Operator precedence determines the order in which operators are evaluated in
an expression. Operators with higher precedence are evaluated before
operators with lower precedence.

Precedence Level Operator Description

Parentheses – overrides
1 (Highest) ()
precedence

2 ** Exponentiation

Unary plus, minus, bitwise


3 +x , -x , ~x
NOT

Multiplication, division, floor


4 * , / , // , %
division, modulus

Python 13
5 +, - Addition, subtraction

6 << , >> Bitwise shift operators

7 & Bitwise AND

8 ^ Bitwise XOR

9 ` `

10 == , != , > , < , >= , <= Comparison operators

11 not Logical NOT

12 and Logical AND

13 or Logical OR

14 if ... else Conditional expressions

15 = , += , -= , *= , etc. Assignment operators

16 (Lowest) is , is not , in , not in Identity & Membership

Comments in Python
Comments in Python are used to explain code, make it readable, and help
others understand the logic. Comments are ignored by the Python interpreter
during execution.

Types of Comments in Python

1. Single-line Comments
Start with a hash symbol: #

Everything after # on that line is treated as a comment

Example:

# This is a single-line comment


x = 10 # Assign 10 to x

2. Multi-line Comments
Python doesn't have a specific multi-line comment syntax like other languages.
But you can use:

Multiple # lines

Triple quotes ''' ... ''' or """ ... """ (as a workaround)

Example (using multiple # lines):

Python 14
# This is a multi-line comment
# describing the code below
x=x+1

Example (using triple quotes):

"""
This is also treated as a
multi-line comment, although it's
technically a multi-line string not assigned to any variable.
"""
print("Hello")

Why Use Comments?


Purpose Description

Code explanation Helps explain the logic or purpose of code

Debugging Helps to temporarily disable parts of code

Documentation Important for maintaining or collaborating

Improves clarity for self or other


Readability
programmers

Best Practices
Use comments to explain why, not what the code is doing

Keep them concise and relevant

Update comments if the code changes

Avoid obvious or redundant comments


Type Conversions in Python
Type conversion refers to changing the data type of a value or variable from
one type to another.

Python provides both:

1. Implicit Type Conversion (Automatic)

2. Explicit Type Conversion (Manual)

1. Implicit Type Conversion


Python automatically converts one data type to another during operations when
needed.

Python 15
a = 10 # int
b = 2.5 # float
c = a + b # int + float → float
print(c) # Output: 12.5
print(type(c)) # <class 'float'>

Python promotes smaller data types to larger ones to avoid


data loss.

2. Explicit Type Conversion


You manually convert data types using type casting functions.

Common Type Conversion Functions:


Function Description Example
int() Converts to integer int(3.6) → 3

float() Converts to float float(2) → 2.0

str() Converts to string str(25) → '25'

bool() Converts to boolean bool(0) → False

list() Converts to list list("abc") → ['a', 'b', 'c']

tuple() Converts to tuple tuple([1, 2]) → (1, 2)

x=5
y = "10"
z = int(y) + x # Convert string to int before adding
print(z) # Output: 15

Invalid Conversion Example:

int("abc") # Error: Cannot convert letters to integer

Summary:

Conversion Type Handled By Example

Implicit Python (auto) 3 + 4.5 → 7.5

Explicit Programmer str(123) → "123"

Python Keywords

Python 16
Keywords are reserved words in Python. They have special meaning and
cannot be used as variable names, function names, or identifiers.
They are the core building blocks of Python syntax and structure.

Keyword Description
False Boolean value false
True Boolean value true
None Represents absence of value
and Logical AND
or Logical OR
not Logical NOT
if Conditional statement
elif Else if condition
else Alternative condition
for Loop through a sequence
while Loop as long as condition is true
break Exit the loop
continue Skip rest of current loop iteration
pass Do nothing (empty block)
in Check membership in a sequence
is Identity comparison
def Define a function
return Return value from function
lambda Anonymous function
class Define a class
try Start exception handling
except Handle exceptions
finally Execute block regardless of exception
raise Raise an exception
import Import a module
from Import specific parts of a module
as Rename module during import
global Declare a global variable
nonlocal Declare a non-local variable
assert For debugging (checks expression)
del Delete a variable or item

Python 17
yield Return from generator function
with Context manager (file handling)
async Declare asynchronous function
await Await result of async function

How to See Keywords in Python?


You can list all keywords using this:

import keyword
print(keyword.kwlist)

Python Built in Functions

Python provides a wide range of


built-in functions that can be used directly without importing any module.
These functions simplify many common tasks like type conversion, data
processing, mathematical calculations, and more.

Function Description
abs() Returns the absolute value of a number

Returns True if all items in an iterable are


all()
True

Returns True if any item in an iterable is


any()
True

Returns a readable version of an object


ascii()
(non-ASCII characters are escaped)
bin() Converts an integer to a binary string
bool() Returns the boolean value of an object
bytearray() Returns a byte array
bytes() Returns a bytes object
callable() Checks if an object is callable
chr() Returns a character from a Unicode code
classmethod() Converts a method to a class method
compile() Compiles source code to a code object
complex() Returns a complex number
delattr() Deletes an attribute from an object
dict() Creates a dictionary

Python 18
Returns list of attributes and methods of an
dir()
object

Returns quotient and remainder of division


divmod()
as a tuple

Returns an enumerate object with index-


enumerate()
value pairs
eval() Evaluates a string as a Python expression
exec() Executes Python code dynamically
filter() Filters items from an iterable
float() Converts to floating-point number
format() Formats a value
frozenset() Returns an immutable set
getattr() Gets the value of an object's attribute

Returns a dictionary of current global


globals()
symbol table
hasattr() Checks if an object has an attribute
hash() Returns the hash value of an object
help() Displays the built-in help system
hex() Converts an integer to a hexadecimal string

Returns the identity (memory address) of


id()
an object
input() Takes user input (returns string)
int() Converts to integer
isinstance() Checks if an object is an instance of a class

Checks if a class is a subclass of another


issubclass()
class
iter() Returns an iterator object
len() Returns the length of an object
list() Converts to a list
locals() Returns a dictionary of local symbol table
map() Applies a function to all items in an iterable
max() Returns the largest item
memoryview() Returns a memory view object
min() Returns the smallest item
next() Returns the next item from an iterator
object() Returns a base object

Python 19
oct() Converts an integer to an octal string
open() Opens a file
ord() Returns Unicode code of a character
pow() Returns the power of a number ( x**y )
print() Prints to the console
property() Gets, sets, or deletes a property

Returns a range object (sequence of


range()
numbers)

Returns the official string representation of


repr()
an object
reversed() Returns a reversed iterator
round() Rounds a number
set() Creates a new set
setattr() Sets an attribute of an object
slice() Returns a slice object
sorted() Returns a sorted list from iterable
staticmethod() Converts a method to a static method
str() Converts to string
sum() Returns the sum of iterable elements
super() Refers to the parent class
tuple() Converts to tuple
type() Returns the data type of an object
vars() Returns the __dict__ attribute of an object
zip() Combines multiple iterables into one

Input and Output in Python

The
input() function is used to take user input

name = input("Enter your name: ")


print("Hello", name)

Example Output:

Enter your name: Sai


Hello Sai

Python 20
num = int(input("Enter a number: "))
print("Your number + 5 is:", num + 5)

print() function is used to display information to the user.

print("Python is fun!")

Example Output:

Python is fun!
You can print multiple items using commas:

name = "Vivek"
age = 21
print("Name:", name, "Age:", age)

Example Programs
1. Sum of Two Numbers

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
print("Sum:", a + b)

2. Convert Celsius to Fahrenheit

celsius = float(input("Enter temperature in Celsius: "))


fahrenheit = (celsius * 9/5) + 32
print("Fahrenheit:", fahrenheit)

3. Find Area of a Circle

radius = float(input("Enter radius of the circle: "))


area = 3.14159 * radius * radius
print("Area of the circle:", area)

4. Swap Two Numbers

x = int(input("Enter first number: "))


y = int(input("Enter second number: "))
x, y = y, x

Python 21
print("After swapping:")
print("x =", x)
print("y =", y)

5. Print Data Types of Different Values

print("Type of 10:", type(10))


print("Type of 3.14:", type(3.14))
print("Type of 'hello':", type("hello"))
print("Type of True:", type(True))

6. Convert Seconds to Hours and Minutes

seconds = int(input("Enter total seconds: "))


hours = seconds // 3600
minutes = (seconds % 3600) // 60
remaining_seconds = seconds % 60
print(f"{hours}h {minutes}m {remaining_seconds}s")

7. BMI Calculator

weight = float(input("Enter weight in kg: "))


height = float(input("Enter height in meters: "))
bmi = weight / (height ** 2)
print("BMI:", round(bmi, 2))

8. Simple Interest Calculator

p = float(input("Enter Principal: "))


r = float(input("Enter Rate of interest: "))
t = float(input("Enter Time in years: "))
si = (p * r * t) / 100
print("Simple Interest:", si)

9. Check Whether a Number is Even or Odd

n = int(input("Enter a number: "))


if n % 2 == 0:
print("Even")

Python 22
else:
print("Odd")

10. Compute Age from Year of Birth

birth_year = int(input("Enter your birth year: "))


current_year = 2025
age = current_year - birth_year
print("Your age is:", age)

11. Currency Converter (INR to USD and EUR)

inr = float(input("Enter amount in INR: "))


usd = round(inr / 83, 2)
eur = round(inr / 90, 2)
print("USD:", usd)
print("EUR:", eur)

12. Total and Average Marks of 5 Subjects

marks = []
for i in range(5):
marks.append(float(input(f"Enter mark {i+1}: ")))
total = sum(marks)
average = total / 5
print("Total:", total)
print("Average:", average)

13. Evaluate Quadratic Equation ax² + bx + c

a = int(input("Enter a: "))
b = int(input("Enter b: "))
c = int(input("Enter c: "))
x = int(input("Enter value of x: "))
value = a * x**2 + b * x + c
print("Result:", value)

Conditional Statements
Theory

Python 23
Conditional statements help control the flow of a program based on certain
conditions. They allow a program to make decisions.
Here are the main types of conditional statements in Python:

1. if Statement
Executes a block of code if the condition is True.

if condition:
# code block

2. if-else Statement
Executes one block if condition is True, another if False.

if condition:
# if block
else:
# else block

3. if-elif-else Ladder
Used to test multiple conditions in sequence.

if condition1:
# block1
elif condition2:
# block2
else:
# else block

4. Nested if Statements
if or if-else blocks inside another if or else block.

if condition1:
if condition2:
# inner block
else:
# inner else
else:
# outer else

Python 24
5. Short-hand if
Single-line if statement (for simple conditions).

if condition: print("Statement")

6. Short-hand if-else (Ternary Operator)


Single-line if-else assignment.

x = "Even" if number % 2 == 0 else "Odd"

7. match-case Statement (Python 3.10+)


Used like switch-case in other languages.

match variable:
case value1:
# block1
case value2:
# block2
case _:
# default block

Programs
1. Check if number is Positive / Negative / Zero

num = float(input("Enter a number: "))


if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")

2. Check Voting Eligibility

age = int(input("Enter your age: "))


if age >= 18:
print("Eligible to vote.")

Python 25
else:
print("Not eligible to vote.")

3. Find Greatest of Two Numbers

a = int(input("Enter first number: "))


b = int(input("Enter second number: "))
if a > b:
print(f"{a} is greater.")
elif a < b:
print(f"{b} is greater.")
else:
print("Both are equal.")

4. Grade Calculator

marks = int(input("Enter marks: "))


if marks >= 90:
print("Grade: A")
elif marks >= 75:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
elif marks >= 40:
print("Grade: D")
else:
print("Grade: F (Fail)")

5. Leap Year Checker

year = int(input("Enter a year: "))


if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
print("Leap year")
else:
print("Not a leap year")

6. Largest Among 3 Numbers

a = int(input("A: "))
b = int(input("B: "))

Python 26
c = int(input("C: "))
if a >= b and a >= c:
print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)

7. Categorize BMI Result

weight = float(input("Weight (kg): "))


height = float(input("Height (m): "))
bmi = weight / (height ** 2)

if bmi < 18.5:


print("Underweight")
elif bmi < 24.9:
print("Normal weight")
elif bmi < 29.9:
print("Overweight")
else:
print("Obese")

8. Age Group Classifier

age = int(input("Enter your age: "))


if age <= 12:
print("Child")
elif age <= 19:
print("Teenager")
elif age <= 59:
print("Adult")
else:
print("Senior Citizen")

9. Triangle Type Checker

a = int(input("Side A: "))
b = int(input("Side B: "))
c = int(input("Side C: "))

Python 27
if a == b == c:
print("Equilateral Triangle")
elif a == b or b == c or a == c:
print("Isosceles Triangle")
else:
print("Scalene Triangle")

10. Electricity Bill Calculator

units = float(input("Enter units consumed: "))


if units <= 100:
amount = units * 3
elif units <= 200:
amount = 100 * 3 + (units - 100) * 5
else:
amount = 100 * 3 + 100 * 5 + (units - 200) * 8

print("Bill Amount: ₹", amount)

11. Student Performance Analyzer

avg = float(input("Enter average marks: "))


if avg >= 90:
print("Outstanding")
elif avg >= 75:
print("Excellent")
elif avg >= 60:
print("Good")
elif avg >= 40:
print("Average")
else:
print("Fail")

12. Income Tax Calculator

income = float(input("Enter annual income: ₹"))

if income <= 250000:


tax = 0
elif income <= 500000:
tax = 0.05 * (income - 250000)

Python 28
elif income <= 1000000:
tax = 12500 + 0.2 * (income - 500000)
else:
tax = 112500 + 0.3 * (income - 1000000)

print("Tax Payable: ₹", tax)

13. Admission Eligibility Checker

math = int(input("Math Marks: "))


phy = int(input("Physics Marks: "))
chem = int(input("Chemistry Marks: "))

total = math + phy + chem

if math >= 60 and phy >= 50 and chem >= 40 and total >= 200:
print("Eligible for admission")
else:
print("Not eligible")

14. Time-Based Greeting Generator

hour = int(input("Enter current hour (0-23): "))


if 5 <= hour < 12:
print("Good Morning!")
elif 12 <= hour < 17:
print("Good Afternoon!")
elif 17 <= hour < 21:
print("Good Evening!")
else:
print("Good Night!")

15. Number Classification (Even/Odd/Prime)

num = int(input("Enter a number: "))

# Even or Odd
if num % 2 == 0:
print("Even")
else:
print("Odd")

Python 29
# Prime Check
if num > 1:
for i in range(2, num):
if num % i == 0:
print("Not Prime")
break
else:
print("Prime")
else:
print("Not Prime")

Looping Statements
Theory
Definition:
A loop is a control structure in programming that allows for the repeated
execution of a block of code as long as a specified condition remains true. Loops
facilitate automation of repetitive tasks and help reduce code redundancy,
thereby improving efficiency and readability.

Classification of Loops
Loops are broadly classified into two types based on when the condition is
evaluated:

1. Entry-Controlled Loops
In entry-controlled loops, the condition is evaluated before the execution of the
loop body.

Examples:

for loop

while loop

2. Exit-Controlled Loops
In exit-controlled loops, the condition is evaluated after the execution of the loop
body.

Example:

i=0
while True:

Python 30
print(i, end=" ")
i += 1
if i >= 5:
break

A. for Loop (Entry-Controlled)


Used when the number of iterations is predetermined or finite.

Syntax in Python: for variable in sequence:

Example:

for i in range(5):
print(i, end=" ")

Output:

01234

B. while Loop (Entry-Controlled)


Used when the number of iterations is not known in advance and depends on a
condition being met.

Syntax in Python:

while condition:
# loop body

Example:

i=0
while i < 5:
print(i, end=" ")
i += 1

Output:

01234

C. Nested Loops
A nested loop is a loop placed within another loop. The inner loop is executed
completely for each iteration of the outer loop.

Python 31
Example in Python:

for i in range(2):
for j in range(3):
print(f"i={i}, j={j}")

Comparison Table: Loop Types

Feature for Loop while Loop

Control Type Entry-controlled Entry-controlled

Condition Evaluation Before entering the loop Before entering the loop

Use Case Iterating over known range Based on dynamic condition

Syntax Structure for init; cond; update while (condition)

Supported in Python Yes Yes

Programs
1. Print 1 to 10

for i in range(1, 11):


print(i, end=' ')

2. Sum of N numbers

n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total)

3. Print even numbers from 1 to 100

for i in range(2, 101, 2):


print(i, end=' ')

4. Print multiplication table

num = int(input("Enter number: "))


for i in range(1, 11):

Python 32
print(f"{num} x {i} = {num * i}")

5. Factorial of a number

n = int(input("Enter number: "))


fact = 1
for i in range(1, n + 1):
fact *= i
print("Factorial:", fact)

6. Count digits in a number

n = int(input("Enter number: "))


count = 0
while n > 0:
n //= 10
count += 1
print("Digit count:", count)

7. Reverse a number

n = int(input("Enter number: "))


rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print("Reversed:", rev)

8. Check palindrome number

n = int(input("Enter number: "))


original = n
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print("Palindrome" if rev == original else "Not a palindrome")

9. Sum of digits

Python 33
n= int(input("Enter number: "))
total = 0
while n > 0:
total += n % 10
n //= 10
print("Sum of digits:", total)

10. Sum of even digits only

n = int(input("Enter number: "))


total = 0
while n > 0:
digit = n % 10
if digit % 2 == 0:
total += digit
n //= 10
print("Sum of even digits:", total)

11. Armstrong number checker

n = int(input("Enter number: "))


temp = n
order = len(str(n))
sum = 0
while temp > 0:
digit = temp % 10
sum += digit ** order
temp //= 10
print("Armstrong number" if sum == n else "Not an Armstrong number")

12. Fibonacci series (first N terms)

n = int(input("Enter N: "))
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b

13. Prime numbers between 1 to N

Python 34
n = int(input("Enter N: "))
for num in range(2, n + 1):
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
break
else:
print(num, end=' ')

14. Number pattern printing (right triangle)

rows = int(input("Enter number of rows: "))


for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=' ')
print()

15. Count vowels and consonants

text = input("Enter a string: ").lower()


vowels = "aeiou"
vowel_count = 0
consonant_count = 0

for char in text:


if char.isalpha():
if char in vowels:
vowel_count += 1
else:
consonant_count += 1

print("Vowels:", vowel_count)
print("Consonants:", consonant_count)File handling is an important part of a
ny web application.

File Handling
1. Introduction

Python 35
Python provides built-in functions to perform file operations such as reading,
writing, and deleting files. The most commonly used function for file handling is
open() .

Syntax:

file = open(filename, mode)

filename : Name (and optionally, path) of the file.

mode : Mode in which the file is to be opened.

2. File Modes in Python


Mode Description

Read – Default mode. Opens a file for


'r'
reading. Error if file does not exist.

Append – Opens a file for appending. Creates


'a'
the file if it does not exist.

Write – Opens a file for writing. Creates the


'w' file if it does not exist and overwrites existing
content.

Create – Creates a new file. Returns an error


'x'
if the file already exists.

't' Text mode – Default mode.

Binary mode – Used for binary files like


'b'
images or PDFs.

3. Opening and Reading Files


Example 1: Open and read entire content

f = open("example.txt", "r")
print(f.read())
f.close()

Example 2: Read first five characters

f = open("example.txt", "r")
print(f.read(5))
f.close()

Python 36
Example 3: Read one line

f = open("example.txt", "r")
print(f.readline())
f.close()

Example 4: Read multiple lines using loop

f = open("example.txt", "r")
for line in f:
print(line)
f.close()

4. Using with Statement


The with statement simplifies file handling and ensures that files are properly closed
after use.

Example:

with open("example.txt", "r") as f:


print(f.read())

This approach is preferred as it automatically handles closing the file.

5. Writing to a File
Example 5: Appending to a file

with open("example.txt", "a") as f:


f.write("This is additional content.\n")

Example 6: Overwriting content in a file

with open("example.txt", "w") as f:


f.write("This content replaces the previous content.")

Note: Using 'w' will overwrite all existing content.

6. Creating New Files

Python 37
Example 7: Create a new file using 'x'

f = open("newfile.txt", "x")

Note: Raises an error if the file already exists.

Example 8: Creating file using 'w' or 'a'

f = open("log.txt", "w") # Creates if not exists

7. Checking if a File Exists


Example 9:

import os
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File does not exist.")

8. Deleting Files
To delete files, the os module must be imported.

Example 10: Delete a file

import os
os.remove("example.txt")

Example 11: Delete file after checking existence

import os
if os.path.exists("example.txt"):
os.remove("example.txt")
else:
print("The file does not exist.")

9. Deleting Folders
Only empty folders can be removed using os.rmdir() .

Python 38
Example 12:

import os
os.rmdir("myfolder")

10. Summary of Key Functions


Function Description
open() Opens a file.
read() Reads the file content.
readline() Reads one line from the file.
write() Writes to the file.
close() Closes the file.
os.remove() Deletes a file.
os.rmdir() Deletes an empty folder.
os.path.exists() Checks whether a file or folder exists.

Python Exception Handling


1. Introduction
Errors detected during execution are called exceptions. In Python, exceptions can
be handled using the try-except statement. This prevents the program from
terminating unexpectedly and allows for custom error handling.

2. Syntax and Structure

try:
# Code block to test
except:
# Code block to handle error
else:
# Code to execute if no error occurred
finally:
# Code to execute regardless of an error

3. Basic Try-Except Example

try:
print(x)

Python 39
except:
print("An exception occurred")

In the above example, since x is not defined, an exception is raised and handled by
the except block.

4. Without Try-Except
If exception handling is not used:

print(x) # Raises NameError: name 'x' is not defined

This will cause the program to stop execution and display an error.

5. Handling Multiple Exceptions


You can use multiple except blocks to handle different types of exceptions.

Example:

try:
print(x)
except NameError:
print("Variable x is not defined")
except:
print("An unknown error occurred")

Here, NameError is specifically handled. Other unexpected errors fall under the
general except block.

6. Using the Else Clause


The else block is executed only if no exception is raised in the try block.

Example:

try:
print("Hello")
except:
print("An error occurred")
else:
print("No errors occurred")

Python 40
7. Using the Finally Clause
The finally block is always executed, regardless of whether an exception occurred
or not. It is typically used to release external resources, such as closing files or
network connections.

Example:

try:
print(x)
except:
print("An error occurred")
finally:
print("Execution completed")

8. Nested Try-Except-Finally
A try block can be nested inside another try block.

Example:

try:
f = open("demofile.txt")
try:
f.write("Lorum Ipsum")
except:
print("An error occurred while writing to the file")
finally:
f.close()
except:
print("An error occurred while opening the file")

In this example, even if an error occurs during writing, the file is closed properly
using the finally block.

9. Raising Exceptions Manually


You can raise exceptions intentionally using the raise keyword.

Example 1: Raise a general exception

x = -1
if x < 0:

Python 41
raise Exception("Sorry, no numbers below zero are allowed")

Example 2: Raise a specific exception

x = "hello"
if not isinstance(x, int):
raise TypeError("Only integers are allowed")

The raise statement is useful for enforcing constraints and validating data types.

10. Summary of Keywords


Keyword Description
try Tests a block of code for errors
except Handles the error
else Executes code if no error occurred
finally Executes code regardless of an error
raise Manually triggers an exception

Strings
Introduction
A string in Python is a sequence of characters enclosed within single ( ' ) or
double ( " ) quotation marks.

Example:

print("Hello")
print('Hello')

Both lines produce the same output.

1. Characteristics of Strings
Indexing: Characters in a string are accessed using an index.

Indexing starts from 0 (left to right).

Negative indexing starts from 1 (right to left).

Immutability: Strings are immutable, meaning their contents cannot be


changed after they are created.

Input Function: The input() function in Python always returns data as a string.

Python 42
2. Quotes Inside Strings
Python allows the use of quotes inside a string as long as they are different from
the enclosing quotes.

Examples:

print("It's alright")
print("He is called 'Johnny'")
print('He is called "Johnny"')

3. Assigning Strings to Variables


Strings can be stored in variables using the assignment operator = .

Example:

a = "Hello"
print(a)

4. Multiline Strings
To assign a multiline string, triple quotes can be used—either triple double-
quotes ( """ ) or triple single-quotes ( ''' ).

Example 1: Using triple double quotes

a = """Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)

Example 2: Using triple single quotes

a = '''Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)

5. Summary

Python 43
Concept Description

String Delimiters 'single' or "double" quotes

Indexing Starts from 0 (positive) or -1 (negative)

Mutability Strings are immutable

Multiline Strings Use ''' or """ for multiline content

Quotes in Quotes Mix single and double quotes appropriately

input() Function Returns input as a string by default

Fundamental String Operations in Python


Python supports several operations that can be performed on strings. The five
basic operations are:

1. Indexing

2. Slicing

3. Concatenation

4. Repetition

5. Membership
Indexing
Indexing is used to access individual characters in a string by referring to their
position (index) in the string.

Types of Indexing
Positive Indexing: Starts from 0 and goes from left to right.

Negative Indexing: Starts from 1 and goes from right to left.

Example:

a = "HELLO"
print(a[0]) # Output: H (first character)
print(a[-1]) # Output: O (last character)

Program: Accessing Characters Using Indexing


This program:

1. Accepts a string input from the user.

2. Displays the full string.

3. Displays the second character using positive indexing.

Python 44
4. Displays the second character from the end using negative indexing.

python
CopyEdit
# Accept input from the user
user_input = input("Enter a string: ")

# Display the entire string


print("Full string:", user_input)

# Display the second character (positive indexing)


if len(user_input) >= 2:
print("Second character from the beginning:", user_input[1])
else:
print("The string is too short to have a second character from the beginnin
g.")

# Display the second character from the end (negative indexing)


if len(user_input) >= 2:
print("Second character from the end:", user_input[-2])
else:
print("The string is too short to have a second character from the end.")

Sample Input and Output


Input:

Enter a string: PYTHON

Output:

Full string: PYTHON


Second character from the beginning: Y
Second character from the end: O

String Slicing in Python


Slicing allows you to extract a portion (substring) of a string by specifying a
range of indices.

Syntax:

Python 45
string[start_index:end_index]

The start_index is inclusive (the slice starts from this index).

The end_index is exclusive (the slice goes up to but does not include this
index).

Example

b = "Hello, World!"
print(b[2:5])

Example 1: From starting index to end

print(a[0:]) # Output: Python

Starts at index 0 and slices till the end.

Example 2: From beginning to a specific ending index

print(a[:6]) # Output: Python

Slicing from the beginning to index 6 (exclusive), i.e., indices 0 through 5.

Example 3: Specifying both start and end indexes

print(a[0:4]) # Output: Pyth

Returns the substring from index 0 to 3.

Example 4: Using step for traversal

print(a[::1]) # Output: Python → Regular forward traversal


print(a[::-1]) # Output: nohtyP → Full reverse of the string

Example 5: Using negative step value

print(a[-1::-3]) # Output: nt

Starts at index -1 (last character), moves in reverse with steps of 3: 'n' , 't' .

Python 46
print(a[4:1:-1]) # Output: oht

Starts at index 4 ( 'o' ), stops before index 1 ( 'y' ), moving in reverse.

print(a[2:5:-1]) # Output: ''

This results in an empty string because the slicing direction and index order
conflict.
String Concatenation
Concatenation refers to the process of combining two or more strings into a
single string. In Python, this is accomplished using the + operator.

1. Basic Concatenation

Example:

a = "Hello"
b = "World"
c=a+b
print(c)

Output:

HelloWorld

In this example, the strings "Hello" and "World" are joined without any space in
between.

2. Concatenation with a Space


To include a space between the strings, simply concatenate a space character ( "
" ) between them.

Example:

a = "Hello"
b = "World"
c=a+""+b
print(c)

Python 47
Output:

Hello World

Here, a space is explicitly added between the two strings during concatenation.

3. Summary
Operation Description Output
a+b Concatenates without space HelloWorld

Concatenates with space


a+""+b Hello World
between

String Repetition
1. Introduction
Repetition is a string operation in Python that allows a string to be repeated a
specified number of times. This is done using the multiplication operator ( * ).

Syntax:

repeated_string = string * n

string : the string to be repeated

n: a non-negative integer specifying how many times the string should be


repeated

2. Example: Basic Repetition

a = "Hello"
print(a * 3)

Output:

HelloHelloHello

Here, the string "Hello" is repeated three times consecutively.

3. Example: Repetition with Space

word = "Python "


print(word * 4)

Python 48
Output:

Python Python Python Python

Note: The space is part of the original string and is repeated along with it.

4. Example: Using Repetition for Pattern Generation

print("*" * 5)

Output:

*****

String repetition can be used to generate text-based patterns.

5. Invalid Use Case


If a string is multiplied by a negative number or a non-integer, Python returns an
empty string or raises a TypeError .

Example:

print("Hi" * -2) # Output: ''


print("Hi" * 2.5) # Raises TypeError

6. Summary

Operation Description Example Output


s*3 Repeats string s 3 times "Hi" * 3 HiHiHi

s*0 Returns empty string "Hello" * 0 ""

s * -1 Returns empty string "Test" * -1 ""

String Membership Operations


Membership operators in Python are used to test whether a substring exists
within another string. Python provides two operators for this purpose:

in – Returns True if a specified value exists in a string.

not in – Returns True if a specified value does not exist in a string.

These operators are commonly used in conditional statements, filtering, and


validation tasks.

Python 49
2. Syntax

substring in string # Returns True or False


substring not in string # Returns True or False

3. Examples

Example 1: Using in

text = "Python Programming"


print("Python" in text)

Output:

True

The substring "Python" is present in "Python Programming" .

Example 2: Using not in

text = "Python Programming"


print("Java" not in text)

Output:

True

The substring "Java" is not present in the string, so the result is True .

Example 3: Conditional Statement with Membership

email = "[email protected]"

if "@" in email:
print("Valid email address")
else:
print("Invalid email address")

Output:

Valid email address

Python 50
This is a practical use of in for input validation.

4. Summary

Operation Description Example Result

Checks if substring exists in


substring in string "Py" in "Python" True
the string

substring not in Checks if substring does not "Java" not in


True
string exist "Python"

5. Common Use Cases


Validating user input (e.g., checking for "@" in an email)

Searching within documents or text

Conditional logic in loops or filters


String Formatting
In Python, combining strings and non-string data types (like integers or floats)
directly using the + operator leads to a TypeError .

Incorrect Example:

age = 20
txt = "My name is Vivek I am " + age # This will raise a TypeError
print(txt)

To properly format strings with variables, Python provides several methods. The
most modern and preferred method is the f-string, introduced in Python 3.6.

2. F-Strings (Formatted String Literals)


An f-string is a string literal prefixed with f or F . Expressions inside curly
braces {} are evaluated at runtime and formatted using standard string
conversion rules.

Syntax:

f"some text {expression}"

Example:

age = 20
txt = f"My name is Vivek, I am {age}"

Python 51
print(txt)

Output:

My name is Vivek, I am 20

3. Using Variables in Placeholders


F-strings allow inserting any variable inside {} .

Example:

python
CopyEdit
price = 59
txt = f"The price is {price} dollars"
print(txt)

Output:

The price is 59 dollars

4. Using Modifiers with Placeholders


You can use format specifiers (modifiers) to control how values appear. These
are added after a colon : inside the placeholder.

Example: Two Decimal Places

price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)

Output:

The price is 59.00 dollars

In this case, .2f formats the number as a float with 2 digits after the decimal
point.

5. Performing Operations Inside Placeholders

Python 52
You can also perform calculations or call functions inside placeholders.

Example: Math Operation

txt = f"The total cost is {20 * 59} dollars"


print(txt)

Output:

The total cost is 1180 dollars

6. Summary of F-String Features

Feature Description Example

Basic Variable Inserts variable value f"My name is {name}"

Formatting with Decimal Controls float precision {price:.2f}

Performs operations inside


Expression Evaluation {10 + 5}
{}

Calling Functions Evaluates functions inline {len(name)}

String Methods
Python provides a rich set of built-in string methods that can be used to
manipulate and analyze string data.

Note: All string methods return new strings; they do not modify the original
string (strings are immutable in Python).

1. Case Conversion Methods


Method Description Example Output

Converts the first


capitalize() character to "hello".capitalize() 'Hello'
uppercase

Converts the string


casefold() to lowercase (more "HELLO".casefold() 'hello'
aggressive)

Converts all
lower() characters to "HELLO".lower() 'hello'
lowercase

Converts all
upper() characters to "hello".upper() 'HELLO'
uppercase

Python 53
Method Description Example Output

Capitalizes the first


title() "hello world".title() 'Hello World'
letter of each word

Swaps case of each


swapcase() "HeLLo".swapcase() 'hEllO'
character

2. Search and Match Methods

Method Description Example Output

Returns the first


find() index of a substring "python".find("t") 2
(or -1)

Returns the last


rfind() index of a substring "python".rfind("o") 4
(or -1)

Returns the first


index() index or raises "python".index("t") 2
ValueError

Returns last index


rindex() "python".rindex("o") 4
or raises ValueError

Checks if string
startswith() "python".startswith("py") True
starts with a value

Checks if string
endswith() "python".endswith("on") True
ends with a value

Counts
count() occurrences of a "banana".count("a") 3
substring

3. Modify and Format Strings

Method Description Example Output

Replaces a
replace() substring with "python".replace("py", "my") 'mython'
another

Formats string with


format() "My age is {}".format(25) 'My age is 25'
placeholders

Similar to format() , "


format_map() used with {name}".format_map({'name': 'John'
dictionaries 'John'})

Pads string with


zfill() "7".zfill(3) '007'
leading zeros

Python 54
Method Description Example Output

Centers string
center(n) within a field of "hi".center(6) ' hi '
width n

Left-aligns string
ljust(n) in a field of width "hi".ljust(5) 'hi '
n

Right-aligns string
rjust(n) in a field of width "hi".rjust(5) ' hi'
n

4. Whitespace and Trimming Methods


Method Description Example Output

Removes leading
strip() and trailing " hello ".strip() 'hello'
whitespace

Removes leading
lstrip() " hello".lstrip() 'hello'
(left) whitespace

Removes trailing
rstrip() "hello ".rstrip() 'hello'
(right) whitespace

5. String Testing Methods


These methods return True or False based on string content.

Method Description Example Output

Returns True if all


isalnum() characters are "abc123".isalnum() True
alphanumeric

Returns True if all


isalpha() characters are "abc".isalpha() True
letters

Returns True if all


isdigit() "123".isdigit() True
characters are digits

Returns True if all


isdecimal() characters are "123".isdecimal() True
decimal

Returns True if all


isnumeric() characters are "123".isnumeric() True
numeric

Returns True if all


isascii() "abc".isascii() True
characters are ASCII

Python 55
Method Description Example Output

Returns True if all


islower() characters are "abc".islower() True
lowercase

Returns True if all


isupper() characters are "ABC".isupper() True
uppercase

Returns True if it’s


istitle() "Hello World".istitle() True
title case

Returns True if all


isspace() characters are " ".isspace() True
whitespace

Returns True if the


isidentifier() string is a valid "var1".isidentifier() True
identifier

Returns True if all


isprintable() characters are "Hello!".isprintable() True
printable

6. Splitting and Joining

Method Description Example Output

Splits string by
split() whitespace or a "a b c".split() ['a', 'b', 'c']
delimiter
rsplit() Splits from the right "a,b,c".rsplit(',', 1) ['a,b', 'c']

Splits string at line


splitlines() "a\nb\nc".splitlines() ['a', 'b', 'c']
breaks

Joins elements of
join() an iterable with a '-'.join(['a', 'b', 'c']) 'a-b-c'
separator

7. Encoding and Translation

Method Description Example Output

Encodes the string


encode() using default or "abc".encode() b'abc'
given encoding

Returns translation Used with


maketrans() str.maketrans("a", "b")
mapping table translate()

Translates string
"abc".translate(str.maketrans("a",
translate() using the translation 'xbc'
"x"))
table

Python 56
8. Partitioning and Substring Extraction

Method Description Example Output

Splits string into


('apple', '#',
partition() 3 parts at first "apple#banana".partition("#")
'banana')
match

Splits from the ('apple#banana',


rpartition() "apple#banana#cherry".rpartition("#")
right '#', 'cherry')

Easy Level Problems


1. Count the Length of a String

s = input("Enter a string: ")


print("Length of the string:", len(s))

2. Convert String to Uppercase

s = input("Enter a string: ")


print("Uppercase:", s.upper())

3. Check if a Word is a Palindrome

s = input("Enter a word: ")


if s == s[::-1]:
print("Palindrome")
else:
print("Not a palindrome")

4. Count Vowels in a String

s = input("Enter a string: ")


count = 0
vowels = "aeiouAEIOU"
for ch in s:
if ch in vowels:
count += 1
print("Number of vowels:", count)

5. Reverse a String

Python 57
s = input("Enter a string: ")
print("Reversed string:", s[::-1])

Medium Level Problems


6. Remove Punctuation from String

import string

s = input("Enter a string: ")


no_punct = ""
for ch in s:
if ch not in string.punctuation:
no_punct += ch
print("String without punctuation:", no_punct)

7. Count Frequency of Characters

s = input("Enter a string: ")


freq = {}
for ch in s:
freq[ch] = freq.get(ch, 0) + 1

for key, value in freq.items():


print(f"{key}: {value}")

8. Check Anagram
An anagram is when we rearrange the letters of one word to form another word.
For example, "listen" and "silent" have the same letters, just in a different order

str1 = input("Enter first string: ")


str2 = input("Enter second string: ")

if sorted(str1) == sorted(str2):
print("True")
else:
print("False")

9. Replace Vowels with

Python 58
s = input("Enter a string: ")
vowels = "aeiouAEIOU"
new_str = ""

for ch in s:
if ch in vowels:
new_str += "*"
else:
new_str += ch

print("Modified string:", new_str)

10. Find First Non-Repeating Character

s = input("Enter a string: ")


freq = {}

for ch in s:
freq[ch] = freq.get(ch, 0) + 1

for ch in s:
if freq[ch] == 1:
print("First non-repeating character:", ch)
break
else:
print("No non-repeating character found")

Advanced String
1. Longest Word in a Sentence
Problem:

Write a program that accepts a sentence and finds the longest word.
Input: "Python is a powerful programming language"

Output: "programming"

sentence = input("Enter a sentence: ")


words = sentence.split()
longest = max(words, key=len)
print("Longest word:", longest)

Python 59
2. Check if Two Strings are Rotations of Each Other
Problem:
Check if one string is a rotation of another string.

Input: "abcde" and "deabc"

Output: True

def are_rotations(s1, s2):


return len(s1) == len(s2) and s2 in s1 + s1

s1 = input("Enter first string: ")


s2 = input("Enter second string: ")
print("Are rotations:", are_rotations(s1, s2))

3. Remove All Duplicate Characters from a String


Input: "programming"

Output: "progamin"

s = input("Enter a string: ")


result = ""
for ch in s:
if ch not in result:
result += ch
print("String without duplicates:", result)

4. Check for Pangram


Problem:
A string is a pangram if it contains every letter of the alphabet at least once.

Input: "The quick brown fox jumps over the lazy dog"

Output: True

import string
s = input("Enter a string: ")
alphabet = set(string.ascii_lowercase)
print("Is Pangram:", alphabet.issubset(s.lower()))

Lists
Introduction

Python 60
A list in Python is a built-in data structure used to store multiple items in a single
variable.

Syntax

mylist = ["apple", "banana", "cherry"]

Key Characteristics of Lists

1. Ordered
Items in a list maintain the order in which they are added.

Indexing starts from 0 .

2. Changeable (Mutable)
You can change, add, or remove items after the list is created.

3. Allow Duplicates
Lists can contain duplicate values.

4. Indexing
Elements can be accessed by index using square brackets [] .
Creating a List
Using Square Brackets

fruits = ["apple", "banana", "cherry"]


print(fruits)

Using the list() Constructor

fruits = list(("apple", "banana", "cherry")) # double parentheses


print(fruits)

Example: List with Duplicate Values

sample_list = ["apple", "banana", "cherry", "apple"]


print(sample_list) # Output: ['apple', 'banana', 'cherry', 'apple']

List Methods

Python 61
Python has a set of built-in methods that you can use on lists.

Method Description Example Output

Adds an element at
append() lst.append("apple") ['apple']
the end of the list

Removes all the


clear() elements from the lst.clear() []
list

Returns a shallow ['apple'] (copy of


copy() new_lst = lst.copy()
copy of the list original list)

Returns the number


1 (if one "apple"
count(x) of times x appears lst.count("apple")
exists)
in the list

Adds elements of
lst.extend(["banana", ['apple', 'banana',
extend(iter) an iterable to the
"cherry"]) 'cherry']
end of the list

Returns the index of


index(x) the first occurrence lst.index("banana") 1
of value x

Inserts item x at ['apple', 'kiwi',


insert(i, x) lst.insert(1, "kiwi")
index i 'banana', 'cherry']

Removes and
returns element at 'cherry' (and
pop([i]) lst.pop()
index i (last if not removes it)
given)

Removes the first


['apple', 'kiwi',
remove(x) occurrence of value lst.remove("banana")
'cherry']
x

Reverses the order ['cherry', 'kiwi',


reverse() lst.reverse()
of the list in place 'apple']

Sorts the list in ['apple', 'banana',


sort() lst.sort()
ascending order 'cherry']

Sorts the list in ['cherry', 'banana',


sort(reverse=True) lst.sort(reverse=True)
descending order 'apple']

# Initial list
my_list = [3, 1, 4, 1, 5, 9]

print("Original list:", my_list)

# append(): Adds an element at the end of the list


my_list.append(2)

Python 62
print("After append(2):", my_list)

# clear(): Removes all the elements from the list


temp_list = my_list.copy()
temp_list.clear()
print("After clear() on a copy:", temp_list)

# copy(): Returns a copy of the list


copied_list = my_list.copy()
print("Copied list using copy():", copied_list)

# count(x): Returns the number of elements with the specified value


count_1 = my_list.count(1)
print("Count of 1 in list:", count_1)

# extend(iter): Adds all elements of an iterable (list) to the end


my_list.extend([6, 7])
print("After extend([6, 7]):", my_list)

# index(x): Returns the index of the first element with the specified value
index_5 = my_list.index(5)
print("Index of 5:", index_5)

# insert(i, x): Inserts an element at the specified index


my_list.insert(2, 10)
print("After insert(2, 10):", my_list)

# pop([i]): Removes and returns the element at the given index (last if not sp
ecified)
popped = my_list.pop()
print("After pop():", my_list, "| Popped element:", popped)

popped_at_index = my_list.pop(2)
print("After pop(2):", my_list, "| Popped element at index 2:", popped_at_inde
x)

# remove(x): Removes the first occurrence of a value


my_list.remove(1)
print("After remove(1):", my_list)

# reverse(): Reverses the list in place


my_list.reverse()

Python 63
print("After reverse():", my_list)

# sort(): Sorts the list in ascending order


my_list.sort()
print("After sort():", my_list)

# sort(reverse=True): Sorts the list in descending order


my_list.sort(reverse=True)
print("After sort(reverse=True):", my_list)

Sample Output:

Original list: [3, 1, 4, 1, 5, 9]


After append(2): [3, 1, 4, 1, 5, 9, 2]
After clear() on a copy: []
Copied list using copy(): [3, 1, 4, 1, 5, 9, 2]
Count of 1 in list: 2
After extend([6, 7]): [3, 1, 4, 1, 5, 9, 2, 6, 7]
Index of 5: 4
After insert(2, 10): [3, 1, 10, 4, 1, 5, 9, 2, 6, 7]
After pop(): [3, 1, 10, 4, 1, 5, 9, 2, 6] | Popped element: 7
After pop(2): [3, 1, 4, 1, 5, 9, 2, 6] | Popped element at index 2: 10
After remove(1): [3, 4, 1, 5, 9, 2, 6]
After reverse(): [6, 2, 9, 5, 1, 4, 3]
After sort(): [1, 2, 3, 4, 5, 6, 9]
After sort(reverse=True): [9, 6, 5, 4, 3, 2, 1]

Programs
1. Check if an Element is Present in a List

elements = input("Enter list elements separated by space: ").split()


item = input("Enter the element to search for: ")

if item in elements:
print(f"{item} is present in the list.")
else:
print(f"{item} is not present in the list.")

2. Display Element at Given Index with Error Handling

Python 64
elements = input("Enter list elements separated by space: ").split()
try:
index = int(input("Enter an index: "))
print("List:", elements)
print("Element at index", index, "is:", elements[index])
except IndexError:
print("Error: Index is out of range.")
except ValueError:
print("Error: Invalid index entered."

3. Check if First or Last Element is 3

nums = input("Enter list of integers separated by space: ").split()


nums = [int(n) for n in nums]

if nums and (nums[0] == 3 or nums[-1] == 3):


print(True)
else:
print(False)

4. Repeat and Merge Two Lists

list1 = input("Enter first list (comma-separated): ").split(",")


list2 = input("Enter second list (comma-separated): ").split(",")
repeat = int(input("Enter number of repetitions: "))

list1 *= repeat
list2 *= repeat

merged_list = list1 + list2


print("Merged list:", merged_list)

5. Compare Two Lists for Same Elements

list1 = input("Enter elements of the first list separated by space: ").split()


list2 = input("Enter elements of the second list separated by space: ").split()

if sorted(list1) == sorted(list2):
print("The two lists contain the same elements.")

Python 65
else:
print("The two lists do not contain the same elements.")

A weather monitoring station records daily temperatures. You are given a list of
temperatures (in Celsius) for the past week. Write a program to remove any
duplicate temperature readings and display the unique temperatures in the order
they were recorded.

Input Format:
A single line containing 7 space-separated integers representing temperatures
recorded for each day of the week.
Output Format:

A single line of space-separated integers representing the unique temperature


readings. If the total number of inputs are not equal to 7, print "insufficient
readings".

Constraints:
The input must contain exactly 7 input values.

# Input from the user


temps = input("Enter 7 space-separated temperature readings: ").split()
# Check if exactly 7 values are provided
if len(temps) != 7:
print("insufficient readings")
else:
temps = list(map(int, temps)) # Convert all to integers
unique = []
for t in temps:
if t not in unique:
unique.append(t)
print(' '.join(map(str, unique))) # Convert back to strings for printing

Advanced Programs
You are managing a shopping list for groceries. You are given a
list of items you need to buy. Some items may appear multiple
times due to errors. Write a program to display the unique items
from your shopping list.
Input Format:
A single line containing space-separated strings representing the items in the
shopping list.

Python 66
Output Format:
A single line of space-separated strings representing the unique items to buy.

items = input("Enter shopping list items").split()


# List to hold unique items in original order
unique_items = []
# Eliminate duplicates while preserving order
for item in items:
if item not in unique_items:
unique_items.append(item)
# Output the result using join
print(' '.join(unique_items))

Store tracks its daily sales. You are given a list of integers
representing the sales made each day in the store. Write a
program to find the top 3 highest sales amounts and display
them in descending order. If there are fewer than 3 unique sales
amounts, display all of them.
Input Format:

A single line contains space-separated integers representing the sales made


each day.
Output Format:
Display the top 3 in descending order. If there are fewer than 3 unique amounts,
display all unique sales.

# Read space-separated sales as input and convert to integers


sales = list(map(int, input("Enter daily sales amounts: ").split()))
# Remove duplicates using set, then sort in descending order
unique_sales = sorted(set(sales), reverse=True)
# Slice top 3 or all if fewer
top_sales = unique_sales[:3]
# Print result
print(' '.join(map(str, top_sales)))

How It Works:
1. map(int, ...) converts input strings to integers.

2. set(...) removes duplicates.

3. sorted(..., reverse=True) gives a descending order.

Python 67
4. [:3] gets the top 3 elements if available.

5. ' '.join(map(str, ...)) joins the numbers into a space-separated string for output.

Write a program that takes a list of strings from the user as input
and counts the frequency of each unique string in the list and
displays the count of each string as per their actual order in the
list.
Input Format:
A single line containing space-separated strings.
Output Format:

Each unique string followed by its frequency on a new line in the format string:
frequency.

# Take space-separated strings as input


strings = input("Enter space-separated strings: ").split()
# Dictionary to store frequency
frequency = {}
# Count frequencies while preserving order
for word in strings:
if word not in frequency:
frequency[word] = 1
else:
frequency[word] += 1
# Display output
for word in frequency:
print(f"{word}: {frequency[word]}")

Write a program that takes a list of integers as input from the


user and find the maximum difference between any two
elements in the list. The maximum difference is defined as .
Input Format:

A single line containing space-separated integers.


Output Format:

A single integer representing the maximum difference between the maximum and
minimum elements in the list.

# Take input and convert to list of integers


nums = list(map(int, input("Enter space-separated integers: ").split()))
# Check if list is not empty

Python 68
if nums:
max_diff = max(nums) - min(nums)
print(max_diff)
else:
print("List is empty.")

Write a program that takes a list of integers as input from the


user and find the maximum difference between any two
elements in the list. The maximum difference is defined
Input Format:
A single line containing space-separated integers.

Output Format:
A single integer representing the maximum difference between the maximum and
minimum elements in the list.

# Take input from user and convert to a list of integers


numbers = list(map(int, input("Enter space-separated integers: ").split()))
# Check if the list has at least two elements
if len(numbers) < 2:
print("List must contain at least two elements.")
else:
max_value = max(numbers)
min_value = min(numbers)
max_difference = max_value - min_value
print(max_difference)

Tuples
Introduction
What is a Tuple?
A tuple is a collection used to store multiple items in a single variable.

Tuples are ordered, immutable (unchangeable), and allow duplicates.

Tuples are one of Python’s four built-in collection data types

Tuple Syntax
Tuples are defined using round brackets () .

Python 69
thistuple = ("apple", "banana", "cherry")
print(thistuple)

Tuple Properties
1. Ordered
Items in a tuple maintain the order in which they were inserted.

The order will not change.

2. Immutable
Once created, tuple elements cannot be modified (no add/remove/change).

3. Allow Duplicates
Since tuples are indexed, duplicate values are allowed.

how to convert a list of elements into a tuple with an example.

Operations on Tuples in Python


Tuples are immutable sequences, meaning their elements cannot be changed
after creation. However, several operations can still be performed on or with
tuples.

Operation
S.No Description Example Code Output
Name

Access
element by t = (10, 20,
1 Indexing 20
index (starting 30)print(t[1])

from 0)

Extract a range
t = (1, 2, 3, 4,
2 Slicing of elements (2, 3, 4)
5)print(t[1:4])
using start:end

Combine tuples
t1 = (1, 2)t2 = (3,
3 Concatenation using + (1, 2, 3, 4)
4)print(t1 + t2)
operator

Repeat tuple
t = (10, 20)print(t * (10, 20, 10, 20, 10,
4 Repetition using *
3) 20)
operator

Check
Membership t = (5, 10, 15)print(10
5 presence using True
Test in t)
in , not in

Loop through t = ('a', 'b', 'c')for i


6 Iteration abc
tuple elements in t: print(i)

Python 70
Operation
S.No Description Example Code Output
Name

Get number of
Length t = (1, 2, 3,
7 elements using 4
Calculation 4)print(len(t))
len()

Count how
Count t = (1, 2, 2, 3,
8 many times a 3
Elements 2)print(t.count(2))
value appears

Find Index of Find first index t = (10, 20, 30,


9 1
Element of a value 20)print(t.index(20))

Assign multiple
Tuple Packing t = (1, 2, 3)a, b, c =
10 variables at 123
& Unpacking tprint(a, b, c)
once

What is Tuple Assignment?


Tuple assignment refers to the ability to assign multiple variables at once using a
sequence (tuple, list, or iterable) on the right-hand side, and a matching
number of variables on the left-hand side.

This is commonly used to write more concise and readable code.

Tuple Methods
Python has two built-in methods that you can use on tuples.

Method Description Example Output

Returns the number of times a (1, 2, 3, 2,


count(value) 3
specified value occurs in the tuple 2).count(2)

Returns the first index of the (1, 2, 3, 2,


index(value) 2
specified value in the tuple 2).index(3)

Write a program to count the number of elements in a tuple.

# Input from user


elements = input("Enter elements: ")
# Convert input to a tuple
t = tuple(elements.split())
# Count number of elements using len()
count = len(t)
# Output the result
print("Number of elements in the tuple:", count)

Python 71
Write a program to find the occurrence of a given element in a
tuple, and print the result.

# Take input from user


elements = input("Enter elements: ")
# Convert input to a tuple
t = tuple(elements.split())
# Take the element to search
search_element = input("Enter the element to count: ")
# Count occurrences using count() method
count = t.count(search_element)
# Output the result
print(f"'{search_element}' occurs {count} time(s) in the tuple.")

Tuple functions
Function Description Example Output

Returns the
number of
len() len((10, 20, 30)) 3
elements in the
tuple

Returns the
min() min((5, 2, 9)) 2
smallest value

Returns the largest


max() max((5, 2, 9)) 9
value

Returns the sum of


sum() all values (numeric sum((1, 2, 3)) 6
only)

Returns a sorted
sorted() sorted((3, 1, 2)) [1, 2, 3]
list from the tuple

Returns True if all


all() elements are truthy all((1, 5, True)) True
or tuple is empty
all((1, 0, 3)) False

Returns True if
any() any element is any((0, 0, 1)) True
truthy
any((0, 0, False)) False

Returns index-
for i, v in
enumerate() value pairs for 0 a1 b
enumerate(('a','b')):print(i,v)
iteration

Difference Between List and Tuple in Python

Python 72
Feature List Tuple

A tuple is a collection
A list is a collection which
Definition which is immutable
is mutable (changeable).
(unchangeable).

Created using square Created using parentheses


Syntax
brackets [ ] ()

Can be modified after


Cannot be modified after
Mutability creation (add, remove,
creation
change elements)

Many built-in methods like


Fewer methods ( count() ,
Methods Available append() , remove() , sort() ,
index() )
etc.

Slower than tuples due to Faster due to fixed size


Performance
dynamic nature and immutability

Memory Usage Uses more memory Uses less memory

Suitable for data that might Suitable for fixed data


Use Cases change (e.g., dynamic (e.g., coordinates, days of
datasets) week)

Iteration Speed Slower in loops Faster in loops

Can Be Used as Dictionary Yes (if it contains only


No (because it’s mutable)
Key immutable items)

Supports Nesting Yes Yes

Programs
Create a Tuple from a List

# Step 1: Take list input from the user


user_input = input("Enter elements separated by space: ")
# Step 2: Convert input into a list
my_list = user_input.split()
# Step 3: Convert the list into a tuple
my_tuple = tuple(my_list)
# Step 4: Print both the list and the tuple
print("List:", my_list)
print("Tuple:", my_tuple)

Write a program to print the tuple element at index n, and print


the result as shown in the examples. If the given index is not
valid, print the error (Tuple Access)

Python 73
# Step 1: Take input and convert to tuple
user_input = input("Enter elements separated by space: ")
my_tuple = tuple(user_input.split())
# Step 2: Take index input
index_input = input("Enter an index: ")
# Step 3: Check if index is a valid integer
if index_input.isdigit() or (index_input.startswith('-') and index_input[1:].isdigit
()):
n = int(index_input)
# Step 4: Check if index is within valid range
if -len(my_tuple) <= n < len(my_tuple):
print(f"Element at index {n} is {my_tuple[n]}")
else:
print("Error accessing the element")
else:
print("Error accessing the element")

Create another tuple with the user-given elements and


concatenate the first tuple with the new tuple and print the result
as shown .(concenation and repetition)

# Input for the first tuple


first_input = input("Enter elements for the first tuple (space-separated): ")
first_tuple = tuple(first_input.split())
# Input for how many times to repeat the first tuple
n_input = input("Enter how many times to repeat the first tuple: ")
# Input for the second tuple
second_input = input("Enter elements for the second tuple (space-separate
d): ")
second_tuple = tuple(second_input.split())
# Check if n is a valid integer
if n_input.isdigit():
n = int(n_input)
repeated_tuple = first_tuple * n
result_tuple = repeated_tuple + second_tuple
print("Final concatenated tuple:", result_tuple)
else:
print("Invalid repetition count. Please enter an integer.")

Create a tuple with the user-given inputs. Write a program using


membership operators to check whether the given element is

Python 74
present in the tuple or not. Print the result as shown in the
examples.(membership test)

# Step 1: Take tuple input


user_input = input("Enter elements for the tuple (space-separated): ")
my_tuple = tuple(user_input.split())
# Step 2: Take element to search
element = input("Enter an element to search: ")
# Step 3: Check membership and print result
if element in my_tuple:
print(f"'{element}' is present in the tuple.")
else:
print(f"'{element}' is not present in the tuple.")

Deleting a tuple
Tuples are immutable, which means you cannot delete or change individual
elements once a tuple is created. However, you can delete the entire tuple using
the del statement.

my_tuple = ("apple", "banana", "cherry")


print("Before deletion:", my_tuple)
# Delete the tuple
del my_tuple

Write a program to add an element to a tuple based on the user-


given value in a specific index, and print the result as shown in
the example. If the index is not in the range, print the error
message as shown (Adding)

# Input: Tuple elements


user_input = input("Enter elements for the tuple: ")
my_tuple = tuple(user_input.split())
# Input: New element and index
new_element = input("Enter the element to add: ")
index_input = input("Enter the index to insert at: ")
# Check if index is a valid integer
if index_input.isdigit():
index = int(index_input)
if 0 <= index <= len(my_tuple):
# Convert to list for modification

Python 75
temp_list = list(my_tuple)
temp_list.insert(index, new_element)
updated_tuple = tuple(temp_list)
print("Updated tuple:", updated_tuple)
else:
print("Index out of range. Cannot insert.")
else:
print("Invalid index. Please enter an integer.")

Write a program to remove an element from the tuple based on


the user-given index, and print the result as shown in the
example. If the index is not valid, print the error (Deleting)

# Step 1: Take input to create a tuple


user_input = input("Enter elements for the tuple: ")
my_tuple = tuple(user_input.split())
# Step 2: Take index input from user
index_input = int(input("Enter the index to delete: "))

# Step 3: Check if the index is valid


if 0 <= index < len(my_tuple):
# Convert to list, remove element at index, then convert back to tuple
temp_list = list(my_tuple)
removed_element = temp_list.pop(index)
updated_tuple = tuple(temp_list)
print("Updated tuple:", updated_tuple)
else:
print("Index out of range. Cannot delete.")

Write a program to compare two given tuples. If the two tuples


contain same elements print True, otherwise False(Comparision)

# Input: First tuple


tuple1_input = input("Enter elements for the first tuple: ")
tuple1 = tuple(tuple1_input.split())
# Input: Second tuple
tuple2_input = input("Enter elements for the second tuple: ")
tuple2 = tuple(tuple2_input.split())
# Comparison
print(tuple1 == tuple2)

Python 76
Take two integers start index and end index as input from the
console. Write a program to print the elements of the tuple
within start index and end index, print the result.(Slicing)

# Step 1: Take input to create the tuple


user_input = input("Enter elements for the tuple: ")
my_tuple = tuple(user_input.split())
# Step 2: Take start and end index input directly as integers
start = int(input("Enter the start index: "))
end = int(input("Enter the end index: "))
# Step 3: Validate index range and slice
if 0 <= start <= end <= len(my_tuple):
sliced = my_tuple[start:end]
print("Sliced tuple:", sliced)
else:
print("Invalid index range.")

Write a program to find the sum of all the tuple elements, and
print the result (Sum)

# Input from user


elements = input("Enter numbers: ")
# Convert input string to a tuple of integers
t = tuple(map(int, elements.split()))
# Calculate the sum using sum() function
total = sum(t)
# Print the result
print("Sum of all elements in the tuple:", total)

To create a Python program to find the maximum element in a


tuple.
Algorithm:

Step 1: Accept a string input from the user representing elements of a tuple
separated by commas and store it in the variable data.
Step 2: Split the input string into individual elements and store them as strings in
a list named list1.

Step 3: Convert each element in list1 to an integer using list comprehension.


Step 4: Create a tuple tuple1 from list1.

Python 77
Step 5: Find the maximum element in tuple1 using the max() function and print it.
Step 6: End the program.

# Step 1: Accept a string input


data = input("Enter tuple elements separated by commas: ")
# Step 2: Split into list of strings
list1 = data.split(',')
# Step 3: Convert each to integer
list1 = [int(x) for x in list1]
# Step 4: Create a tuple
tuple1 = tuple(list1)
# Step 5: Find and print the minimum element
minimum = min(tuple1)
print("Minimum element in the tuple:", minimum)
# Step 6: End of program

Create a Python program to find the minimum element in a tuple.


Algorithm:
Step 1: Accept a string input from the user representing elements of a tuple
separated by commas and store it in the variable data.
Step 2: Split the input string into individual elements and store them as strings in
a list named list1.
Step 3: Convert each element in list1 to an integer using list comprehension.
Step 4: Create a tuple tuple1 from list1.

Step 5: Find the minimum element in tuple1 using the min() function and print it.
Step 6: End the program.

# Step 1: Accept a string input from the user


data = input("Enter the elements of the tuple separated by commas: ")
# Step 2: Split the input string into a list of strings
list1 = data.split(',')
# Step 3: Convert each element to an integer
list1 = [int(x) for x in list1]
# Step 4: Create a tuple from the list
tuple1 = tuple(list1)
# Step 5: Find the minimum element in the tuple
min_element = min(tuple1)
# Print the result

Python 78
print("Minimum element in the tuple:", min_element)
# Step 6: End of the program

Find Index of a User-Given Element in a Tuple

# Input from the user


data = input("Enter tuple elements separated by commas: ")
element = input("Enter the element to find the index: ")
# Convert to tuple
tuple1 = tuple(data.split(','))
# Check and find index
if element in tuple1:
index = tuple1.index(element)
print(f"Index of '{element}' in the tuple is:", index)
else:
print("Element not found in the tuple.")

You have a list of tuples where each tuple contains a pair of


elements. Your task is to sort the tuples based on the second
element of each tuple in ascending order.

# Input from user: pairs of integers separated by space


data = input("Enter pairs of integers (e.g., 1,2 4,1 3,5): ")

# Convert input to list of tuples


pair_list = []
for pair in data.split():
first, second = pair.split(',')
pair_list.append((int(first), int(second)))

# Sort by the second element of each tuple


sorted_list = sorted(pair_list, key=lambda x: x[1])

# Print result
print("Sorted list based on second element:")
for tup in sorted_list:
print(tup)

Write a Python program that takes pairs of integers and sorts


them based on the second element in each tuple.

Python 79
Input Format:

The first line contains an integer representing the number of tuples.

The next lines each contain two integers separated by a space representing
the elements of tuples.

Output Format:

Print the sorted list of tuples based on the second element.

Note:

If the second element of multiple tuples is equal, print them in the order of
their appearance.

Refer to the visible test cases for better understanding.

# Read the number of tuples


n = int(input())

# Initialize an empty list


tuple_list = []

# Read n pairs of integers and append them as tuples


for _ in range(n):
a, b = map(int, input().split())
tuple_list.append((a, b))

# Sort the list based on the second element of each tuple


sorted_tuples = sorted(tuple_list, key=lambda x: x[1])

# Print the sorted list of tuples


for t in sorted_tuples:
print(t)

You are given the elements of two tuples of same length, and
you need to combine them by interleaving their elements
(alternating elements from each tuple).

# Input two tuples of same length


tuple1 = tuple(input("Enter elements of first tuple (space-separated): ").split
())
tuple2 = tuple(input("Enter elements of second tuple (space-separated): ").s
plit())
# Check if lengths are equal

Python 80
if len(tuple1) != len(tuple2):
print("Tuples are not of the same length.")
else:
# Interleave elements
result = tuple()
for a, b in zip(tuple1, tuple2):
result += (a, b)
print("Interleaved tuple:", result)

Notes:
It uses zip() to pair elements from both tuples.

The result is a new tuple with alternating values from the input tuples.

Elements are taken as strings (you can cast to int() if needed).

Write a Python program that takes the elements of two tuples of


the same length and prints a new tuple where elements from the
two input tuples are interleaved.
Input Format:
The first line contains the number of elements in each tuple (N).

The second line contains N elements (strings) for the first tuple, separated by
space.
The third line contains N elements (strings) for the second tuple, separated by
space.

Output Format:
Output a tuple where the elements of the two input tuples are interleaved.

Constraints:
The length of both tuples must be equal

# Input number of elements


n = int(input())
# Input elements for the first tuple
tuple1 = tuple(input().split())
# Input elements for the second tuple
tuple2 = tuple(input().split())
# Check if both tuples have the correct length
if len(tuple1) != n or len(tuple2) != n:
print("Tuple lengths do not match the given size.")
else:

Python 81
# Interleave elements
result = tuple()
for i in range(n):
result += (tuple1[i], tuple2[i])
# Output result
print(result)

You are given a list of tuples where some tuples may be


repeated. Your task is to remove any duplicate tuples and return
a tuple of unique tuples.

# Input: number of tuples


n = int(input())
# Read the tuples
tuples_list = []
for _ in range(n):
items = tuple(input().split())
tuples_list.append(items)
# Remove duplicates while preserving order
unique = []
seen = set()
for t in tuples_list:
if t not in seen:
seen.add(t)
unique.append(t)
# Convert to tuple of tuples
result = tuple(unique)
# Output
print(result)

Write a Python program that takes elements of N tuples in


separate lines and prints a tuple of unique tuples, maintaining
the order of first occurrence.
Input Format:

The first line contains an integer representing the number of tuples (N).
The next N lines each contain two space separated integers representing the
values of tuples.

Output Format:
Output the tuple of unique tuples in the order of their occurrence in the input.

Python 82
You are working on a database management system where user data is stored in
tuples. Each tuple stores a user's first and last name. Due to an error, some
records have the first and last names swapped. Your task is to correct this by
swapping the two elements in a tuple

# Step 1: Input number of tuples


n = int(input())
# Step 2: Read and store the tuples
raw_data = []
for _ in range(n):
a, b = input().split()
raw_data.append((a, b))
# Step 3: Remove duplicates, keep first occurrence
unique_tuples = []
seen = set()
for t in raw_data:
if t not in seen:
seen.add(t)
unique_tuples.append(t)
# Step 4: Swap the elements in each tuple
swapped = [(b, a) for a, b in unique_tuples]
# Step 5: Convert to a tuple of tuples and print
result = tuple(swapped)
print(result)

Given two strings (first name and last name), write a program
that swaps the first and the last names and prints the corrected
names in the form of a tuple.
Input Format:

The first name and the last name in two lines.


Output Format:

A tuple where the first string is the last name, and the second string is the first
name.

# Swapping first name and last name


first_name = input()
last_name = input()
# Swapping the names
swapped_name = (last_name, first_name)
print("Swapped Name Tuple:", swapped_name)

Python 83
# Merging product and customer details
product_details = tuple(input("Enter product details (space-separated): ").spl
it())
customer_details = tuple(input("Enter customer details (space-separated):
").split())
# Combine both tuples
combined_info = product_details + customer_details
print("Combined Tuple:", combined_info)

You are managing product and customer information for an e-


commerce company. Product details and customer details are
stored separately in tuples. For an upcoming marketing
campaign, you need to merge these details into a single tuple for
easier access.
Given the details of the products and the details of the customer who bought the
products in two separate lines, concatenate both details and print them as a
tuple.

Input Format:
The first line contains elements (strings) separated by space representing the
product information.

The second line contains elements (strings) separated by space representing


the details of the customer.
Output Format:

A tuple containing the concatenated product and customer information.

# Input product details


product_input = input("Enter product details (space-separated): ")
product_details = tuple(product_input.split())
# Input customer details
customer_input = input("Enter customer details (space-separated): ")
customer_details = tuple(customer_input.split())
# Merge both tuples
merged_details = product_details + customer_details
# Display the merged tuple
print("Merged Details Tuple:", merged_details)

You are developing a system for a retail store to manage


inventory. The store tracks the stock of products, and your task

Python 84
is to provide a report on how many times a particular product
appears in the stock.
Given the names of the products available in the inventory, separated by space,
and the name of a product, count how many times the product appears in the
stock.
Input Format:

The first line contains the names of the products (strings) separated by space.
The second line contains a string representing the product to be searched for.
Output Format:

In the first line, print the available products as a tuple.


In the second line, print the integer representing the number of times the product
appears in the tuple.

# Input: list of product names


product_list = input().split()
# Convert the list to a tuple
inventory = tuple(product_list)
# Input: product to search for
search_product = input()
# Count occurrences
count = inventory.count(search_product)
# Output the results
print(inventory)
print(count)

Dictionaries
Introduction
A dictionary in Python is a collection of key–value pairs. It is a core data
structure used to map unique keys to corresponding values.

Key Characteristics
Feature Description

In Python 3.6 and earlier, dictionaries do not


Unordered (≤3.6)
maintain any insertion order.

From Python 3.7 onward, dictionaries


Ordered (≥3.7)
maintain the insertion order.

Dictionaries can be modified after creation


Mutable
(add, update, delete items).

Python 85
Feature Description

Each key must be unique. Values can be


Unique Keys
duplicated.

Keys must be of immutable (hashable)


Key Types
types such as strings, numbers, or tuples.

Values can be of any data type and can be


Value Types
duplicated.

Syntax

dictionary_name = {key1: value1, key2: value2, ..., keyN: valueN}

Typical Operations on a Dictionary


Operation Syntax / Method Description Example

Creates an empty
Create Dictionary d = {}d = dict() d = {}
dictionary

Adds a key-value
Add Element d[key] = value pair to the d["name"] = "Alice"
dictionary

Retrieves value for d["name"] or


Access Element d[key]d.get(key)
the given key d.get("name")

d[key] = Updates the value


Update Value d["age"] = 30
new_valued.update({...}) for the given key

Removes the key-


Delete Element del d[key]d.pop(key) value pair from del d["age"]
dictionary

Clears all key-value


Delete All Elements d.clear() d.clear()
pairs

Deletes the entire


Delete Dictionary del d del d
dictionary object

Loops through
Iterate Keys for k in d: for k in d:
dictionary keys

Loops through
Iterate Values for v in d.values(): for v in d.values():
dictionary values

Loops through both


Iterate Items for k, v in d.items(): for k, v in d.items():
keys and values

Creating a Dictionary from Two Lists:


zip() Function in Python:

Python 86
The built-in zip() function in Python pairs elements from two or more
iterables (like lists or tuples) by their corresponding positions (indexes).

The result is an iterator of tuples, where each tuple contains one element
from each iterable.

It stops as soon as the shortest iterable is exhausted, ensuring no


IndexError.

When we want to create a dictionary, we require key-value pairs.

We take:

One list (e.g., list1 ) for keys

Another list (e.g., list2 ) for values

We use zip(list1, list2) to pair them element-wise.

Then, we pass the zipped object to the dict() constructor to convert the
sequence of tuples into a dictionary.

Syntax:

dict(zip(keys_list, values_list))

This expression:

Zips keys_list and values_list into tuples

Converts them into a dictionary using dict()

Notes:
The two lists should ideally have the same length.

If they differ in length, zip() will truncate to the length of the shorter list.

Keys in a dictionary must be unique and immutable.

Values can be of any data type, including duplicates.

Create two lists with the user-given inputs. Write a program to convert the
given lists into a dictionary using the zip() function, and print the result

Write a program to create a


dictionary using two lists. Create two lists using user-given elements, and
print the results by sorting the items

Create a dictionary using two lists

Python 87
To create a dictionary by pairing elements from two separate
lists — one representing keys and the other representing values.

# Lists
keys = ['name', 'age', 'city']
values = ['Alice', 30, 'New York']
# Create dictionary
user_info = dict(zip(keys, values))
# Output
print(user_info)

Accessing Elements in a Dictionary (Python)


You can access the value of a dictionary by referring to its key using either:

1. Using Index Operator [key]


Syntax: dict[key]

If the key exists, it returns the value.

If the key does not exist, it raises a KeyError.

2. Using get(key) Method


Syntax: dict.get(key)

If the key exists, returns the value.

If the key doesn't exist, returns None or a default value if provided.

Behavior When Key Doesn’t


Method Behavior When Key Exists
Exist
dict[key] Returns value Raises KeyError

Returns None or default


dict.get(key) Returns value
value

Write a program to print the value of the user given key. if the
given key does not exist in dictionary then print value as None

# Step 1: Create dictionary using user input


keys = input("Enter keys separated by space: ").split()
values = input("Enter values separated by space: ").split()

# Step 2: Create dictionary using zip()


my_dict = dict(zip(keys, values))

Python 88
# Step 3: Ask user for a key to search
search_key = input("Enter the key to search: ")

# Step 4: Get value using get(), returns None if key not found
print("Value:", my_dict.get(search_key))

Membership Test in Dictionaries


You can check whether a key exists in a dictionary using the in and not in

operators.

Syntax:

key in dictionary # Returns True if key exists


key not in dictionary # Returns True if key does not exist

Expression Meaning Result


'key' in dict Is 'key' a key in dict ? True/False

'key' not in dict Is 'key' not a key in dict ? True/False

Is 'value' in dictionary's
'value' in dict.values() True/False
values?

Write a program to check whether the given key exists in the


dictionary or not. If the key exists in the dictionary then
print True, otherwise print False

# Step 1: Create dictionary using user input


keys = input("Enter keys separated by space: ").split()
values = input("Enter values separated by space: ").split()
# Step 2: Create dictionary using zip()
my_dict = dict(zip(keys, values))
# Step 3: Take the key to check
key_to_check = input("Enter the key to check: ")
# Step 4: Check membership and print result
print(key_to_check in my_dict)

Iteration in Dictionary
In Python, dictionaries can be iterated using a for loop to access keys, values, or
key-value pairs.

Iterating Over Keys (Default)

Python 89
fruits = {1: 'apple', 2: 'orange', 3: 'mango'}
for key in fruits:
print(key)

Iterating Over Values

for value in fruits.values():


print(value)

Iterating Over Key-Value Pairs

for key, value in fruits.items():


print(f"{key}: {value}")

Using items() to Get List of Tuples

print(list(fruits.items()))

Summary Table
Method Returns Example
for k in d Keys print(k)

for v in d.values() Values print(v)

for k, v in d.items() Key-value pairs as tuples print(k, v)

list(d.items()) List of (key, value) tuples [(1, 'apple'), (2, 'orange')]

Create a dictionary with user given keys and values. Write a


program to print key and values of a dictionary

Write a program to print key, value of a dictionary in the format


given in the sample test case.

data1: 1,2,3,4,5
data2: One,Two,Three,Four,Five
1 -> One
2 -> Two
3 -> Three
4 -> Four
5 -> Five

Python 90
# Take input for keys and values
keys = input("data1: ").split(",")
values = input("data2: ").split(",")
# Create dictionary using zip
my_dict = dict(zip(keys, values))
# Print the key -> value pairs
for k, v in my_dict.items():
print(f"{k} -> {v}")

Dictionary Methods
Python has a set of built-in methods that you can use on dictionaries.

Method Description

Removes all the elements from the


clear()
dictionary.
copy() Returns a shallow copy of the dictionary.

Creates a new dictionary from specified


fromkeys()
keys and a common value.

Returns the value for the specified key.


get(key)
Returns None if the key is not found.

Returns a view object with all key-value


items()
pairs as tuples.

Returns a view object with all the keys in


keys()
the dictionary.

Removes the item with the specified key


pop(key)
and returns its value.

Removes and returns the last inserted key-


popitem()
value pair (Python 3.7+).

Returns the value of a key. If the key does


setdefault() not exist, inserts the key with a specified
default value.

Updates the dictionary with elements from


update() another dictionary or an iterable of key-
value pairs.

Returns a view object with all the values in


values()
the dictionary.

Write a program to replace the value of an existing key by the user given value.
If the given key does not exist in the dictionary, print the result as key does not
exist.

Python 91
Deleting Elements from a Dictionary
In Python, dictionaries are mutable, meaning their contents can be modified. You
can delete elements (key-value pairs) from a dictionary using several built-in
methods and the del keyword. These operations help manage memory efficiently
and update data dynamically during program execution.

1. pop() Method
Purpose: Removes a specific key-value pair from the dictionary.

Usage: dictionary.pop(key)

Returns: The value of the removed key.

Error Handling: Raises a KeyError if the key does not exist (unless a default
value is provided).

2. popitem() Method
Purpose: Removes the last inserted key-value pair from the dictionary (since
Python 3.7).

Usage: dictionary.popitem()

Returns: A tuple (key, value) of the removed item.

Error Handling: Raises a KeyError if the dictionary is empty.

3. clear() Method
Purpose: Removes all key-value pairs, making the dictionary empty.

Usage: dictionary.clear()

Effect: Empties the dictionary, but the variable still exists as an empty
dictionary.

4. del Keyword
Purpose: Deletes a specific key-value pair or the entire dictionary.

Usage:

del dictionary[key] — deletes a specific element

del dictionary — deletes the entire dictionary object

Error Handling:

If the key does not exist, KeyError is raised.

Python 92
If you try to access the dictionary after deleting it with del ,a NameError is
raised.

Method Action
pop(key) Removes specific key, returns value
popitem() Removes last item, returns pair
clear() Clears all items (empty dict)
del dict[key] Deletes key-value pair
del dict Deletes entire dictionary

Dictionary Functions
Function Description Example Output

Returns True if all


keys in the
all() dictionary are True all({'a':1, 'b':2}) True
(or dictionary is
empty).

Returns True if any


True (because 'a'
any() key in the dictionary any({'a':0, '':0})
is truthy)
is True .

Returns the number


len() of key-value pairs in len({'a':1, 'b':2, 'c':3}) 3
the dictionary.

Returns a sorted list


of keys in the
sorted({'b':2, 'a':1,
sorted() dictionary (does not ['a', 'b', 'c']
'c':3})
sort the dictionary
itself).

Programs
Write a program to print the output in the following format
using all(), any(), len() and sorted() functions

# Input dictionary
data = {'x': 10, 'y': 0, 'z': 30}
# Display the original dictionary
print("Original Dictionary:")
print(data)
# Use all()
print("\nResult of all():")
print(all(data)) # True if all keys are truthy
# Use any()

Python 93
print("\nResult of any():")
print(any(data)) # True if any key is truthy
# Use len()
print("\nLength of dictionary:")
print(len(data)) # Number of key-value pairs
# Use sorted()
print("\nSorted keys of dictionary:")
print(sorted(data)) # List of sorted keys

Write a program to change the keys into values and values into
keys of a dictionary.

# Take input from the user for keys and values


keys = input("Enter keys separated by commas: ").split(",")
values = input("Enter values separated by commas: ").split(",")
# Create the original dictionary
original_dict = dict(zip(keys, values))
# Swap keys and values
swapped_dict = {v: k for k, v in original_dict.items()}
# Print the swapped dictionary
print("Original Dictionary:", original_dict)
print("Swapped Dictionary:", swapped_dict)

Given a dictionary with keys as tuples and values as lists. Write a


program that prints the keys and values

# Sample dictionary with tuple keys and list values


data = {
(1, 2): [10, 20],
(3, 4): [30, 40],
(5, 6): [50, 60]
}
# Print each key-value pair
for key, value in data.items():
print(f"{key} : {value}")

Write a program to generate and print a dictionary where the


values of identical keys from two dictionaries are added together
and stored.

Python 94
# Two sample dictionaries with some common keys
dict1 = {'a': 10, 'b': 20, 'c': 30}
dict2 = {'b': 5, 'c': 15, 'd': 25}
# Create a new dictionary to store the result
result = {}
# Add all keys from dict1
for key in dict1:
result[key] = dict1[key]
# Add values from dict2
for key in dict2:
if key in result:
result[key] += dict2[key] # Add values for common keys
else:
result[key] = dict2[key] # Add new key from dict2
# Print the result
print("Merged dictionary with added values:")
print(result)

Take an integer sequence from the user. Write a program to print


a dictionary from the given sequence, consider the element in
the sequence as a key, and the number of times the element
occurs in the sequence as a value. Print the result as shown in
the example.

# Input sequence from user


sequence = input("Enter a sequence of integers separated by space: ").split
()
# Convert to integers
sequence = list(map(int, sequence))
# Create dictionary with frequency
freq_dict = {}
for num in sequence:
freq_dict[num] = freq_dict.get(num, 0) + 1
# Print result
print("Frequency Dictionary:")
print(freq_dict)

Write a program to check the existence of a key in two


dictionaries.
If the given key is present in both the dictionaries, then print present in both

Python 95
If the given key is present in the first dictionary only, then print present in
first and if the key is present in the second dictionary only, then print present
in second

If the given key is not present is both the dictionaries, then print key is not
present.

# Sample dictionaries (you can modify or take input if needed)


dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'b': 4, 'c': 5, 'd': 6}
# Input key to check
key = input("Enter key to check: ")
# Check key presence
if key in dict1 and key in dict2:
print("present in both")
elif key in dict1:
print("present in first")
elif key in dict2:
print("present in second")
else:
print("key is not present")

You are building a word list to analyze different words. Your task
is to store the words in a dictionary where the key is the word,
and the value is the length of that word. Finally, print the
resulting dictionary.
Input Format:

The first line contains an integer n representing the number of words.

The next n lines, each contain a word (string).

Output Format:
Print a dictionary where the keys are the words, and the values are their
corresponding lengths.

# Input number of words


n = int(input())
# Initialize dictionary
word_dict = {}
# Loop to take words and store length
for _ in range(n):
word = input()
word_dict[word] = len(word)

Python 96
# Print the dictionary
print(word_dict)

You are building a word list to analyze different words. Your task
is to store the words in a dictionary where the key is the word,
and the value is the count of vowels in that word. Finally, print
the resulting dictionary.
Input Format:

The first line contains an integer n representing the number of words.

The next n lines, each containing a word (string).

Output Format:

Print a dictionary where the keys are the words and the values are the counts
of vowels in each word.

# Input: number of words


n = int(input())
# Define set of vowels
vowels = set('aeiouAEIOU')
# Initialize dictionary
vowel_count_dict = {}
# Loop to process each word
for _ in range(n):
word = input()
count = sum(1 for ch in word if ch in vowels)
vowel_count_dict[word] = count
# Output the resulting dictionary
print(vowel_count_dict)

You are building a word list to analyze different words. Your task
is to store the words in a dictionary where the key is the word,
and the value is the first letter of that word. Finally, print the
resulting dictionary.
Input Format:
The first line contains an integer n representing the number of words.

The next n lines, each containing a word (string).

Output Format:

Print a dictionary where the keys are the words, and the values are the first
letters of each word.

Python 97
# Input number of words
n = int(input())
# Initialize dictionary
first_letter_dict = {}
# Read words and build dictionary
for _ in range(n):
word = input().strip()
if word: # ensure word is not empty
first_letter_dict[word] = word[0]
# Output the dictionary
print(first_letter_dict)

Emma is managing a store and wants to keep track of the


inventory. She receives updates about items and their
quantities, and she needs a program to record these updates in
a dictionary. Can you help her by writing a Python program that
adds or updates items in the inventory?
Input Format:
The first line contains an integer n (the number of items).

The next n lines contain the item name (string) and quantity (integer) separated
by a space.

Output Format:

Print the final inventory in the format {'item_name': quantity, ...}.

# Input number of inventory updates


n = int(input())
# Initialize empty dictionary for inventory
inventory = {}
# Read and update inventory
for _ in range(n):
line = input().strip().split()
item = line[0]
qty = int(line[1])
# Add or update quantity
if item in inventory:
inventory[item] += qty
else:
inventory[item] = qty

Python 98
# Output final inventory
print(inventory)

A shopping mall keeps a record of the total sales made by each


store for the day in a dictionary. The keys represent the store
names, and the values represent the total sales in dollars. Write a
program that takes this dictionary as input from the user and
prints all the store details followed by the store with the highest
sales.
Input Format:

The first line contains an integer n representing the number of stores.


The next n lines, each containing a store name (string) followed by the sales
amount (integer) separated by space.
Output Format:

The first line contains the sales details as a dictionary in the order of the input.

The second line contains the store name with the highest sales.

# Input number of stores


n = int(input())
# Initialize empty dictionary for store sales
sales = {}
# Read input and store in dictionary
for _ in range(n):
store, amount = input().split()
sales[store] = int(amount)
# Print sales dictionary
print(sales)
# Find the store with the highest sales
max_store = max(sales, key=sales.get)
print(max_store)

A school keeps track of student grades in a dictionary where the


keys are student names and the values are lists of grades.
Create a program that takes this dictionary as input and
calculates the average grade for each student, printing a new
dictionary with student names as keys and their average grades
as values. Each student has exactly three grades.
Input Format:

Python 99
First line of the input is an integer representing the number of students.

The next lines, each containing a student name (string) followed by three
grades (space-separated integers).

Output Format:

A dictionary where the keys are student names, and the values are their
average grades (float) rounded to one decimal place.

# Input number of students


n = int(input())
# Initialize dictionary to store average grades
avg_grades = {}
# Process input for each student
for _ in range(n):
data = input().split()
name = data[0]
grades = list(map(int, data[1:4])) # Convert next 3 values to integers
avg = round(sum(grades) / 3, 1)
avg_grades[name] = avg
# Output the final dictionary
print(avg_grades)

Sets
set is a built-in data type used to store multiple unique elements within a single
variable. It is one of the four major collection data types in Python, alongside lists,
tuples, and dictionaries. What makes sets distinct is their property of storing
unordered, unindexed, and non-duplicate items. Sets are especially useful when
the presence of a particular item is more important than the order or frequency of
items.

Properties of Sets
Property Explanation

Unordered Elements do not maintain insertion order.

No indexing or slicing; elements can't be


Unindexed
accessed by position.

You can't change elements, but you can


Unchangeable (Immutable items)
add/remove entire elements.

Unique items Duplicate values are not allowed.

1.Accessing Elements in a Set

Python 100
Since sets are unordered, they do not support indexing or slicing.

Elements can be accessed by:

Iterating over the set using a for loop.

Checking for membership using the in or not in keyword.

Example: Accessing Elements

fruits = {"apple", "banana", "cherry"}


# Iteration
for item in fruits:
print(item)
# Membership Test
print("banana" in fruits) # Output: True
print("mango" not in fruits) # Output: True

2. Modifying a Set
Set elements are immutable and cannot be changed individually.

However, sets are mutable as a whole, meaning that elements can be added
or removed.

Direct modification of individual elements is not supported.

3. Adding Elements to a Set


Python provides two primary methods to add elements to a set:

Method Description Syntax Example


add() Adds a single element to the set myset.add("orange")

Adds multiple elements from an iterable to myset.update(["kiwi",


update()
the set "melon"])

Example: Using add()

myset = {"apple", "banana"}


myset.add("orange")
print(myset)
# Output: {'apple', 'banana', 'orange'}

Example: Using update() with a Set

Python 101
myset = {"apple", "banana"}
tropical = {"mango", "papaya"}
myset.update(tropical)
print(myset)
# Output: {'apple', 'banana', 'mango', 'papaya'}

Example: Using update() with a List

myset = {"apple", "banana"}


myset.update(["kiwi", "melon"])
print(myset)
# Output: {'apple', 'banana', 'kiwi', 'melon'}

Summary Table

Supports Multiple
Operation Method Example
Items

Iteration for loop Yes for i in myset:

Membership
in , not in Yes "apple" in myset
Check

Add Single Item add() No myset.add("orange")

myset.update(["kiwi",
Add Multiple Items update() Yes
"melon"])

Set Operations
Python provides powerful and flexible set operations that are used to perform
mathematical-like operations such as union, intersection, difference, and
symmetric difference. These operations are useful in data analysis, filtering,
comparison tasks, and more.

1. Union
Combines all elements from two or more sets.

Duplicates are removed automatically.

Does not modify the original sets.

Syntax:

A.union(B)
# or

Python 102
A|B

Example:

A = {1, 2, 3}
B = {3, 4, 5}
print(A.union(B)) # Output: {1, 2, 3, 4, 5}

2. Intersection
Returns elements that are common to both sets.

Does not modify the original sets.

Syntax:

A.intersection(B)
# or
A&B

Example:

A = {1, 2, 3}
B = {2, 3, 4}
print(A.intersection(B)) # Output: {2, 3}

3. Difference
Returns elements that are only in the first set and not in the second.

Order matters ( A - B ≠ B - A ).

Syntax:

A.difference(B)
# or
A-B

Example:

A = {1, 2, 3}
B = {2, 3, 4}

Python 103
print(A.difference(B)) # Output: {1}
print(B.difference(A)) # Output: {4}

4. Symmetric Difference
Returns elements that are in either of the sets but not in both.

Syntax:

A.symmetric_difference(B)
# or
A^B

Example:

A = {1, 2, 3}
B = {3, 4, 5}
print(A.symmetric_difference(B)) # Output: {1, 2, 4, 5}

5. Subset and Superset


Operation Method Description

Subset A.issubset(B) Returns True if all elements of A are in B

Superset A.issuperset(B) Returns True if A contains all elements of B

Example:

A = {1, 2}
B = {1, 2, 3}
print(A.issubset(B)) # True
print(B.issuperset(A)) # True

6. Disjoint Sets
Returns True if sets have no elements in common.

Syntax:

A.isdisjoint(B)

Example:

Python 104
A = {1, 2}
B = {3, 4}
print(A.isdisjoint(B)) # True

Summary Table of Set Operations

Operation Method Operator Description

Union set1.union(set2) ` `

Only common
Intersection set1.intersection(set2) &
elements

Elements in set1
Difference set1.difference(set2) -
but not in set2

Symmetric Elements in either


set1.symmetric_difference(set2) ^
Difference set, not both

True if all
Subset Test set1.issubset(set2) — elements of set1
in set2

True if set1
Superset Test set1.issuperset(set2) — contains all
elements of set2

True if no
Disjoint Test set1.isdisjoint(set2) — common
elements

Set Methods
Python provides several built-in set methods that allow performing operations
such as adding, updating, removing, and copying set elements. These methods
are available only for mutable sets (i.e., not frozenset ).

Table of Set Methods

Method Description
add(elem) Adds a single element elem to the set

Adds multiple elements from another


update(iterable)
iterable (list, tuple, set, etc.)

Removes elem from the set; raises


remove(elem)
KeyError if not found

Removes elem if it exists; does nothing if


discard(elem)
not found

Removes and returns an arbitrary element;


pop()
raises KeyError if empty

Python 105
Method Description
clear() Removes all elements from the set
copy() Returns a shallow copy of the set

Returns a new set with elements from both


union(set)
sets
intersection(set) Returns a new set with common elements

Returns a new set with elements in this set


difference(set)
but not in the other

Returns a new set with elements in either


symmetric_difference(set)
set but not both

Returns True if this set is a subset of the


issubset(set)
other

Returns True if this set is a superset of the


issuperset(set)
other

Returns True if two sets have no elements


isdisjoint(set)
in common

Set methods that return a new set: union() , intersection() , difference() ,


symmetric_difference()

Set methods that modify in place: add() , update() , remove() , discard() , clear() ,
pop()

Python 106

You might also like