[go: up one dir, main page]

0% found this document useful (0 votes)
91 views30 pages

PYTHON_PASS_FINAL

Uploaded by

ananya.shdeepak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views30 pages

PYTHON_PASS_FINAL

Uploaded by

ananya.shdeepak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 30

Introduction to Python Programming

Module wise Questions & Solutions


Placement.docx MODULE 1
Describe the math operators in Python from highest to lowest Precedence with an example for each. 6
1 Write the steps how Python is evaluating the expression (5 - 1) * ((7 + 1) / (3 - 1)) and reduces it to a
single value.

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

 The steps for evaluating the expression in Python are as follows:

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:

 If we have more than one condition then elif statement is used.


 The elif statement is an “else if” statement that always follows an if or another elif statement.
 It provides another condition that is checked only if all of the previous conditions were False.
 In code, an elif statement always consists of the following:
1. The elif 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 elif clause)

 Flowchart:

5
Introduction to Python Programming

6 Illustrate the use of break and continue with a code snippet. 6


break Statement
 The break statement is used to immediately exit from the loop.
 A break statement simply contains the break keyword.


 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 ❷.

8 Explain index ( ), insert ( ), sort ( ) and remove ( ) methods with examples 8


index(): List values have an index() method that can be passed a value, and if that value exists in the
list, the index of the value is returned. If the value isn’t in the list, then Python produces a ValueError
error. When there are duplicates of the value in the list, the index of its first appearance is returned
fruits = [4, 55, 64, 32, 16, 32]
x = fruits.index(32)
print(x)
3
insert ( ): The insert() method can insert a value at any index in the list.
fruits = ['apple', 'banana', 'cherry']
fruits.insert(1, "orange")
print(fruits)
['apple', 'orange', 'banana', 'cherry']
sort ( ): Lists of number values or lists of strings can be sorted with the sort() method.
cars = ['Ford', 'BMW', 'Volvo']
cars.sort()
print(cars)
['BMW', 'Ford', 'Volvo']
remove ( ): The remove() method is passed the value to be removed from the list it is called on.
fruits = ['apple', 'banana', 'cherry']
fruits.remove("banana")
print(fruits)
['apple', 'cherry']

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

Module wise Questions & Solutions


MODULE 2
1 Explain the methods of List data type in Python for the following operations with suitable code 8
snippets for each.
(i) Adding values to a list ii) Removing values from a list
(iii) Finding a value in a list iv) Sorting the values in a list
i) Adding values to a list:
 To add new values to a list, the append() and insert() methods can be used.
 The append() method adds the argument to the end of the list.

 The insert() method insert a value at any index in the list.


 The first argument to insert() is the index for the new value, and the second argument is the new
value to be inserted.

1
Introduction to Python Programming

ii) Removing values from a list:


 To remove values from a list, the remove( ) and del( ) methods can be used.
 The del statement is used when we know the index of the value we want to remove from the list.
 The remove() method is used when we know the value we want to remove from the list.

 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.

iii) Finding a value in a list:


 To find a value in a list we can use index value.
 The first value in the list is at index 0, the second value is at index 1, and the third value is at
index 2, and so on. The negative indexes can also be used.
 The expression 'Hello ' + spam[0] evaluates to 'Hello ' + 'cat' because spam[0] evaluates to the
string 'cat'. This expression in turn evaluates to the string value 'Hello cat'.
Negative index  spam[-1]

iv) Sorting the values in a list

 Lists of number values or lists of strings can be sorted with the() method.
  Retrieves last value.
 Example:

2
Introduction to Python Programming

2 Discuss the following Dictionary methods in Python with examples. 8


(i) get() (ii) items() (iii) keys() (iv) values() v) setdefault()

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

(iii) keys( ): This method returns the dictionary keys.


Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.keys( ):
print(i)
Output: color
age
iv) values( ): This method returns the dictionary values.
Ex: spam = {‘color’ : ‘red’ , ‘age’ : 27}
for i in spam.values( ):
print(i)
Output: red 27
v. setdefault()to set a value in a dictionary for a certain key only if that key does not already have a
value
spam = {'name': 'Pooka', 'age': 5}
if 'color' not in spam:
spam['color'] = 'black'

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.

ii) To right-justify, left-justify, and center a string.

 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

4 What is list? Explain the concept of list slicing with example. 6


List: A list is a value that contains multiple values in an ordered sequence.
Slicing: Extracting a substring from a string is called substring.
Example:

5 Explain references with example. 7


 Reference: A reference is a value that points to some bit of data, and a list reference is a value
that points to a list.

 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, {}.

The dictionary is different from list data type:


 In lists the items are ordered and in dictionaries the items are unordered.
 The first item in a list exists. But there is no “first” item in adictionary.
 The order of items matters for determining whether two lists are the same, it does not matter in
what order the key-value pairs are typed in a dictionary.

Lab Program Number 4:


num = input("Enter a number : ")
print("The number entered is :", num)
uniqDig = set(num)
for elem in uniqDig:
print(elem, "occurs", num.count(elem), "times")

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

Module wise Questions & Solutions


MODULE 3
1 List any six methods associated with string and explain each of them with example. 8

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.

e) getcwd( )  This method is used to get the current working directory.

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.

In the above example:


1  Destination is a folder, hence the source file is copied to destinationfile.
2  Destination is a folder with a filename, hence the source file copied will be
renamed to the given filename.

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.

Rename: shutil.move(source, destination) can be used to move and rename also.

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

5 Briefly explain assertions and raising an exception.


Assertions: An assertion is a sanity check to make sure your code isn’t doing something obviously
wrong. These sanity checks are performed by assert statements. If the sanity check fails, then an
AssertionError exception is raised.

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.

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.
Introduction to Python Programming (MODULE-4)

1 How do we specify and handle absolute, relative paths? 10

 There are two ways to specify a file path.


1. An absolute path, which always begins with the root folder
2. A relative path, which is relative to the program‟s current working directory
 The os.path module provides functions for returning the absolute path of a relative path and for
checking whether a given path is an absolute path.
1. Calling os.path.abspath(path) will return a string of the absolute path of the argument. This is
an easy way to convert a relative path into an absolute one.
2. Calling os.path.isabs(path) will return True if the argument is an absolute path and False if it
is a relative path.
3. Calling os.path.relpath(path, start) will return a string of a relative path from the start path
to path. If start is not provided, the current working directory is used as the start path.

 \
Introduction to Python Programming (MODULE-4)

2 With code snippet, explain reading, extracting and creating ZIP files. 6

Reading ZIP Files:

 To read the contents of a ZIP file, ZipFile object must be created.


 ZipFile objects are values through which the program interacts with the file.
 To create a ZipFile object, the zipfile.ZipFile() function is called, passing it a string of
the .zip file‟s filename.

Creating ZIP Files:

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

Extracting ZIP 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.

WRITE LAB MANUAL PROGRAM NUMBER 7


3 Benefits of Compressing Files:
i) Compressing a file reduces its size, which is useful when transferring it over the Internet.
ii) ZIP file can also contain multiple files and subfolders, it’s a handy way to package several
files into one.
A ZipFile object has a namelist() method that returns a list of strings for all the files and folders
contained in the ZIP file.
These strings can be passed to the getinfo() ZipFile method to return a ZipInfo object about that
particular file.
ZipInfo objects have their own attributes, such as file_size and compress_size in bytes, which hold
integers of the original file size and compressed file size, respectively.

4 Walking a Directory Tree:


We want to rename every file in some folder and also every file in every subfolder of that
folder. That is, you want to walk through the directory tree, touching each file as you go.

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.

Lab Program Number 10:


class Student:
def __init__(self, name = "", usn = "", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score

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

Illustrate the concept of modifier with Python code.


2
Modifiers: It modifies the objects passed to it as arguments and it has effect.

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

3 Explain init and str method with an example Python Program. 7

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.

Lab Program Number 10:


class Student:
def __init__(self, name = "", usn = "", score = [0,0,0,0]):
self.name = name
self.usn = usn
self.score = score

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_ _

Lab Program Number 3:

from math import sqrt

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)

print('The length of list1 is', len(myList))

print('List Contents', myList)


total = 0
for elem in myList:
total += elem
mean = total / num

total = 0
for elem in myList:
total += (elem - mean) * (elem - mean)

variance = total / num

stdDev = sqrt(variance)

print("Mean =", mean)


print("Variance =", variance)
print("Standard Deviation =", "%.2f"%stdDev)
Introduction to Python Programming
5 Illustrate the concept of pure function with Python code.

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.

You might also like