Python Code and Theory
Python Code and Theory
In Python, there are several built-in Python exceptions that can be raised when an error occurs
during the execution of a program. Here are some of the most common types of exceptions in
Python:
• SyntaxError: This exception is raised when the interpreter encounters a syntax error in the
code, such as a misspelled keyword, a missing colon, or an unbalanced parenthesis.
• NameError: This exception is raised when a variable or function name is not found in the
current scope.
• IndexError: This exception is raised when an index is out of range for a list, tuple, or other
sequence types.
• ValueError: This exception is raised when a function or method is called with an invalid
argument or input, such as trying to convert a string to an integer when the string does not
represent a valid integer.
• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.
• ImportError: This exception is raised when an import statement fails to find or load a
module.
Modules
A document with definitions of functions and various statements written in Python is called a Python
module.
o A built-in module, such as the itertools module, is inherently included in the interpreter.
We employ modules to divide complicated programs into smaller, more understandable pieces.
Modules also allow for the reuse of code.
Rather than duplicating their definitions into several applications, we may define our most frequently
used functions in a separate module and then import the complete module.
Here, we are creating a simple Python program to show how to create a module.
# here, the above function will square the number passed as the input
result = number ** 2
Import Module
In Python, we may import functions from one module into our program, or as we say into, another
module.
For this, we make use of the import Python keyword. In the Python window, we add the next to
import keyword, the name of the module we need to import. We will import the module we defined
earlier example_module.
Syntax:
1. import example_module
The functions that we defined in the example_module are not immediately imported into the
present program. Only the name of the module, i.e., example_ module, is imported here.
Lambda function
Python Lambda Functions are anonymous functions means that the function is without a name. As
we already know the def keyword is used to define a normal function in Python. Similarly,
the lambda keyword is used to define an anonymous function in Python.
• This function can have any number of arguments but only one expression, which is evaluated
and returned.
• One is free to use lambda functions wherever function objects are required.
• You need to keep in your knowledge that lambda functions are syntactically restricted to a
single expression.
• It has various uses in particular fields of programming, besides other types of expressions in
functions.
In the example, we defined a lambda function(upper) to convert a string to its upper case
using upper().
This code defines a lambda function named upper that takes a string as its argument and converts it
to uppercase using the upper() method. It then applies this lambda function to the string
‘GeeksforGeeks’ and prints the result
str1 = 'GeeksforGeeks'
print(upper(str1))
Lists: list operations, list slices, list methods, list loop, mutability, aliasing, cloning lists, list
parameters, list comprehension; Tuples: tuple assignment, tuple as return value, tuple
List:
List is a collection which is ordered and changeable and allows duplicate members.
To use a list, you must declare it first. Do this using square brackets and separate
List operations:
These operations include indexing, slicing, adding, multiplying, and checking for
membership
Lists respond to the + and * operators much like strings; they mean concatenation and
repetition here too, except that the result is a new list, not a string.
Append()
Extend()
Insert()
Pop()
Remove()
Reverse()
Sort()
Aliasing:
1. An alias is a second name for a piece of data, often easier (and more useful) than
making a copy.
2. If the data is immutable, aliases don’t matter because the data can’t change.
3. But if data can change, aliases can result in lot of hard – to – find bugs.
Tuples:
A tuple is a collection which is ordered and unchangeable. In Python tuples are written
If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being
added, changed, or deleted.
Count()
Index()
Length()
Dictionaries:
A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Key-value pairs
Unordered
X={1:’A’,2:’B’,3:’c’}
X=dict([(‘a’,3) (‘b’,4)]
X=dict(‘A’=1,’B’ =2)
Data types:
The data stored in memory can be of many types. For example, a student roll number is
stored as a numeric value and his or her address is stored as alphanumeric characters. Python
has various standard data types that are used to define the operations possible on them and
Int:
length.
>>> print(24656354687654+2)
24656354687656
>>> print(20)
20
# To verify the type of any object in Python, use the type() function:
>>> type(10)
<class 'int'>
Float:
Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Float can also be scientific numbers with an "e" to indicate the power of 10.
>>> y=2.8
>>> y
2.8
Boolean:
Objects of Boolean type may have one of two values, True or False:
>>> type(True)
<class 'bool'>
String:
quotation marks. Python allows for either pairs of single or double quotes.
• Strings can be output to screen using the print function. For example: print("hello").
mrcet college
If you want to include either type of quote character within the string, the simplest way is to
delimit the string with the other type. If a string is to contain a single quote, delimit it with
Specifying a backslash (\) in front of the quote character in a string “escapes” it and causes
Python to suppress its usual special meaning. It is then interpreted simply as a literal single
quote character:
Functions
Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
Output:
def add_numbers(x,y):
sum = x + y
return sum
Output:
The sum is 25
2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
6. One or more valid python statements that make up the function body. Statements must have
def hf():
print("hw")
hf()
The return statement is used to exit a function and go back to the place from where it was
called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
Arguments
# Passing Arguments
def hello(wish):
return '{}'.format(wish)
print(hello("mrcet"))
Output:
Mrcet
Below is a call to this function with one and no arguments along with their respective error
messages.
#Keyword Arguments
When we call a function with some values, these values get assigned to the arguments
Python allows functions to be called using keyword arguments. When we call functions in
There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters which we want, provided that the other parameters have default argument values.
#Default Arguments
We can provide a default value to an argument by using the assignment operator (=)
def hello(wish,name='you'):
return '{},{}'.format(wish,name)
print(hello("good morning"))
Output:
good morning,you
Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.
Variable-length arguments
Sometimes you may need more arguments to process function then you mentioned in the
definition. If we don’t know in advance about the arguments needed in function, we can use
For this an asterisk (*) is placed before a parameter in function definition which can hold
If we use one asterisk (*) like *var, then all the positional arguments from that point till the
end are collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like
**var, then all the positional arguments from that point till the end are collected as
#Program to find area of a circle using function use single return value function with
argument.
pi=3.14
def areaOfCircle(r):
return pi*r*r
print(areaOfCircle(r))
Conditional (if):
The if statement contains a logical expression using which data is compared and a decision
Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
Alternative if (If-Else):
An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
The else statement is an optional statement and there could be at most only one else
Syntax of if - else :
if test expression:
Body of if stmts
else:
The elif statement allows us to check multiple expressions for TRUE and execute a
block of code as soon as one of the conditions evaluates to TRUE. Similar to the else,
the elif statement is optional. However, unlike else, for which there can be at most one
If test expression:
Body of if stmts
else:
Loops
A loop statement allows us to execute a statement or group of statements multiple times as
long as the condition is true. Repeated execution of a set of statements with the help of loops
is called iteration.
Loops statements are used when we need to run same code again and again, each time with a
different value.
Statements:
1. While Loop
2. For Loop
While loop:
Loops are either infinite or conditional. Python while loop keeps reiterating a block of
The while loop contains a boolean expression and the code inside the loop is
The statements that are executed inside while can be a single line of code or a block of
multiple statements.
Syntax:
while(expression):
Statement(s)
For loop
The For Loops in Python are a special type of loop statement that is used for sequential traversal.
Python For loop is used for iterating over an iterable like a String, Tuple, List, Set, or Dictionary.
Here we will see Python for loop examples with different types of iterables:
This code uses a for loop to iterate over a string and print each character on a new line. The loop
assigns each character to the variable i and continues until all characters in the string have been
processed.
Python
print("String Iteration")
s = "Geeks"
for i in s:
print(i)
Output:
String Iteration
G
e
e
k
s
This code uses a Python for loop with index in conjunction with the range() function to generate a
sequence of numbers starting from 0, up to (but not including) 10, and with a step size of 2. For each
number in the sequence, the loop prints its value using the print() function. The output will show the
numbers 0, 2, 4, 6, and 8.
Python
print(i)
Output :
0
2
4
6
8
#list of items
list = ['M','R','C','E','T']
i=1
i = i+1
tuple = (2,3,5,7)
for a in tuple:
print (a)
#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}
print (keys)
print(blocks)
college = 'MRCET'
print (name)
When one Loop defined within another Loop is called Nested Loops.
Syntax:
statements
statements
for i in range(1,6):
for j in range(5,i-1,-1):
print('')
String slices:
Subsets of strings can be taken using the slice operator ([ ] and [:]) with indexes starting at 0
in the beginning of the string and working their way from -1 at the end.
Slicing will start from index and will go up to stop in step of steps.
65
For example 1−
1. Correct word
# replaced_string = replace_consecutive(user_input)
#def replace_consecutive(string):
result = ''
i=0
count = 1
count += 1
i += 1
if count >= 3:
result += string[i] * 2
else:
i += 1
2. Division
num=int(input("Enter a number:"))
while(num):
if(d==0):
break
else:
result=num/d
print(result)
break
3. Fibonacci series
fibonacci_series = []
a, b = 0, 1
fibonacci_series.append(a)
a, b = b, a + b
print(fibonacci_series)
4. For loop
str="BBA-CA 3"
for i in str:
print()
5. Magic number
# Initialize sum
sum = 0
if char.isdigit():
temp_sum = 0
temp_sum += sum % 10
sum //= 10
sum = temp_sum
6. String list
list1=["sinha","arvind","aakash","binod","chetan"]
name="aakash"
for i in list1:
if (i==name):
continue
else:
print(i)
7. Print vibgyor
while (True):
if (str=="r" or str=="R"):
print("Red")
print("Orange")
print("Green")
print("Blue")
print("Indigo")
print("Violet")
break
else:
print("invalid input")
break
8. Prime number
if num <= 1:
else:
is_prime = True
if num % i == 0:
is_prime = False
break
if is_prime:
else:
def extract_numbers(s):
"""Extract numbers from a string"""
numbers = []
current_number = ''
for char in s:
if char.isdigit():
current_number += char
elif current_number:
numbers.append(int(current_number))
current_number = ''
if current_number:
numbers.append(int(current_number))
return numbers
if __name__ == "__main__":
numbers = extract_numbers(user_input)
if numbers:
total_sum = sum(numbers)
else:
Fat 2 questions
1. Create a program that reads a CSV file and extracts specific columns, then
Solution ->
import csv
reader = csv.DictReader(infile)
writer.writeheader()
writer.writerow(extracted_row)
# Example usage:
input_file = 'industry.csv'
output_file = 'output.csv'
columns_to_extract = [‘industry’]
dictionary.
Solution ->
import json
def json_to_dict(json_file):
data = json.load(file)
return data
# Example usage:
json_file = 'Downloads/example_1.json'
result = json_to_dict(json_file)
3. Develop a function that takes a list of integers and returns a new list
Solution ->
def unique_elements(input_list):
unique_list = []
unique_list.append(item)
seen.add(item)
return unique_list
# Example usage:
input_list = [1, 2, 3, 4, 2, 3, 5, 1]
result = unique_elements(input_list)
print(result)
Solution ->
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
# Example usage:
num = 5
Solution ->
def count_file_stats(file_path):
line_count = 0
word_count = 0
char_count = 0
# Counting lines
line_count += 1
# Counting words
words = line.split()
word_count += len(words)
# Counting characters
char_count += len(line)
# Example usage:
file_path = 'sample.txt'
balanced.
Solution ->
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return self.items == []
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return None
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return None
def is_balanced(parentheses):
stack = Stack()
if char in '([{':
stack.push(char)
if stack.is_empty():
return False
stack.pop()
else:
return False
return stack.is_empty()
# Example usage:
parentheses_str = "[{()}]"
if is_balanced(parentheses_str):
else:
list.
Solution- >
def longest_consecutive_sequence(nums):
if not nums:
return []
nums.sort()
longest_sequence = [nums[0]]
current_sequence = [nums[0]]
for i in range(1, len(nums)):
if nums[i] == nums[i - 1] + 1:
current_sequence.append(nums[i])
else:
longest_sequence = current_sequence
current_sequence = [nums[i]]
longest_sequence = current_sequence
return longest_sequence
# Example usage:
result = longest_consecutive_sequence(nums)
8. Create a program that reads an integer from the user and handles the
def read_integer_from_user():
while True:
try:
user_integer = int(user_input)
return user_integer
except ValueError:
# Example usage:
user_integer = read_integer_from_user()
ZeroDivisionError.
Solution ->