Python Basics
Python Basics
Python
Created @June 25, 2025 4:19 PM
Class programming
TABLE OF CONTENT
1. Introduction to Python
What is Python?
Data Types
Operators
Comments
Type Conversions
Keywords
Built-in Functions
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
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
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
Python 3
Free to use and has a large developer
Open-source
community
Applications of Python:
Web development (Django, Flask)
Artificial Intelligence
Game development
Desktop applications
History of Python
Year Event
Python 4
Python 2 reached end of life on January 1,
2020 2020. The community fully shifted to
Python 3.
Import statements Place at the top of the file, one per line.
2. Documentation in Python
Documentation explains what your code does, how to use it, and why it was
written that way.
Type Description
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.
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 = .
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
1. Numeric Types
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
Ordered, immutable
tuple (1, 2, 3)
collection
# 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))
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
Python 9
2. Relational (Comparison) Operators Compare values
1. Arithmetic Operators
Operator Meaning Example Output
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
// 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
Python 10
!= Not equal to 5 != 3 True
Greater than or
>= 5 >= 5 True
equal
<= Less than or equal 3 <= 5 True
3. Assignment Operators
Assignment operators are used to assign values to variables. Python supports
several types of assignment operators.
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.
5. Bitwise Operators
Bitwise operators operate on the binary representation of integers.
| Bitwise OR 5|3 7
^ Bitwise XOR 5^3 6
Python 12
6. Identity Operators
Operator Meaning Example Output
a = [1, 2]
b=a
c = [1, 2]
7. Membership Operators
Operator Meaning Example Output
Parentheses – overrides
1 (Highest) ()
precedence
2 ** Exponentiation
Python 13
5 +, - Addition, subtraction
8 ^ Bitwise XOR
9 ` `
13 or Logical OR
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.
1. Single-line Comments
Start with a hash symbol: #
Example:
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)
Python 14
# This is a multi-line comment
# describing the code below
x=x+1
"""
This is also treated as a
multi-line comment, although it's
technically a multi-line string not assigned to any variable.
"""
print("Hello")
Best Practices
Use comments to explain why, not what the code is doing
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'>
x=5
y = "10"
z = int(y) + x # Convert string to int before adding
print(z) # Output: 15
Summary:
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
import keyword
print(keyword.kwlist)
Function Description
abs() Returns the absolute value of a number
Python 18
Returns list of attributes and methods of an
dir()
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
The
input() function is used to take user input
Example Output:
Python 20
num = int(input("Enter a number: "))
print("Your number + 5 is:", num + 5)
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
Python 21
print("After swapping:")
print("x =", x)
print("y =", y)
7. BMI Calculator
Python 22
else:
print("Odd")
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)
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")
match variable:
case value1:
# block1
case value2:
# block2
case _:
# default block
Programs
1. Check if number is Positive / Negative / Zero
Python 25
else:
print("Not eligible to vote.")
4. Grade Calculator
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)
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")
Python 28
elif income <= 1000000:
tax = 12500 + 0.2 * (income - 500000)
else:
tax = 112500 + 0.3 * (income - 1000000)
if math >= 60 and phy >= 50 and chem >= 40 and total >= 200:
print("Eligible for admission")
else:
print("Not eligible")
# 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
Example:
for i in range(5):
print(i, end=" ")
Output:
01234
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}")
Condition Evaluation Before entering the loop Before entering the loop
Programs
1. Print 1 to 10
2. Sum of N numbers
n = int(input("Enter N: "))
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total)
Python 32
print(f"{num} x {i} = {num * i}")
5. Factorial of a number
7. Reverse a number
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)
n = int(input("Enter N: "))
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
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=' ')
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:
f = open("example.txt", "r")
print(f.read())
f.close()
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()
f = open("example.txt", "r")
for line in f:
print(line)
f.close()
Example:
5. Writing to a File
Example 5: Appending to a file
Python 37
Example 7: Create a new file using 'x'
f = open("newfile.txt", "x")
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.
import os
os.remove("example.txt")
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")
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
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:
This will cause the program to stop execution and display an error.
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.
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.
x = -1
if x < 0:
Python 41
raise Exception("Sorry, no numbers below zero are allowed")
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.
Strings
Introduction
A string in Python is a sequence of characters enclosed within single ( ' ) or
double ( " ) quotation marks.
Example:
print("Hello")
print('Hello')
1. Characteristics of Strings
Indexing: Characters in a string are accessed using an index.
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"')
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 ( ''' ).
5. Summary
Python 43
Concept Description
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.
Example:
a = "HELLO"
print(a[0]) # Output: H (first character)
print(a[-1]) # Output: O (last character)
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: ")
Output:
Syntax:
Python 45
string[start_index:end_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])
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
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.
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
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
a = "Hello"
print(a * 3)
Output:
HelloHelloHello
Python 48
Output:
Note: The space is part of the original string and is repeated along with it.
print("*" * 5)
Output:
*****
Example:
6. Summary
Python 49
2. Syntax
3. Examples
Example 1: Using in
Output:
True
Output:
True
The substring "Java" is not present in the string, so the result is True .
email = "[email protected]"
if "@" in email:
print("Valid email address")
else:
print("Invalid email address")
Output:
Python 50
This is a practical use of in for input validation.
4. Summary
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.
Syntax:
Example:
age = 20
txt = f"My name is Vivek, I am {age}"
Python 51
print(txt)
Output:
My name is Vivek, I am 20
Example:
python
CopyEdit
price = 59
txt = f"The price is {price} dollars"
print(txt)
Output:
price = 59
txt = f"The price is {price:.2f} dollars"
print(txt)
Output:
In this case, .2f formats the number as a float with 2 digits after the decimal
point.
Python 52
You can also perform calculations or call functions inside placeholders.
Output:
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).
Converts all
lower() characters to "HELLO".lower() 'hello'
lowercase
Converts all
upper() characters to "hello".upper() 'HELLO'
uppercase
Python 53
Method Description Example Output
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
Replaces a
replace() substring with "python".replace("py", "my") 'mython'
another
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
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
Python 55
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']
Joins elements of
join() an iterable with a '-'.join(['a', 'b', 'c']) 'a-b-c'
separator
Translates string
"abc".translate(str.maketrans("a",
translate() using the translation 'xbc'
"x"))
table
Python 56
8. Partitioning and Substring Extraction
5. Reverse a String
Python 57
s = input("Enter a string: ")
print("Reversed string:", s[::-1])
import string
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
if sorted(str1) == sorted(str2):
print("True")
else:
print("False")
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
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"
Python 59
2. Check if Two Strings are Rotations of Each Other
Problem:
Check if one string is a rotation of another string.
Output: True
Output: "progamin"
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
1. Ordered
Items in a list maintain the order in which they are added.
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
List Methods
Python 61
Python has a set of built-in methods that you can use on lists.
Adds an element at
append() lst.append("apple") ['apple']
the end of the list
Adds elements of
lst.extend(["banana", ['apple', 'banana',
extend(iter) an iterable to the
"cherry"]) 'cherry']
end of the list
Removes and
returns element at 'cherry' (and
pop([i]) lst.pop()
index i (last if not removes it)
given)
# Initial list
my_list = [3, 1, 4, 1, 5, 9]
Python 62
print("After append(2):", 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)
# 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)
Python 63
print("After reverse():", my_list)
Sample Output:
Programs
1. Check if an Element is Present in a List
if item in elements:
print(f"{item} is present in the list.")
else:
print(f"{item} is not present in the list.")
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."
list1 *= repeat
list2 *= repeat
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:
Constraints:
The input must contain exactly 7 input values.
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.
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:
How It Works:
1. map(int, ...) converts input strings to integers.
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.
A single integer representing the maximum difference between the maximum and
minimum elements in the list.
Python 68
if nums:
max_diff = max(nums) - min(nums)
print(max_diff)
else:
print("List is empty.")
Output Format:
A single integer representing the maximum difference between the maximum and
minimum elements in the list.
Tuples
Introduction
What is a Tuple?
A tuple is a collection used to store multiple items in a single variable.
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.
2. Immutable
Once created, tuple elements cannot be modified (no add/remove/change).
3. Allow Duplicates
Since tuples are indexed, duplicate values are allowed.
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
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
Assign multiple
Tuple Packing t = (1, 2, 3)a, b, c =
10 variables at 123
& Unpacking tprint(a, b, c)
once
Tuple Methods
Python has two built-in methods that you can use on tuples.
Python 71
Write a program to find the occurrence of a given element in a
tuple, and print the result.
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 a sorted
sorted() sorted((3, 1, 2)) [1, 2, 3]
list from the tuple
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
Python 72
Feature List Tuple
A tuple is a collection
A list is a collection which
Definition which is immutable
is mutable (changeable).
(unchangeable).
Programs
Create a Tuple from a List
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")
Python 74
present in the tuple or not. Print the result as shown in the
examples.(membership test)
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.
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.")
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)
Write a program to find the sum of all the tuple elements, and
print the result (Sum)
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.
Python 77
Step 5: Find the maximum element in tuple1 using the max() function and print it.
Step 6: End the program.
Step 5: Find the minimum element in tuple1 using the min() function and print it.
Step 6: End the program.
Python 78
print("Minimum element in the tuple:", min_element)
# Step 6: End of the program
# Print result
print("Sorted list based on second element:")
for tup in sorted_list:
print(tup)
Python 79
Input Format:
The next lines each contain two integers separated by a space representing
the elements of tuples.
Output Format:
Note:
If the second element of multiple tuples is equal, print them in the order of
their appearance.
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).
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.
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
Python 81
# Interleave elements
result = tuple()
for i in range(n):
result += (tuple1[i], tuple2[i])
# Output result
print(result)
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
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:
A tuple where the first string is the last name, and the second string is the first
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)
Input Format:
The first line contains elements (strings) separated by space representing the
product information.
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:
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
Python 85
Feature Description
Syntax
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
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
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.
We take:
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:
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.
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
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)
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
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))
operators.
Syntax:
Is 'value' in dictionary's
'value' in dict.values() True/False
values?
Iteration in Dictionary
In Python, dictionaries can be iterated using a for loop to access keys, values, or
key-value pairs.
Python 89
fruits = {1: 'apple', 2: 'orange', 3: 'mango'}
for key in fruits:
print(key)
print(list(fruits.items()))
Summary Table
Method Returns Example
for k in d Keys print(k)
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
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)
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()
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:
Error Handling:
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
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.
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)
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.
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:
Output Format:
Print a dictionary where the keys are the words, and the values are their
corresponding lengths.
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:
Output Format:
Print a dictionary where the keys are the words and the values are the counts
of vowels in each word.
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.
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)
The next n lines contain the item name (string) and quantity (integer) separated
by a space.
Output Format:
Python 98
# Output final inventory
print(inventory)
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.
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.
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
Python 100
Since sets are unordered, they do not support indexing or slicing.
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.
Python 101
myset = {"apple", "banana"}
tropical = {"mango", "papaya"}
myset.update(tropical)
print(myset)
# Output: {'apple', 'banana', 'mango', 'papaya'}
Summary Table
Supports Multiple
Operation Method Example
Items
Membership
in , not in Yes "apple" in myset
Check
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.
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.
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}
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
Union set1.union(set2) ` `
Only common
Intersection set1.intersection(set2) &
elements
Elements in set1
Difference set1.difference(set2) -
but not in set2
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 ).
Method Description
add(elem) Adds a single element elem to the set
Python 105
Method Description
clear() Removes all elements from the set
copy() Returns a shallow copy of the set
Set methods that modify in place: add() , update() , remove() , discard() , clear() ,
pop()
Python 106