0% found this document useful (0 votes)
17 views25 pages

Python Code and Theory

Uploaded by

gta579035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
17 views25 pages

Python Code and Theory

Uploaded by

gta579035
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 25

Exception Handling

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.

• TypeError: This exception is raised when an operation or function is applied to an object of


the wrong type, such as adding a string to an integer.

• 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.

• KeyError: This exception is raised when a key is not found in a dictionary.

• 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.

• AttributeError: This exception is raised when an attribute or method is not found on an


object, such as trying to access a non-existent attribute of a class instance.

• IOError: This exception is raised when an I/O operation, such as reading or writing a file, fails
due to an input/output error.

• ZeroDivisionError: This exception is raised when an attempt is made to divide a number by


zero.

• 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.

In Python, we can define a module in one of 3 ways

o Python itself allows for the creation of modules.


o Similar to the re (regular expression) module, a module can be primarily written in C
programming language and then dynamically inserted at run-time.

o A built-in module, such as the itertools module, is inherently included in the interpreter.

A module is a file containing Python code, definitions of functions, statements, or classes. An


example_module.py file is a module we will create and whose name is example_module.

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.

# defining a function in the module to reuse it

def square( number ):

# here, the above function will square the number passed as the input

result = number ** 2

return result # here, we are returning the result of the function

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.

Python Lambda Function Syntax

Syntax: lambda arguments : expression

• 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.

Python Lambda Function Example

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'

upper = lambda string: string.upper()

print(upper(str1))

LISTS, TUPLES, DICTIONARIES

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

comprehension; Dictionaries: operations and methods, comprehension;

Lists, Tuples, Dictionaries:

List:

It is a general purpose most widely used in data structures

List is a collection which is ordered and changeable and allows duplicate members.

(Grow and shrink as needed, sequence type, sortable).

To use a list, you must declare it first. Do this using square brackets and separate

values with commas.

We can construct / create list in many ways.

List operations:

These operations include indexing, slicing, adding, multiplying, and checking for

membership

Basic List Operations:

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()

Delete: Delete a list or an item from a list

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.

4. Aliasing happens whenever one variable’s value is assigned to another variable.

Tuples:

A tuple is a collection which is ordered and unchangeable. In Python tuples are written

with round brackets.

Supports all operations for sequences.

Immutable, but member objects may be mutable.

If the contents of a list shouldn’t change, use a tuple to prevent items from accidently being
added, changed, or deleted.

Tuples are more efficient than list due to python’s implementation

Some of the operations of tuple are:

Access tuple items

Change tuple items

Loop through a tuple

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

We can construct or create dictionary like:

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

the storage method for each of them.

Int:

Int, or integer, is a whole number, positive or negative, without decimals, of unlimited

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:

1. Strings in Python are identified as a contiguous set of characters represented in the

quotation marks. Python allows for either pairs of single or double quotes.

• 'hello' is the same as "hello".

• Strings can be output to screen using the print function. For example: print("hello").

>>> print("mrcet college")

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

double quotes and vice versa:

>>> print("mrcet is an autonomous (') college")

mrcet is an autonomous (') college

Suppressing Special Character:

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:

>>> print("mrcet is an autonomous (\') college")

mrcet is an autonomous (') college

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

makes code reusable.

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.

Ex: abs(),all().ascii(),bool()………so on….


integer = -20

print('Absolute value of -20 is:', abs(integer))

Output:

Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.

def add_numbers(x,y):

sum = x + y

return sum

print("The sum is", add_numbers(5, 20))

Output:

The sum is 25

Function definition consists of following components:

1. Keyword def indicates the start of function header.

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.

4. A colon (:) to mark the end of function header.

5. Optional documentation string (docstring) to describe what the function does.

6. One or more valid python statements that make up the function body. Statements must have

same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function

def hf():

print("hw")

print("gh kfjg 66666")

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

function, then the function will return the None object.

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.

>>> wish("MRCET") # only one argument

TypeError: wish() missing 1 required positional argument: 'msg'

>>> wish() # no arguments

TypeError: wish() missing 2 required positional arguments: 'name' and 'msg'

#Keyword Arguments

When we call a function with some values, these values get assigned to the arguments

according to their position.

Python allows functions to be called using keyword arguments. When we call functions in

this way, the order (position) of the arguments can be changed.

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

Function arguments can have default values in Python.

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.

This means to say, non-default arguments cannot follow default arguments.

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

variable-length arguments also called arbitrary arguments.

For this an asterisk (*) is placed before a parameter in function definition which can hold

non-keyworded variable-length arguments and a double asterisk (**) is placed before a

parameter in function which can hold keyworded variable-length arguments.

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

a dictionary called ‘var’.

#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

r=int(input("Enter radius of circle"))

print(areaOfCircle(r))

Conditional (if):

The if statement contains a logical expression using which data is compared and a decision

is made based on the result of the comparison.

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

code after the end of the if statement(s) is executed.

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

resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else

Statement following if.

Syntax of if - else :

if test expression:

Body of if stmts

else:

Body of else stmts

Chained Conditional: (If-elif-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

statement, there can be an arbitrary number of elif statements following an if.

Syntax of if – elif - else :

If test expression:

Body of if stmts

elif test expression:

Body of elif stmts

else:

Body of else stmts

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:

In Python Iteration (Loops) statements are of three types:

1. While Loop

2. For Loop

3. Nested For Loops

While loop:

Loops are either infinite or conditional. Python while loop keeps reiterating a block of

code defined inside it until the desired condition is met.

The while loop contains a boolean expression and the code inside the loop is

repeatedly executed as long as the boolean expression is true.

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.

Python For Loop Syntax

for var in iterable:


# statements

Note: In Python, for loops only implement the collection-based iteration.

Here we will see Python for loop examples with different types of iterables:

Python For Loop with String

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

# Iterating over a String

print("String Iteration")

s = "Geeks"

for i in s:

print(i)

Output:

String Iteration
G
e
e
k
s

Python for loop with Range

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

for i in range(0, 10, 2):

print(i)

Output :

0
2
4
6
8

Iterating over a list:

#list of items

list = ['M','R','C','E','T']

i=1

#Iterating over the list


for item in list:

print ('college ',i,' is ',item)

i = i+1

Iterating over a Tuple:

tuple = (2,3,5,7)

print ('These are the first four prime numbers ')

#Iterating over the tuple

for a in tuple:

print (a)

Iterating over a dictionary:

#creating a dictionary

college = {"ces":"block1","it":"block2","ece":"block3"}

#Iterating over the dictionary to print keys

print ('Keys are:')

for keys in college:

print (keys)

#Iterating over the dictionary to print values

print ('Values are:')

for blocks in college.values():

print(blocks)

Iterating over a String:

#declare a string to iterate over

college = 'MRCET'

#Iterating over the string

for name in college:

print (name)

Nested For loop:

When one Loop defined within another Loop is called Nested Loops.

Syntax:

for val in sequence:

for val in sequence:


48

statements

statements

# Example 2 of Nested For Loops (Pattern Programs)

for i in range(1,6):

for j in range(5,i-1,-1):

print(i, end=" ")

print('')

String slices:

A segment of a string is called a slice. Selecting a slice is similar to selecting a character:

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.

Slice out substrings, sub lists, sub Tuples using index.

Syntax:[Start: stop: steps]

Slicing will start from index and will go up to stop in step of steps.

Default value of start is 0,

65

Stop is last index of list

And for step default is 1

For example 1−

str = 'Hello World!'

print str # Prints complete string

print str[0] # Prints first character of the string

print str[2:5] # Prints characters starting from 3rd to 5th

print str[2:] # Prints string starting from 3rd character print

str * 2 # Prints string two times

print str + "TEST" # Prints concatenated string


Python codes

1. Correct word

string = input("Enter a string: ")

# replaced_string = replace_consecutive(user_input)

#def replace_consecutive(string):

"""Replace consecutive same alphabets with two alphabets"""

result = ''

i=0

while i < len(string):

count = 1

while i + 1 < len(string) and string[i] == string[i + 1]:

count += 1

i += 1

if count >= 3:

result += string[i] * 2

else:

result += string[i] * count

i += 1

print("String after replacement:", result)

2. Division

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

d=int(input("Enter the number divisor:"))

while(num):

if(d==0):

print("cannot divide by 0!")

break

else:

result=num/d

print(result)
break

3. Fibonacci series

range_limit = int(input("Enter the range limit: "))

print("Fibonacci series up to", range_limit, "is:")

fibonacci_series = []

a, b = 0, 1

while a <= range_limit:

fibonacci_series.append(a)

a, b = b, a + b

print(fibonacci_series)

4. For loop

str="BBA-CA 3"

for i in str:

print(i, end=" ")

print()

print("outside of for loop")

5. Magic number

# Take input date

date = input("Enter a date (DD-MM-YYYY format): ")

# Initialize sum

sum = 0

# Iterate through each character in the input date

for char in date:

# Check if the character is a digit

if char.isdigit():

# Convert the digit character to integer and add it to the sum


sum += int(char)

# Repeat the process until you get a single-digit output

while sum >= 10:

temp_sum = 0

while sum > 0:

temp_sum += sum % 10

sum //= 10

sum = temp_sum

print("Sum of Digits:", 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):

str=input("Enter a single characeter: ")

if (str=="r" or str=="R"):

print("Red")

elif (str=="o" or str=="O"):

print("Orange")

elif (str=="y" or str=="Y"):


print("Yellow")

elif (str=="g" or str=="G"):

print("Green")

elif (str=="b" or str=="B"):

print("Blue")

elif (str=="i" or str=="I"):

print("Indigo")

elif (str=="v" or str=="V"):

print("Violet")

elif (str=="q" or str=="Q"):

break

else:

print("invalid input")

break

8. Prime number

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

if num <= 1:

print(num, "is not a prime number.")

else:

is_prime = True

for i in range(2, int(num**0.5) + 1):

if num % i == 0:

is_prime = False

break

if is_prime:

print(num, "is a prime number.")

else:

print(num, "is not a prime number.")

9. Check numbers in a string, add them, display sum as output

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__":

user_input = input("Enter a string: ")

numbers = extract_numbers(user_input)

if numbers:

total_sum = sum(numbers)

print("Sum of numbers in the string:", total_sum)

else:

print("No numbers found in the string.")

Fat 2 questions

1. Create a program that reads a CSV file and extracts specific columns, then

writes the extracted data to a new CSV file.

Solution ->

import csv

def extract_columns(input_file, output_file, columns):

with open(input_file, 'r', newline='') as infile, open(output_file, 'w',


newline='') as outfile:

reader = csv.DictReader(infile)

writer = csv.DictWriter(outfile, fieldnames=columns)

writer.writeheader()

for row in reader:

extracted_row = {col: row[col] for col in columns}

writer.writerow(extracted_row)

# Example usage:

input_file = 'industry.csv'

output_file = 'output.csv'

columns_to_extract = [‘industry’]

extract_columns(input_file, output_file, columns_to_extract)

2. Develop a program that reads a JSON file and converts it to a Python

dictionary.

Solution ->

import json

def json_to_dict(json_file):

with open(json_file, 'r') as file:

data = json.load(file)

return data

# Example usage:

json_file = 'Downloads/example_1.json'

result = json_to_dict(json_file)

print(result) # This will print the converted Python dictionary

3. Develop a function that takes a list of integers and returns a new list

containing only the unique elements, preserving their order.

Solution ->

def unique_elements(input_list):

unique_list = []

seen = set() # To keep track of elements seen so far

for item in input_list:


if item not in seen:

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)

4. Develop a program to find the factorial of a given number using recursion.

Solution ->

def factorial(n):

# Base case: factorial of 0 or 1 is 1

if n == 0 or n == 1:

return 1

# Recursive case: factorial of n is n * factorial(n-1)

else:

return n * factorial(n - 1)

# Example usage:

num = 5

print("Factorial of", num, "is:", factorial(num))

5. Write a Python program to count the number of lines, words, and

characters in a text file.

Solution ->

def count_file_stats(file_path):

line_count = 0

word_count = 0

char_count = 0

with open(file_path, 'r') as file:

for line in file:

# Counting lines

line_count += 1
# Counting words

words = line.split()

word_count += len(words)

# Counting characters

char_count += len(line)

return line_count, word_count, char_count

# Example usage:

file_path = 'sample.txt'

lines, words, characters = count_file_stats(file_path)

print("Number of lines:", lines)

print("Number of words:", words)

print("Number of characters:", characters)

6. Implement a stack and use it to check if a given string of parentheses is

balanced.

Solution ->

class Stack:

def __init__(self):

self.items = []

def is_empty(self):

return self.items == []

def push(self, item):

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()

for char in parentheses:

if char in '([{':

stack.push(char)

elif char in ')]}':

if stack.is_empty():

return False

elif (char == ')' and stack.peek() == '(') or \

(char == ']' and stack.peek() == '[') or \

(char == '}' and stack.peek() == '{'):

stack.pop()

else:

return False

return stack.is_empty()

# Example usage:

parentheses_str = "[{()}]"

if is_balanced(parentheses_str):

print("The parentheses are balanced.")

else:

print("The parentheses are not balanced.")

7. Write a program to find the longest consecutive sequence of numbers in a

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:

if len(current_sequence) > len(longest_sequence):

longest_sequence = current_sequence

current_sequence = [nums[i]]

if len(current_sequence) > len(longest_sequence):

longest_sequence = current_sequence

return longest_sequence

# Example usage:

nums = [100, 4, 200, 1, 3, 2, 5, 6, 7, 8, 9]

result = longest_consecutive_sequence(nums)

print("Longest consecutive sequence:", result)

8. Create a program that reads an integer from the user and handles the

ValueError if the input is not an integer.

def read_integer_from_user():

while True:

try:

user_input = input("Please enter an integer: ")

user_integer = int(user_input)

return user_integer

except ValueError:

print("Invalid input! Please enter an integer.")

# Example usage:

user_integer = read_integer_from_user()

print("You entered:", user_integer)

9. Write a function that divides two numbers and handles the

ZeroDivisionError.

Solution ->

def safe_divide(a, b):

You might also like