PYTHON_PASS_FINAL
PYTHON_PASS_FINAL
The operator is a symbol which tells the compiler to do specific mathematical function.
In python, a single value with no operators is also considered an expression,
The order of operations of Python math operators is similar to that of mathematics i.e., **, *,
/, //, %, +, -
The associativity is also similar and followed from left to right.
Example:
18%4= 2
ii. 8.8 // 8 = 1.0
iii. (172-80)*10/5 = 184.0
iv. not False= True 5*01mark each
v. 3*1**3 = 3
Introduction to Python Programming
2 Explain Local and Global Scope in Python programs. What are local and global variables? How can you
force a variable in a function to refer to the global variable?
Parameters and variables that are assigned in a called function are said to exist inside
that function‟s local scope.
Variables that are assigned outside all functions are said to exist in the globalscope.
A variable that exists in a local scope is called a local variable, while a variable that exists in the
global scope is called a global variable.
Scopes matter for several reasons:
1. Code in the global scope cannot use any local variables.
2. However, a local scope can access global variables.
3. We can use the same name for different variables if they are in different scopes. That is, there
can be a local variable named spam and a global variable also named spam.
We can force a variable in a function to refer to the global variable using global statement as
shown below:
Program Output
Because eggs is declared global at the top of spam() ❶, when eggs is set to 'spam' ❷, this assignment
is done to the globally scoped eggs. No local eggs variable is created.
1
Introduction to Python Programming
3 What are Comparison and Boolean operators? List all the Comparison and Boolean operators in Python 6
and explain the use of these operators with suitable examples.
Comparison operators: These are used to compare two values and evaluate down to a single
Boolean value.
Boolean Operators: The three Boolean operators (and, or, and not) are used to compare Boolean
values.
and operator: The and operator evaluates an expression to True if both Boolean values are True;
otherwise, it evaluates to False.
ii. or operator: The or operator valuates an expression to True if either of the two Boolean
values is True. If both are False, it evaluates to False.
iii. not operator: The not operator operates on only one Boolean value (or expression).
The not operator simply evaluates to the opposite Boolean value. Much like using double
negatives in speech and writing, you can nest not operators ❶, though there‟s never not
no reason to do this in real programs.
2
Introduction to Python Programming
4 What is Exception Handling? How exceptions are handled in Python? Write a Python program with 6
exception handling code to solve divide-by-zero error situation.
Exception Handling: If we don‟t want to crash the program due to errors instead we want the
program to detect errors, handle them, and then continue to run is called exception handling.
Exceptions can be handled with try and except statements.
The code that could potentially have an error is put in a try clause. The program execution moves
to the start of a following except clause if an error happens.
Lab Program Number 8:
import sys
def DivExp(a,b):
assert a>0, "a should be greater than 0"
try:
c = a/b
except ZeroDivisionError:
print("Value of b cannot be zero")
sys.exit(0)
else:
return c
val1 = int(input("Enter a value for a : "))
val2 = int(input("Enter a value for b : "))
val3 = DivExp(val1, val2)
print(val1, "/", val2, "=", val3)
In the above program if the second number given by the user as input is 0 then, it catches the error
and the exception statement will be printed.
3
Introduction to Python Programming
5 List and explain the syntax of all flow control statements with example.
1. if, else, elif Statements:
if Statements:
An if statement‟s clause (that is, the block following the if statement) will execute if the
statement‟s condition is True. The clause is skipped if the condition is False.
In plain English, an if statement could be read as, “If this condition is true, execute the code in the
clause.”
In Python, an if statement consists of the following:
1. The if keyword
2. A condition (that is, an expression that evaluates to True or False)
3. A colon
4. Starting on the next line, an indented block of code (called the if clause)
Example:
Flowchart:
2. else Statements:
An if clause can optionally be followed by an else statement. The else clause is executed only
when the if statement‟s condition is False.
In plain English, an else statement could be read as, “If this condition is true, execute this code.
Or else, execute that code.”
An else statement doesn‟t have a condition, and in code, an else statement always consists of the
following:
1. The else keyword
2. A colon
3. Starting on the next line, an indented block of code (called the else clause)
Example:
4
Introduction to Python Programming
Flowchart:
3. elif Statements:
Flowchart:
5
Introduction to Python Programming
The first line ❶ creates an infinite loop; it is a while loop whose condition is always True.
The program execution will always enter the loop and will exit it only when a break statement is
executed.
The program asks the user to type name ❷.
While the execution is still inside the while loop, an if statement gets executed ❸ to check
whether name is equal to entered name.
If this condition is True, the break statement is run ❹, and the execution moves out of the loop
to print('Thank you!') ❺.
continue Statement
The continue statement is used to immediately jump back to the start of the loop and reevaluate
the loop‟s condition.
A continue statement simply contains continue keyword.
If the user enters any name besides Joe ❶, the continue statement ❷ causes the program
execution to jump back to the start of the loop.
When it reevaluates the condition, the execution will always enter the loop, since the condition is
simply the value True. Once they make it past that if statement, the user is asked for a password
❸.
If the password entered is swordfish, then the break statement ❹ is run, and the execution jumps
out of the while loop to print Access granted ❺.
6
Introduction to Python Programming
7 What are user defined functions? How can we pass parameters in user defined functions? Explain with 7
suitable example.
User defined functions are the mini-programs written by the user to do some specifictask.
The functions always start with the keyword “def”.
We can pass parameters to the user defined functions as shownbelow:
The definition of the hello() function in this program has a parameter called name❶.
A parameter is a variable that an argument is stored in a function. The first time the hello()
function is called, it‟s with the argument 'Alice' ❸.
The program execution enters the function, and the variable name is automatically set to 'Alice',
which is what gets printed by the print() statement ❷.
7
Introduction to Python Programming
9 Make use of necessary examples to explain print(), input(), int(), float() and str()
The input() function waits for the user to type some text on the keyboard and press enter.
Ex: myName = input().
This function call evaluates to a string equal to the user’s text, and the previous line of code
assigns the myName variable to this string value.
Output: myName
The print() function contains the expression between the parentheses. Expressions always evaluate
to a single value.
Ex: myName= Alice
print('It is good to meet you, ' + myName)
Output: ‘It is good to meet you, Alice’.
The str() function will evaluate to the string form of the value passed to it.
Ex: str(29)
Output= ‘29’
The str() function is useful when you have an integer or float that you want to link to a string.
The int() function will evaluate to the integer form of the value passed to it.
Ex: int(42.7)
Output=42
If we pass a value to int() that it cannot evaluate as an integer, Python will display an error
message.
Ex: int(‘92.7’)
ValueError: invalid literal for int() with base 10: '99.99'
float() function will evaluate to the and floating-point form of the value passed to it.
Ex: float(10)
float(‘10’)
Output=10.0
8
Introduction to Python Programming
10 To demonstrate the use of the keywords break and continue in While loop.
9
Introduction to Python Programming
1
Introduction to Python Programming
Attempting to delete a value that does not exist in the list will result in a ValueErrorerror.
If the value appears multiple times in the list, only the first instance of the value will be removed.
Lists of number values or lists of strings can be sorted with the() method.
Retrieves last value.
Example:
2
Introduction to Python Programming
(i) get( ): Dictionaries have a get() method that takes two arguments:
The key of the value to retrieve
A fallback value to return if that key does not exist.
(ii) items( ): This method returns the dictionary values and keys in the form of tuples.
Ex: spam = {"color’ : "red’ , "age’ : 27}
for i in spam.items( ):
print(i)
Output: ("color’, ‘red’)
(‘age’, 27)
4
Introduction to Python Programming
3 Explain the various string methods for the following operations with examples. 6
(i) Removing whitespace characters from the beginning, end or both sides of a string.
(ii) To right-justify, left-justify, and center a string.
i) Removing whitespace characters from the beginning, end or both sides of a string.
The strip() string method will return a new string without any whitespace characters at the
beginning or end.
The lstrip() and rstrip() methods will remove whitespace characters from the left and right ends,
respectively.
The rjust() and ljust() string methods return a padded version of the string they are called on, with
spaces inserted to justify the text.
The first argument to both methods is an integer length for the justified string.
An optional second argument to rjust() and ljust() will specify a fill character other than a space
character.
The center() string method works like ljust() and rjust() but centers the text rather than justifying
it to the left or right.
5
Introduction to Python Programming
Here, the list is created, and assigned reference to it in the spam variable.
In the next line copies only the list reference in spam to cheese, not the list value itself. This means
the values stored in spam and cheese now both refer to the same list.
When a function is called, the values of the arguments are copied to the parameter variables.
when eggs() is called, a return value is not used to assign a new value to spam.
Even though spam and some Parameters contain separate references, they both refer to the
same list.
This is why the append('Hello') method call inside the function affects the list even after the function
call has returned.
6
Introduction to Python Programming
6 What is dictionary? How it is different from list? Write a program to count the number of 7
occurrences of character in a string.
Dictionary: A dictionary is a collection of many values. Indexes for dictionaries can use many
different data types, not just integers. Indexes for dictionaries are called keys, and a key with its
associated value is called a key-value pair. A dictionary is typed with braces, {}.
7
Introduction to Python Programming
7 Explain the following string methods with code snippets: i) join() ii) islower() iii) strip() iv) centre() v) sp
i) join() :The join() method is called on a string, gets passed a list of strings, and returns a string.
>>> ', '.join(['cats', 'rats', 'bats'])
'cats, rats, bats'
>>> ' '.join(['My', 'name', 'is', 'Simon'])
'My name is Simon'
ii) islower() : will return a Boolean True value if the string has at least one letter and all the letters are
lowercase
>>> spam = 'Hello, world!'
>>> spam.islower()
False
iii) strip() : The strip() string method will return a new string without any whitespace characters at
the beginning or end.
>>> spam = ' Hello, World '
>>> spam.strip()
'Hello, World'
iv) centre() : The center() string method works like ljust() and rjust() but centers the text rather
than justifying it to the left or right.
>>> 'Hello'.center(20)
' Hello '
>>> 'Hello'.center(20, '=')
'=======Hello========'
v) split():The split() method does the opposite: It’s called on a string value and returns a list of strings.
>>> 'My name is Simon'.split() ['My', 'name', 'is', 'Simon']
8
Introduction to Python Programming
i) upper( ): This method is used to convert lower case characters into uppercase characters.
Ex: x = 'Python'
x = x.upper( )
PYTHON
ii) lower( ): This method is used to convert upper case characters into lower casecharacters.
Ex: x = 'Python'
x = x.lower( )
python
iii) isupper( ): This method is used to check whether a string has at least one letter or complete
string is upper or not. It returns Boolean value.
Ex: x = 'Python'
x = x.isupper( )
TRUE
Ex: y = 'python'
y = y.isupper( )
FALSE
iv) islower( ): This method is used to check whether a string has at least one letter or complete
string is lower or not. It returns Boolean value.
Ex: x = 'Python'
x = x.islower( )
TRUE
Ex: y= 'PYTHON'
y = y.isupper( )
TRUE
v) isspace( ): Returns True if the string consists only of spaces, tabs, and newlines and is not
blank.
Ex: ' '.isspace( )
TRUE
vi) isalnum( ): Returns True if the string consists only of letters and numbers and is not blank.
Ex: 'hello123‟.isalnum( )
TRUE
Ex: ' '.isalnum( )
FALSE
1
Introduction to Python Programming
2 Describe the difference between Python os and os.path modules. Also, discuss the following 7
methods of os module
a) chdir() b) rmdir() c) walk() d) listdir() e) getcwd()
os module It is from the standard library and it provides a portable way of accessing and using
operating system dependent functionality.
os.path module It is used to manipulate the file and directory paths and path names.
a) chdir( ) This method is used to change from current working directory to the required
directory.
Ex: import os
os.chdir(“C:\\Windows\\System”)
b) rmdir( ) This method is used to delete the folder at path. This folder must not contain any
files or folders.
c) walk( ) This method is used to access or do any operation on each file in a folder.
Ex: import os
for foldername, subfolder, filenames in os.walk(“C:\\Windows\\System”)
print(“The current folder is “+foldername)
d) listdir( ) This method returns a list containing the names of the entries in the directory
given by path.
Ex: import os
os.getcwd( )
3
Introduction to Python Programming
3 Demonstrate shutil module the copy, move, rename and delete functions of with Python code 7
snippet.
Copy: shutil.copy(source, destination) will copy the file from source path to destination path.
Move: shutil.move(source, destination) will move the file or folder from source path to
the destination path and will return a string of the absolute path of the new location.
Delete: We can delete a single file or a single empty folder with functions in the os
module, whereas to delete a folder and all of its contents, we use the shutil module.
1. Calling os.unlink(path) will delete the file at path.
2. Calling os.rmdir(path) will delete the folder at path. This folder must be empty
of any files or folders.
3. Calling shutil.rmtree(path) will remove the folder at path, and all files and
folders it contains will also be deleted.
Ex: import os
for filename in in os.listdir( ):
if filename.endswith(„.txt‟):
os.unlink(filename)
4
Introduction to Python Programming
4 Explain the file Reading/Writing process with suitable Python Program. 6
Reading File: read( ) and readlines( ) methods are used to read the contents of a file. read( ) method
reads the contents of a file as a single string value whereas readlines( ) method reads each line as a
string value.
Ex:
Writing File: The file must be opened in order to write the contents to a file. It can be done in two
ways: wither in write mode or append mode. In write mode the contents of the existing file will be
overwritten whereas in append mode the contents will be added at the end of existing file.
Ex: In the below example bacon.txt file is opened in write mode hence, all the contents will be
deleted and Hello world! Will be written.
Introduction to Python Programming
Raising Exeptions: Python raises an exception whenever it tries to execute invalid code. Raising
an exception is a way of saying, “Stop running the code in this function and move the program
execution to the except statement.”
Exceptions are raised with a raise statement.
\
Introduction to Python Programming (MODULE-4)
2 With code snippet, explain reading, extracting and creating ZIP files. 6
To create our own compressed ZIP files, must open the ZipFile object in write mode by
passing 'w' as the second argument.
The write() method‟s first argument is a string of the filename to add.
The second argument is the compression type parameter, which tells the computer what algorithm
it should use to compress the files.
The extractall() method for ZipFile objects extracts all the files and folders from a ZIP file into the
current working directory.
After running the below code, the contents of example.zip will be extracted to C:\ drive.
The extract() method for ZipFile objects will extract a single file from the ZIPfile.
The os.walk() function is passed a single string value: the path of a folder. You can use os.walk() in
a for loop statement to walk a directory tree, the os.walk() function will return three values on
each iteration through the loop:
1. A string of the current folder’s name
2. A list of strings of the folders in the current folder
3. A list of strings of the files in the current folder
Example:
import os
for folderName, subfolders, filenames in os.walk('C:\\delicious'):
print('The current folder is ' + folderName)
for subfolder in subfolders:
print('SUBFOLDER OF ' + folderName + ': ' + subfolder)
for filename in filenames:
print('FILE INSIDE ' + folderName + ': '+ filename)
print('')
Introduction to Python Programming
MODULE 5
1 Define classes and objects in Python. Create a class called Employee and initialize it with 8
employee id and name. Design methods to:
i) setAge_to assign age to employee.
ii) setSalary_to assign salary to the employee.
iii) Display_to display all information of the employee.
def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]
def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
Introduction to Python Programming
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print("%15s"%("NAME"), "%12s"%("USN"),
"%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL","%12s"%("P
ERCENTAGE"))
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn,
"%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.score[3],"%12.2f"
%percentage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()
Ex: In the below example the object start has been passed as parameters and it has been changed by
adding seconds to it. Hence, it is a modifier.
Introduction to Python Programming
init : The init method (short for “initialization”) is a special method that gets invoked when an
object is instantiated. The parameters of init to have the same names as the attributes.
str : It is a special method which returns a string representation after “initialization of an object.
def getMarks(self):
self.name = input("Enter student Name : ")
self.usn = input("Enter student USN : ")
self.score[0] = int(input("Enter marks in Subject 1 : "))
self.score[1] = int(input("Enter marks in Subject 2 : "))
self.score[2] = int(input("Enter marks in Subject 3 : "))
self.score[3] = self.score[0] + self.score[1] + self.score[2]
def display(self):
percentage = self.score[3]/3
spcstr = "=" * 81
print(spcstr)
print("SCORE CARD DETAILS".center(81))
print(spcstr)
print("%15s"%("NAME"), "%12s"%("USN"),
"%8s"%"MARKS1","%8s"%"MARKS2","%8s"%"MARKS3","%8s"%"TOTAL","%12s"%("PE
RCENTAGE"))
print(spcstr)
print("%15s"%self.name, "%12s"%self.usn,
"%8d"%self.score[0],"%8d"%self.score[1],"%8d"%self.score[2],"%8d"%self.score[3],"%12.2f"
%percentage)
print(spcstr)
def main():
s1 = Student()
s1.getMarks()
s1.display()
main()
Introduction to Python Programming
4 Explain operator overloading with example. 7
Operator Overloading: Ability of an existing to work on user defined data type. It is a
polymorphic nature of any object oriented programming. Basic operators like +, -, * can
b overloaded. Here, the behavior of an operator is changed like + so it works with a user
defined type.
Ex: + _ _ add _ _ - _ _sub_ _ * _ _ mul_ _
myList = []
num = int(input("Enter the number of elements in your list : "))
for i in range(num):
val = int(input("Enter the element : "))
myList.append(val)
total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)
stdDev = sqrt(variance)
Pure Function: It does not modify any of the objects passed to it as arguments and it has no effect,
like displaying a value or getting user input, other than returning a value.
Ex: In the below example the two objects start and duration have been passed as parameters to
function add_time and it doesn‟t modify the objects received. Hence, it is a pure function.