Q1. Illustrate the concept of “for loop”using ranges,strings, lists, dictionaries in Python.
Introduction :
A
● forloopin Python is used to iterate over a sequence(like a list, string, range, or dictionary).
● It is a control flow statement that allows code to be repeated for each item in the sequence.
● The loop executes the block of code inside it for every item in the given iterable.
Syntax :
for item in iterable:
# Execute code
❖
item
: This is a variable that will hold the currentitem from the iterable during each iteration.
❖ i
terable : This is the sequence or collection of itemsthat you want to loop over. It can be a list,
string, range, or dictionary, among others.
Example :
USAGE :
forloop in Python is a versatile and powerfulway to iterate over different types of sequences (lists, strings,
he
T
ranges, dictionaries).
➢
ange: Useful for iterating over a sequence of numbers.
R
➢ String: Can iterate over each character in the string.
➢ List: Allows iteration over each element in the list.
➢ Dictionary: Can iterate over keys, values, or key-valuepairs.
forLoop with Ranges :
Using
➔ The
range()function in Python generates a sequenceof numbers. It is commonly used
forloops when you need to iterate a specific numberof times.
in
range()
Syntax of : for i in
range(start,
stop, step)
:
s
● tart : The starting value (inclusive).
● stop
: The ending value (exclusive).
●
step: The difference between each number in the sequence(optional, default is 1).
stop:
Range with only a
start&
Range with a specified stop
:
stepvalue:
Range with a
forLoop with Strings :
Using
➔ In Python, strings are sequences of characters, meaning each character can be
accessed individually.
➔ The forloop allows you to iterate over each characterin a string, one by one. This can
be useful when you want to process or manipulate individual characters in a string.
Basic Syntax:
for char in string:
# Code block to process 'char'
●
char
: A variable that will hold the current characterof the string during each iteration.
●
string
: The string variable you are iterating over.
Example :
EXPLANATION :
➢ The
forloop goes through each character of the string
"Abhay Damalu @ 123"
.
➢ During each iteration, the
charvariable holds onecharacter of the string (eg. 'A', 'B', 'H', 'A', 'Y'...).
➢ The print(char,”ord(char)”)statement outputs eachcharacter individually along with their
ascii value.
forLoop with List:
Using
➔ Alistin Python is an ordered collection of itemsthat can hold different types of data,
such as integers, strings, or even other lists.
➔ Lists areiterableobjects, meaning we can easilyuse aforloop to iterate through their
elements one by one.
Basic Syntax:
for item in list:
# code block to execute for each item
●
item
: Represents the current element of the list thatthe loop is iterating over.
●
list
: The list variable that contains the data youwant to iterate through.
Example :
EXPLANATION :
➢ The
forloop goes through each item in the list.
➢ During each iteration, the
dayvariable holds oneitem of the list.
➢ The
print(day)statement outputs each day in the listindividually.
forLoop with Dictionary:
Using
➔ A dictionaryinPythonisanunorderedcollectionofkey-valuepairs.Eachelementina
dictionary consists of a key and a value, and dictionaries are commonlyusedtostore
data in a way that allows fast lookups using keys.
➔ We can iterate over the keys, values, or key-value pairs in a dictionary using a forloop.
➔ We can use methods like
.items() .keys()
, .values()formorecontrolover
,and
how you iterate.
Basic Syntax:
for key in dictionary:
# Access the value associated with the key using dictionary[key]
Example :
Q2. Demonstrate the use of functions and passing of parameters through an example.
Q2. Demonstrate the use of functions and passing of parameters through an example.
➔ A Python function is a block of organized, reusable code that is used to perform a
single, related action.
➔ Functions provide better modularity for your application and a high degree of
code reusing.
➔ We can pass values to a function through parameters, which the function can then use to
perform its task.
KEY POINTS :
1. Parameters
P
● arametersare thevariableslisted in the function definition.
● They act as placeholders for the values (arguments) that will be passed to the function when
it is called.
● Parameters define what type of data the function expects when it is called.
2. Arguments
A
● rgumentsare theactual valuesordatapassed tothe function when it is called.
● They correspond to the parameters defined in the function, providing the function with the
values it needs to work with.
3. Function Definition
defkeyword followed by the function
● The process of defining a function in Python is done using the
ame, parameters (optional), and the function body.
n
The function can optionally return a value.
●
4. Function Call
● Function calling is the process of invoking a previously defined function, passing the required
arguments (if any), and using the return value (if any).
Basic Syntax:
USE OF USER - DEFINED FUNCTIONS :
With No Parameter :
With a single Parameter :
With multiple Parameter :
With default Parameter :
Q3. How can the manipulations be done in strings, lists, tuples, sets, dictionaries.
STRINGS
Strings areimmutablesequences of characters. Common operations include:
s[0]
● Accessing: s[-1]
,
s[1:5]
● Slicing: s[::-1]
,
s.upper()
● Changing case: s.lower()
,
s.replace("old", "new")
● Replacing:
s.split(",")
● Splitting:
" ".join(['a', 'b', 'c'])
● Joining:
s.find("substring")
● Finding substrings:
Method Description Example
upper()
Converts to uppercase "hello".upper()→
"HELLO"
lower()
Converts to lowercase "HELLO".lower()→
"hello"
title()
Capitalizes each word "hello world".title()→
"Hello World"
strip()
Removes spaces " hi ".strip()→
"hi"
replace()
Replaces substring "cat".replace("c", "b")→
"bat"
split()
Splits string into list "a,b,c".split(",")→
['a', 'b', 'c']
join()
Joins list into string " ".join(['Hi', 'there'])→
"Hi there"
find()
Finds index of substring "hello".find("e")→
1
count()
Counts occurrences "banana".count("a")→
3
startswith()
Checks prefix "hello".startswith("he")→
True
endswith()
Checks suffix "hello".endswith("o")→
True
LISTS
Lists aremutableordered collections. Operations include:
lst[0]
● Accessing: lst[-1]
,
lst[1:4]
● Slicing:
lst.append(x)
● Adding elements: lst.insert(i, x)
,
lst.remove(x)
● Removing elements: lst.pop(i)
,
lst.sort()
● Sorting: lst.reverse()
,
" ".join(list)
● Joining:
Method Description Example
append(x)
Adds item to the end fruits.append('orange')
insert(i, x)
i
Inserts at index fruits.insert(1, 'kiwi')
remove(x)
x
Removes first occurrence of fruits.remove('banana')
pop(i)
i
Removes and returns item at index fruits.pop(1)
sort()
Sorts the list in-place fruits.sort()
reverse()
Reverses the list in-place fruits.reverse()
clear()
Removes all items fruits.clear()
index(x)
x
Returns first index of fruits.index('apple')
count(x)
xoccurs
Returns number of times fruits.count('apple')
copy()
Returns a shallow copy fruits.copy()
TUPLES
Tuples areimmutableordered collections. Operations include:
t[0]
● Accessing: t[-1]
,
t[1:3]
● Slicing:
U
● a, b, c = t
npacking:
● Creating new tuple: Convert a tuple to a list, modify, then convert back.
Operation Example Result
Concatenation (1, 2) + (3, 4)
(1, 2, 3, 4)
Repetition (1, 2) * 2
(1, 2, 1, 2)
Membership 3 in (1, 2, 3)
True
Length len((1, 2, 3))
3
Index (1, 2, 3).index(2)
1
Count (1, 2, 2, 3).count(2)
2
SETS
Sets areunorderedcollections ofunique elements.Operations include:
s.add(x)
● Adding elements:
s.remove(x)
● Removing elements: s.discard(x)
,
s1 | s2
● Union:
s1 & s2
● Intersection:
s1 - s2
● Difference:
x in s
● Membership testing:
union()
Combines two sets a.union(b)
intersection()
Common elements a & b
difference()
Elements in a not in b a - b
symmetric_difference() Elements in a or b, not both
a ^ b
issubset()
Checks if a is a subset of b a.issubset(b)
issuperset()
Checks if a is a superset of b a.issuperset(b)
isdisjoint()
Checks if sets have no common elemen
a.isdisjoint(b)
add(x)
Adds an element a.add(4)
remove(x)
Removes x (Error if not found) a.remove(2)
discard(x)()
Removes x (No error if not found) a.discard(5)
pop()
Removes and returns a random item a.pop()
clear()
Removes all elements a.clear()
copy()
Shallow copy b = a.copy()
DICTIONARIES
Dictionaries storekey-value pairs. Operations include:
d[key]
● Accessing values: d.get(key)
,
d[key] = value
● Adding/Updating:
d.pop(key)
● Removing: del d[key]
,
d.keys()
● Keys/Values/Items: d.values()
, d.items()
,
d.copy()
● Copying:
d.update(other_dict)
● Updating:
Method Description Example
get(key)
Returns value or None if key not found person.get("age")
update(dict2)
Adds or updates multiple keys person.update({"age": 27,
"city": "LA"})
pop(key)
Removes key and returns value person.pop("age")
popitem()
Removes and returns last inserted pair person.popitem()
del dict[key]
Deletes key-value pair del person["city"]
clear()
Empties the dictionary person.clear()
copy()
Returns a shallow copy copy_dict = person.copy()
Q4. Describe the use of file read & write functions.
In Python, file handling is essential for reading and writing data to and from files. Python
provides several built-in functions to work with files. Here's a detailed explanation of
how toreadandwritefiles in Python.
Opening Files
open()function. The
efore reading or writing to a file, you need to open it using the
B
syntax is:
file_object = open("filename", "mode")
●
"filename"is the name of the file you want to open.
●
"mode"specifies the file operation (e.g., read, write, append).
Modes for File Operations:
●
'r'
: Read (default mode, opens the file for reading).
●
'w'
: Write (opens the file for writing, creates a new file or overwrites if it exists).
●
'a'
: Append (opens the file for appending, creates a new file if it doesn't exist).
●
'b' 'rb'or
: Binary mode (used for reading/writing binary files, e.g., 'wb'
).
●
'x'
: Exclusive creation (creates a new file, raises error if the file already exists).
Reading from a File
o read from a file, you first open it in read mode (
T 'r'
), then use one of the following
methods:
read()
: Reads the entire content of the file as astring.
with open("file.txt", "r") as file:
content = file.read()
print(content)
1.
readline()
: Reads one line at a time from the file.
with open("file.txt", "r") as file:
line = file.readline()
# Reads the first line
print(line)
2.
readlines()
: Reads all lines in a file and returns them as a list of strings.
with open("file.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing to a File
o write to a file, you open it in write mode (
T 'w'
) or append mode (
'a'
), and then use
one of these methods:
write()
: Writes a string to the file.
with open("file.txt", "w") as file:
file.write("Hello, World!")
1.
writelines()
: Writes a list of strings to the file.
lines = ["Hello\n", "World\n"]
with open("file.txt", "w") as file:
file.writelines(lines)