0% found this document useful (0 votes)
252 views99 pages

PythonQB Complete BESANT

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)
252 views99 pages

PythonQB Complete BESANT

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/ 99

Python Programming, ii BCa , 4 SEm th

BWC, mangalorE

Unit - i

Two Mark questions


1.How to write a comment line in Python? Mention two types.
A comment is a text that describes what the program or a particular part of the program is trying to do
and is ignored by the Python interpreter.
Python uses two types of comments: single-line comment and multiline comments.

1) Single Line Comment : the hash (#) symbol is used to comment a single line.
Eg: #This is single line Python comment

2) Multiline comments : the hash(#) or triple triple quotes, either ''' or """ (three single quotes or
three double quotes are used to comment multiple line.

2.What is Python Virtual Machine?


The Python Virtual Machine (PVM) converts byte code instructions into machine code so that the
computer can execute those machines instructions and display the final output. To carry out this
conversion the PVM is equipped with an interpreter. The interpreter converts byte code to machine code
and sends it to the processor for execution.

3. List any four flavors of Python.


1) CPython : This standard python compiler is implemented in C language. Python program is
internally converted into bytecode using C functions. This byte is run on PVM created in C
language. The advantage is that it is possible to execute C and C++ functions and programs in
CPython.
2) Jython: Earlier known as JPython. This is the implementation of Python programming language
which is designed to run on the Java platform. Jython compiler first compiles the python program
into Java byte code. This byte code is executed by Java Virtual Machine (JVM) to produce the
output. Jython contains libraries which are useful for both python and Java programmers.
3) IronPython: This is the implementation of Python programming language in .NET framework.
This is written in C# language. The Python program when compiled gives an intermediate
language(IL) which runs on Common Language Runtime (CLR) to produce the output. This
flavor of python gives flexibility of using both .NET and python libraries.
4) RubyPython: This is a bridge between Ruby and Python interpreters. It encloses a python
interpreter inside Ruby applications.
5) AnacondaPython: When python is redeveloped for handling large-scale data processing,
predictive analytics and scientific computing, it is called AnacondaPython. This implementation
mainly focuses on large scale of data.

4.Give 2 step process of Python program execution


The following are the steps in executing a python program:
1) Type the Source code: Every python program is typed with an extension .py. After typing the
program, the next step is to compile the program using python compiler.

1
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

2) Compile and run the program:


The complier converts the python code to byte codeByte instructions are system(platform)
independent. The size of each byte code is 1 byte. Byte code instructions are contained in
.pyc file.
PVM uses an interpreter to understand the bytecode and converts it into machine code.
These machine codes are then executed by the processor and results are displayed.

5.List any four standard datatypes supported by Python.


Data types specify the type of data like numbers and characters to be stored and manipulated within a
program. Basic data types of Python are:
1) Numbers : Integers, floating point numbers and complex numbers fall under Python numbers
category.
Eg: a=34, b=89.72
2) Boolean: It represents boolean datatype. There are only two boolean values True and False.
Eg: x =False
3) Strings: A string consists of a sequence of one or more characters, which can include letters,
numbers, and other types of characters. Strings are enclosed within single quotes or doubles
quotes.
Eg: subject = “Maths”
4) None: None is another special data type in Python. None is frequently used to represent then
absence of a value
Eg: money = None

6.How to determine the data type of a variable? Give the syntax and example
The type() function returns the data type of the given object.
The syntax for type() function is,
type(object)
Eg:
print(type(17))
print(type("A"))
print(type(4+9j))

OUTPUT
<class 'int'>
<class 'str'>
<class 'complex'>

2
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

7.What is the purpose of membership operators? Give example


Membership operators are useful to test for membership in a sequence such as list, tuples, string or
dictionaries. There are 2 membership operators:

1) in : Returns True if element is found in the specified sequence. If the element is not found in the
specified sequences it returns False.
Eg : print( ‘p’ in ‘python’) # returns True
2) not in : Returns True if element is not found in the specified sequence. If the element is found in
the specified sequences it returns False.
Eg: print(‘s’ not in ‘python’) # returns True

8.How to input data in Python? Give syntax and example


input() function is used to gather data from the user.
The syntax for input function is,
variable_name = input([prompt])
• prompt is a string written inside the parenthesis that is printed on the screen.
• The prompt statement gives an indication to the user of the value that needs to be entered through
the keyboard.
• Even when the user inputs a number, it is treated as a string which should be casted or converted
to number explicitly using appropriate type casting function.
Eg: name=input(“Enter your name:”)

9.List four type conversion functions.


Type conversion functions are used to explicitly cast, or convert, a variable from one type to
another.
1) The int() Function : To explicitly convert a float number or a string to an integer, cast the
number using int() function.
• Eg:
x=int(3.5)

2) The float() Function : The float() function returns a floating point number constructed from a
number or string.
• Eg:
x=float(56)

3) The str() Function: The str() function returns a string which is fairly human readable.
1) Eg:
x= str(5.78)

4) The complex() Function:


It is used to print a complex number with the value real + imag*j or convert a string or number
to a complex number.
Eg
c1=complex("1")

3
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

10.List any four categories of Operators in Python.


Python language supports a wide range of operators. They are:
1. Arithmetic Operators: Arithmetic operators are used to execute arithmetic operations such as
addition, subtraction, division, multiplication etc.
Eg: +,-,*,/
2. Assignment Operators : Assignment operators are used for assigning the values generated after
evaluating the right operand to the left operand.
Eg:=
3. Comparison Operators : When the values of two operands are to be compared then comparison
operators are used.
Eg: ==, +=,-=, *=, /=
4. Logical Operators: The logical operators are used for comparing or negating the logical values
of their operands and to return the resulting logical value
Eg: and, or, not

11.What is indentation? Why it is required?


In Python, Programs get structured through indentation. Any statements written under another statement
with the same indentation is interpreted to belong to the same code block. If there is a next statement
with less indentation to the left, then it just means the end of the previous code block. If a code block has
to be deeply nested, then the nested statements need to be indented further to the right.
Incorrect indentation will result in IndentationError.

12.Give syntax of if...elif statement in Python


The if…elif…else is also called as multi-way decision control statement. To choose from several
possible alternatives, an elif statement is used along with an if statement.

The syntax for if…elif…else statement is,


if Boolean_Expression_1:
statement_1
elif Boolean_Expression_2:
statement_2
elif Boolean_Expression_3:
statement_3
:
:
:
else:
statement_last
Eg:
if grade>=80:
print(‘A’)
elif grade>=60:
print(‘B’)
elif grade>=40:
print(‘C’)
else:
print(‘D’)
4
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

13.What is the purpose of else suit in Python loops? Give example

The else clause in python can be used with if,for, while and try…except statements. The else keyword in
if catches anything which isn't caught by the preceding conditions.
The else keyword in a for loop specifies a block of code to be executed when the loop is finished.
The else keyword in a while loop specifies a block of code to be executed when the condition no longer
is true.
The else keyword in try block specifies a block of code to be executed only if the try clause does not
raise an exception.

Eg:
for x in range(6):
print(x)
else:
print("Finally finished!")

Prints all numbers from 0 to 5, and print a message when the loop has ended.

14.What are the rules for naming identifiers?


1. Identifiers can be a combination of letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to
9) or an underscore (_).
Names like myCountry, other_1 and good_ morning, all are valid examples.
A Python identifier can begin with an alphabet (A – Z and a – z and _).
2. An identifier cannot start with a digit but is allowed everywhere else. 1plus is invalid, but plus1 is
perfectly fine.
3. Keywords cannot be used as identifiers.
4. One cannot use spaces and special symbols like !, @, #, $, % etc. as identifiers.
5. Identifier can be of any length.

15.What is an identifier? Give example


An identifier is a name given to a variable, function, class or module. Identifiers can be a combination of
letters in lowercase (a to z) or uppercase (A to Z) or digits (0 to 9) or an underscore (_).Identifier can be
of any length.

Eg: myCountry, other_1 and good_morning

16.What are python keywords? Give example


Keywords are a list of reserved words that have predefined meaning.
They are special vocabulary and cannot be used by programmers as identifiers for variables, functions,
constants or with any identifier name.
Eg:if, while, for, class, def

17.What are python Variables?


Variable is a named placeholder to hold any type of data which the program can use to assign and
modify during the course of execution. In Python, there is no need to declare a variable explicitly by
specifying whether the variable is an integer or a float or any other type.

5
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

18.What are the rules for naming variables?


1. Variable names can consist of any number of letters, underscores and digits.
2. Variable should not start with a number.
3. Python Keywords are not allowed as variable names.
4. Variable names are case-sensitive. For example, computer and Computer are different variables.

19.Give syntax and example for assigning values to variables


The general format for assigning values to variables is as follows:
variable_name = expression
• The equal sign (=)is used to assign values to variables.
• The operand to the left of the = operator is the name of the variable and the operand to the right
of the = operator is the expression which can be a value or any code snippet that results in a
value.
• That value is stored in the variable on the execution of the assignment statement.
Eg:
1. Allow a single value to a single variable
• Eg: subject = ‘maths’
2. Allow assign a single value to several variables simultaneously
• Eg: a=b=c=1

20.Give the syntax and example for str.format() method.


The syntax for format() method is,
str.format(p0, p1, ..., k0=v0, k1=v1, ...)
• where p0, p1,... are called as positional arguments
• k0, k1,... are keyword arguments with their assigned values of v0, v1,... respectively.
• Eg:
a = 10
b = 20
print("The values of a is {0} and b is {1}".format(a, b))
OUTPUT
The values of a is 10 and b is 20

21.What is f-string literal? Give an example


A f-string is a string literal that is prefixed with “f”. These strings may contain replacement fields,
which are expressions enclosed within curly braces {}. The expressions are replaced with their
values.
Eg:
x=56
y=67.7
print(f"Length={x} and Breadth={y}")
OUTPUT:
Length=56 and Breadth=67.7

6
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

22.What are syntax errors? Give example

Syntax errors, also known as parsing errors. When the proper syntax of the language is not followed then
a syntax error is thrown.
Eg:
amount = 10000

if(amount>=3000)
print("You are eligible to purchase")

OUTPUT:

ERROR!
File "<string>", line 3
if(amount>=3000)
^
SyntaxError: expected ':'

It returns a syntax error message because after the if statement a colon: is missing.

23. What are Exceptions? Give Example


An exception is an unwanted event that interrupts the normal flow of the program.
When an exception occurs in the program, execution gets terminated and displays a system-generated
error message.
EG:
10 * (1/0)

Traceback (most recent call last):


File "<stdin>", line 1, in <module>

ZeroDivisionError: division by zero

The ZeroDivisionError implies that as we are trying to divide a number by 0.

24.What is use of finally statement ?


A finally block is always executed before leaving the try statement, whether an exception has occurred
or not. When an exception has occurred in the try block and has not been handled by an except block, it
is re-raised after the finally block has been executed. The finally clause is also executed when any other
clause of the try statement is left via a break, continue or return statement.

25.Differentiate scope and life time of a variable.


The scope of variable is a region of the program where a variable is visible or accessible.
Lifetime of a variable is the duration for which a variable exists in the memory.

Python programs have two scopes: global and local.

7
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

A variable is a global variable if its value is accessible and modifiable throughout your program. Global
variables have a global scope.
A variable that is defined inside a function definition is a local variable. The lifetime of a variable refers
to the duration of its existence. The local variable is created and destroyed every time the function is
executed, and it cannot be accessed by any code outside the function definition.
Local variables inside a function definition have local scope and exist as long as the function is
executing.

26.List any four built in functions in Python.

Function Syntax Explanation


Name
min() min(arg_1, arg_2, arg_3,…, The min() function returns the smallest of
arg_n) two or more arguments.
where arg_1, arg_2, arg_3 are the
arguments.

max() max(arg_1, arg_2, arg_3,…,arg_n) The max() function returns the largest of
where arg_1, arg_2, arg_3 are two or more arguments.
the arguments.

pow() pow(x, y) The pow(x, y) function returns x to the


where x and y are numbers. power y which is equivalent to using the
power operator: x**y.

len() len(s) The len() function returns the length or the


where s may be a string, byte, list, number of items in an object.
tuple, range, dictionary or a set.

27.Give the Syntax of user defined function.


The syntax for function definition is,

def function_name(parameter_1, parameter_2, …, parameter_n):


statement(s)

1. A function definition consists of the def keyword, followed by the name of the function.
The def keyword introduces a function definition.
2. The function’s name has to follow naming rules for variables. Keyword cannot be used as a
function name.
3. A list of parameters to the function are enclosed in parentheses and separated by commas.
Functions can have zero or more parameters
4. A colon is required at the end of the function header. The first line of the function definition
which includes the name of the function is called the function header.
5. Block of statements that define the body of the function start at the next line of the function
header and they must have the same indentation level.

8
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

28.Give the syntax and example for range() function.

The Python range() function returns a sequence of numbers, in a given range.


The range() function only works with integers.
Syntax :

range([start ,] stop [, step])


Both start and step arguments are optional and the range argument value should always
be an integer.
start → value indicates the beginning of the sequence. If the start argument is not specified, then the
sequence of numbers start from zero by default.
stop → Generates numbers up to this value but not including the number itself.
step → indicates the difference between every two consecutive numbers in the
sequence. The step value can be both negative and positive but not zero.
Eg:

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


print(i)

OUTPUT
0
3
6
9

29.What is the meaning of__name__ == __main__ ?

If the Python interpreter is running the source program as a stand-alone main program, it sets the special
built-in __name__ variable to have a string value "__main__".
After setting up these special variables, the Python interpreter reads the program to execute
the code found in it. All of the code that is at indentation level 0 gets executed.

if __name__ == "__main__":
statement(s)

The special variable, __name__ with "__main__", is the entry point to your program. When
Python interpreter reads the if statement and sees that __name__ does equal to "__main__",
it will execute the block of statements present there.

30.Give example of function returning multiple values.

def get_details():
name=input("Enter Employee name:")
dept=input("Enter Department:")
return name,dept

9
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

ename,edept = get_details()
print(f"{ename} belongs to {edept} section")

OUTPUT

Enter Employee name:Asha


Enter Department:Accounts

Asha belongs to Accounts section

In the above example get_details() returns multiple values as tuple. In the main function the tuple is
unpacked and stored in ename,edept respectively.

31.What is keyword argument? Give example

Whenever we call a function with some values as its arguments, these values get assigned to the
parameters in the function definition according to their position.
In the calling function, you can explicitly specify the argument name along with their value in the form
kwarg = value.
In the calling function, keyword arguments must follow positional arguments.

Eg:

def show_details(name,salary):
print("Employee Name:", name)
print("Employee Salary:", salary)

show_details(salary=25000,name="Kalpana")

OUTPUT:

Employee Name: Kalpana


Employee Salary: 25000

32.What is default argument? Give example

Each default parameter has a default value as part of its function definition.
Any calling function must provide arguments for all required parameters in the function definition but
can omit arguments for default parameters.
If no argument is sent for that parameter, the default value is used.

10
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

def show_details(name,salary=20000):
print("Employee Name:", name)
print("Employee Salary:", salary)

show_details(salary=25000,name="Kalpana")

show_details(name="Suhana")

OUTPUT:

Employee Name: Kalpana


Employee Salary: 25000

Employee Name: Suhana


Employee Salary: 20000

In the above example, since salary of Suhana is not passed, the default value for salary will be used.

33.Differentiate *args and **kwargs


*args:
• *args as parameter in function definition allows you to pass a non-keyworded, variable length
tuple argument list to the calling function.
• *args must come after all the positional parameters.

Eg:

def show_details(*args):

for item in args:


print(item)

show_details("Maths","Science","English")

OUTPUT:
Maths
Science
English

**kwargs:

• **kwargs as parameter in function definition allows you to pass keyworded, variable length
dictionary argument list to the calling function.
• **kwargs must come right at the end.

11
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Eg:
def multipleFunction(**kwargs):
for key, value in kwargs.items():
print("%s is %s" % (key, value))

multipleFunction(Name='Asha',Dept='Accounts',Salary=20000)

OUTPUT:
Name is Asha
Dept is Accounts
Salary is 20000

Long Answer Questions


1.Explain any five features of Python.
1. Simple: Python is a simple programming language. There is more clarity and less stress on
understanding the syntax of the language. Developing and understanding programs is easy.
2. Easy to learn: Developing programs in python is easy as it uses very few keywords and has a
very simple structure. Python resembles C language and most of the language constructs in C are
also available in Python. Hence, migrating from C to Python in easy for programmers.
3. Open Source: Python can be freely downloaded from www.python.org website. Its source code
can be read, modified and used in programs as desired by the programmers.
4. High Level Language: programming languages are of two types: High Level and Low level .
 A low-level language uses machine code instructions to develop instructions which directly
interact with the CPU. Example: Machine language, Assembly language.
 A high-level language uses English language to develop programs. It is easy to learn and use.
Example: Python, Java, C++, C etc.
5. Dynamically typed: Python is a dynamically typed language which means there is no need to
declare anything. An assignment statement binds a name to an object , and the object can be of
any type. If a name is assigned to an object of one type, it may be later assigned to an object of a
different data type.
6. Platform Independent: Python programs are not dependent on any operating systems. It can run
on systems with any operating systems (Windows, Linux, Unix, Macintosh, Solaris etc).
 When a python code is compiled using python compiler, it generates byte code. Byte code
represents a fixed set of instructions that run on all operating systems and hardware. Using a
PVM (Python Virtual Machine) anybody can run these byte code instructions on any
computer system.
7. Portable: When a program yields the same result on any computer, it is called a portable
program.

8. Procedure and object oriented: Python is both procedure and object oriented language.
In procedure-oriented language, programs are built using functions and procedures.
In object-oriented language, programs are written using classes and objects.
9. Interpreted: A program code is called source code. Python compiler compiles source code
and generates byte code. The byte is executed by a PVM (Python Virtual Machine). Inside the

12
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

PVM , an interpreter converts the bytecode to machine code and the processor runs the
machine code to produce results.

10. Extensible: Programs or pieces of code from C and C++ can be integrated into Python and
executed using PVM. There are two flavors of python where programs from other languages
can be integrated to Python:
Jython: Integrates Java code into Python and runs on JVM (Java Virtual Machine)
Iron Python: Integrates .NET code into Python runs on CLR ( Common Language Runtime)

11. Embeddable: Python programs can be inserted into other programming languages like C,
C++, PHP, Java, .NET and Delphi. Programmers can use these applications to their advantage
in various software projects.

12. Huge Library: Python has a big library which can be used on any operating systems.
Programmers can develop programs using the modules available in the libraries.

13. Scripting Language: It is a programming language that uses interpreter instead of compiler
to execute a program. Generally scripting languages perform supporting tasks for bigger
applications and software. PHP is a scripting language which accepts input from an HTML
page and sends it to web server. Python is a scripting language as it is interpreted and it is
used on the Internet to support other software.

14. Database Connectivity: A database represents software that stores and manipulates data.
Python provides interfaces to connect its programs to all major databases like Oracle, Sybase
and MySQL.

15. Scalable: A program is scalable if it can be moved from one operating system to another or
hardware and take full advantage of its environment in terms of performance. Python
programs are scalable since they can on run on any platform and use the features of the new
platform effectively.

16. Batteries Included: Python library contains several small applications (small packages)
which are already developed and immediately available to programmers. These small can be
used and maintained easily. Programmers need not download applications or packages
separately. These libraries are called batteries included.
Example: numpy, pandas, matplotlib, Pillow , scipy etc.

2.Explain any five flavors of Python .


1) CPython : This standard python compiler is implemented in C language. Python program is
internally converted into bytecode using C functions. This byte is run on PVM created in C
language. The advantage is that it is possible to execute C and C++ functions and programs in
CPython.
2) Jython: Earlier known as JPython. This is the implementation of Python programming language
which is designed to run on the Java platform. Jython compiler first compiles the python program
into Java byte code. This byte code is executed by Java Virtual Machine (JVM) to produce the
output. Jython contains libraries which are useful for both python and Java programmers.
3) IronPython: This is the implementation of Python programming language in .NET framework.
This is written in C# language. The Python program when compiled gives an intermediate

13
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

language(IL) which runs on Common Language Runtime (CLR) to produce the output. This
flavor of python gives flexibility of using both .NET and python libraries.
4) RubyPython: This is a bridge between Ruby and Python interpreters. It encloses a python
interpreter inside Ruby applications.
5) AnacondaPython: When python is redeveloped for handling large-scale data processing,
predictive analytics and scientific computing, it is called AnacondaPython. This implementation
mainly focuses on large scale of data.

3.Explain various data types in Python.


Data Types:
• Data types specify the type of data like numbers and characters to be stored and manipulated
within a program. Basic data types of Python are:
1. Numbers
2. Boolean
3. Strings
4. None

Numbers:
• Integers, floating point numbers and complex numbers fall under Python numbers category.
• They are defined as int, float and complex class in Python.
• Integers can be of any length; it is only limited by the memory available.
• A floating point number is accurate up to 15 decimal places.
• Integer and floating points are separated by decimal points.
• Eg: 1 is an integer, 1.0 is floating point number.
• Complex numbers are written in the form, x + yj, where x is the real part and y is the imaginary
part.

Boolean:
• It represents boolean datatype.
• There are only two boolean values True and False.
• Python internally represents True as 1 and False as 0.
• Eg: a= True

Strings:
• A string consists of a sequence of one or more characters, which can include letters, numbers,
and other types of characters.
• A string can also contain spaces.
• Strings are enclosed within single quotes or doubles quotes.
• Multiline strings can be denoted using triple quotes, ''' or """.
• Eg:
• s = 'This is single quote string’
• s = "This is double quote string“
• s = '''This is
Multiline
string'''

14
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

None:
• None is another special data type in Python.
• None is frequently used to represent then absence of a value. For example,
• Eg: money = None

4.Explain the Arithmetic operators, logical operators and relational operators with an example.

Arithmetic Operators
• Arithmetic operators are used to execute arithmetic operations such as addition, subtraction,
division, multiplication etc.

Logical Operators
• The logical operators are used for comparing or negating the logical values of their operands and
to return the resulting logical value.
• The values of the operands on which the logical operators operate evaluate to either True or
False.
• The result of the logical operator is always a Boolean value, True or False.

15
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Relational (Comparison) Operators:

• When the values of two operands are to be compared then comparison operators are used.
• The output of these comparison operators is always a Boolean value, either True or False.
• The operands can be Numbers or Strings or Boolean values.
• Strings are compared letter by letter using their ASCII values.

5.Explain the bitwise operators with examples.

Bitwise Operators:
• Bitwise operators treat their operands as a sequence of bits (zeroes and ones) and perform bit by
bit operation.
• Bitwise operators perform their operations on binary representations, but they return standard
Python numerical values.

16
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

6.How to read different types of input from the keyboard. Give examples

Python, input() function is used to gather data from the user. The syntax for input function is,
variable_name = input([prompt])

• prompt is a string written inside the parenthesis that is printed on the screen.

17
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

• The prompt statement gives an indication to the user of the value that needs to be entered through
the
• keyboard.
• When the user presses Enter key, the program resumes and input returns what the user typed as a
string.
• Even when the user inputs a number, it is treated as a string which should be casted or converted
to number explicitly using appropriate type casting function.
Eg:

name = input("Enter Name:")

phone=int(input("Enter phone no:"))

salary=float(input("Enter salary:"))

print(f"Name={name}, phone={phone} , salary={salary}")

OUTPUT:

Enter Name:Rahul

Enter phone no:7788996655

Enter salary:34000
Name=Rahul, phone=7788996655 , salary=34000.0

7.Explain use of string.format and f-string with print() function.


The two major string formats which are used inside the print() function are:
1. str.format()
2. f-strings

str.format() Method:
• str.format() method is used to insert the value of a variable, expression or an object into another
string and display it to the user as a single string.
• The format() method returns a new string with inserted values.
• The format() method uses its arguments to substitute an appropriate value for each format code in
the template.
• The syntax for format() method is,
str.format(p0, p1, ..., k0=v0, k1=v1, ...)
• where p0, p1,... are called as positional arguments
• k0, k1,... are keyword arguments with their assigned values of v0, v1,... respectively.
• Eg:
a = 10
b = 20
print("The values of a is {0} and b is {1}".format(a, b))
OUTPUT
The values of a is 10 and b is 20

18
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

f-strings:
• A f-string is a string literal that is prefixed with “f”.
• These strings may contain replacement fields, which are expressions enclosed within curly braces
{}.
• The expressions are replaced with their values.
• Eg:
x=56
y=67.7
print(f"Length={x} and Breadth={y}")
OUTPUT:
Length=56 and Breadth=67.7

8.Explain any five type conversion functions with example.


Type conversion functions are used to explicitly cast, or convert, a variable from one type to another.
1) The int() Function :
a. To explicitly convert a float number or a string to an integer, cast the number using int()
function.
b. Eg:
x=int(3.5)
y=int("11")
print(f"x={x} and y={y}")
OUTPUT:
x=3 and y=11

2) The float() Function :


• The float() function returns a floating point number constructed from a number or string.
• Eg:
x=float(56)
y=float("34")
print(f"x={x} and y={y}")
OUTPUT:
x=56.0 and y=34.0

3) The str() Function: The str() function returns a string which is fairly human readable.
Eg:
x= str(5.78)
print(f"x={x} and datatype of x={type(x)}")
OUTPUT
x=5.78 and datatype of x=<class 'str'>

4) The chr() Function: Convert an integer to a string of one character whose ASCII code is same
as the integer using chr() function. The integer value should be in the range of 0–255.
Eg:
ascii_to_char = chr(100)
print(f'Equivalent Character for ASCII value of 100 is {ascii_to_char}’)
OUTPUT:
Equivalent Character for ASCII value of 100 is d

19
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

5) The complex() Function:


• complex() function is used to print a complex number with the value real + imag*j or
convert a string or number to a complex number.
• If the first argument for the function is a string, it will be interpreted as a complex number
and the function must be called without a second parameter.
• The second parameter can never be a string.
• Each argument may be any numeric type (including complex).
• If imag is omitted, it defaults to zero and the function serves as a numeric conversion
function like int(), float().
Eg
c1=complex("1")
print(c1)
c2=complex(5,8)
print(c2)
print("real part=", c2.real, "and imaginary part=", c2.imag)
OUTPUT
(1+0j)
(5+8j)
real part= 5.0 and imaginary part= 8.0

9.Explain while and for loops with syntax and example.

The syntax for while loop is,


while Boolean_Expression:
statement(s)

1. The while loop starts with the while keyword and ends with a colon.
2. The Boolean expression is evaluated before the statements in the while loop block is executed.
3. If the Boolean expression evaluates to False, then the statements in the while loop block are
never executed.
4. If the Boolean expression evaluates to True, then the while loop block is executed.
5. After each iteration of the loop block, the Boolean expression is again checked, and if it is True,
the loop is iterated again.

Eg:

i = 1
while i <= 4:
print(i)
i = i + 1

output:
1
2
3

20
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

The syntax for the for loop is,

for iteration_variable in sequence:


statement(s)

1. The for loop starts with for keyword and ends with a colon.
2. The first item in the sequence gets assigned to the iteration variable iteration_variable. The
iteration_variable can be any valid variable name.
3. Then the statement block is executed.
4. The process of assigning items from the sequence to the iteration_variable and then executing
the statement continues until all the items in the sequence are completed.

Eg:

for i in "Apple":
print(i)

Output:

A
p
p
l
e

10.Explain Exception handling in Python with try…except… finally block

Exception handling an important feature that allows us to handle the errors caused by exceptions.
Handling of exception ensures that the flow of the program does not get interrupted when
an exception occurs which is done by trapping run-time errors. Handling of exceptions
results in the execution of all the statements in the program.

The syntax for try…except…finally is,


try:
statement_1
except Exception_Name_1:
statement_2
except Exception_Name_2:
statement_3
.
.
.
else:
statement_4
21
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

finally:
statement_5

1. A try block consisting of one or more statements is used to partition code that might be affected
by an exception.
2. The associated except blocks are used to handle any resulting exceptions thrown in the try block.
3. If any statement within the try block throws an exception, control immediately shifts to the
except
4. block.
5. If no exception is thrown in the try block, the except block is skipped.
6. There can be one or more except blocks.
7. The except blocks are evaluated from top to bottom in the code, but only one except block is
executed for each exception that is thrown.
8. The first except block that specifies the exact exception name of the thrown exception is
executed.
9. The else (optional) block, must follow all except blocks. It is useful for code that must be
executed if the try block does not raise an exception.
10. A finally (optional) block is always executed before leaving the try statement, whether an
exception has occurred or not.

11.Give the syntax of range function. Explain use range function in for loop with examples.

The Python range() function returns a sequence of numbers, in a given range.


The range() function only works with integers.
The range() function generates a sequence of numbers which can be iterated through using for loop.
Syntax :
range([start ,] stop [, step])
Both start and step arguments are optional and the range argument value should always
be an integer.
start → value indicates the beginning of the sequence. If the start argument is not specified, then the
sequence of numbers start from zero by default.
stop → Generates numbers up to this value but not including the number itself.
step → indicates the difference between every two consecutive numbers in the
sequence. The step value can be both negative and positive but not zero.

Eg 1:

for i in range(4):
print(i)

OUTPUT

0
1
2

22
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

3
The function range(4) generates all the numbers starting from 0 up to 3

Eg 2:

for i in range(5,8):
print(i)

OUTPUT
5
6
7
The function range(5,8) generates all the numbers starting from 5 up to 7

Eg 3:

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


print(i)

OUTPUT
0
3
6
9

The function range(0, 10, 3) generates all the numbers starting from 0 up to 10 but
the difference between each number is 3.

12.With syntax and example explain how to define and call a function in Python

User-defined functions are reusable code blocks created by users to perform some specific task in the
program.

The syntax for function definition is,

def function_name(parameter_1, parameter_2, …, parameter_n):


statement(s)

1. A function definition consists of the def keyword, followed by the name of the function.
The def keyword introduces a function definition.
2. The function’s name has to follow naming rules for variables. Keyword cannot be used as a
function name.
3. A list of parameters to the function are enclosed in parentheses and separated by commas.
Functions can have zero or more parameters

23
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

4. A colon is required at the end of the function header. The first line of the function definition
which includes the name of the function is called the function header.
5. Block of statements that define the body of the function start at the next line of the function
header and they must have the same indentation level.
Defining a function does not execute it. Calling the function actually performs the specified actions with
the indicated parameters.

The syntax for function call or calling function is,


function_name(argument_1, argument_2,…,argument_n)

1. Arguments are the actual value that is passed into the calling function.
2. There must be a one-to-one correspondence between the parameters in the function definition
and the arguments of the calling function.
3. When a function is called, the parameters are temporarily “bound” to the arguments.
4. A function should be defined before it is called.

Eg:

def area(x,y):
return x*y

length=int(input("Enter length:"))
breadth=int(input("Enter breadth:"))
result=area(length,breadth)
print(f"Area of the rectangle={result}")

OUTPUT

Enter length:5
Enter breadth:4
Area of the rectangle=20

In the above example the arguments length and breadth are bound to the parameters x and y of the
function area().
The function area() calculates the result and returns it back to the calling function.

13. Explain *args and **kwargs with example

*args and **kwargs allows you to pass a variable number of arguments to the calling function.
*args:
• *args as parameter in function definition allows you to pass a non-keyworded, variable length
tuple argument list to the calling function.
• *args must come after all the positional parameters.

Eg:

24
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

def show_details(*args):

for item in args:


print(item)

show_details("Maths","Science","English")

OUTPUT:
Maths
Science
English

**kwargs:

• **kwargs as parameter in function definition allows you to pass keyworded, variable length
dictionary argument list to the calling function.
• **kwargs must come right at the end.

Eg:
def multipleFunction(**kwargs):
for key, value in kwargs.items():
print("%s is %s" % (key, value))

multipleFunction(Name='Asha',Dept='Accounts',Salary=20000)

OUTPUT:
Name is Asha
Dept is Accounts
Salary is 20000

14. With example explain keyword arguments and default arguments to the function.

Whenever we call a function with some values as its arguments, these values get assigned to the
parameters in the function definition according to their position.
In the calling function, you can explicitly specify the argument name along with their value in the form
kwarg = value.
In the calling function, keyword arguments must follow positional arguments.
All the keyword arguments passed must match one of the parameters in the function definition and their
order is not important. No parameter in the function definition may receive a value more than once.

Eg:

25
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

def show_details(name,salary):
print("Employee Name:", name)
print("Employee Salary:", salary)

show_details(salary=25000,name="Kalpana")

OUTPUT:

Employee Name: Kalpana


Employee Salary: 25000

Each default parameter has a default value as part of its function definition.
Any calling function must provide arguments for all required parameters in the function definition but
can omit arguments for default parameters.
If no argument is sent for that parameter, the default value is used.

def show_details(name,salary=20000):
print("Employee Name:", name)
print("Employee Salary:", salary)

show_details(salary=25000,name="Kalpana")

show_details(name="Suhana")

OUTPUT:

Employee Name: Kalpana


Employee Salary: 25000

Employee Name: Suhana


Employee Salary: 20000

In the above example, since salary of Suhana is not passed, the default value for salary will be used.

15. With example explain how command line arguments are passed to python program.

A Python program can accept any number of arguments from the command line.
Command line arguments is a methodology in which user will give inputs to the program
through the console using commands. We need to import sys module to access command
line arguments. All the command line arguments in Python can be printed as a list of

26
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

string by executing sys.argv.

import sys
def main():
print("Arguments:",sys.argv)
print("Total arguments:", {len(sys.argv)})

for arg in sys.argv:


print(arg)

if __name__ == "__main__":
main()

OUTPUT

G:\BCA\EvenSem>python cmdPrg.py 123 "apple"


Arguments: ['cmdPrg.py', '123', 'apple']
Total arguments: {3}
cmdPrg.py
123
Apple

16. Write a program to check for ‘ValueError’ exception

while True:
try:
number = int(input("Please enter a number: "))
print(f"The number you have entered is {number}")
break
except ValueError:
print("Oops! That was no valid number. Try again…")

OUTPUT
lease enter a number: hello
Oops! That was no valid number. Try again…
Please enter a number: 10
The number you have entered is 10

1. The try block is executed inside the while loop .


2. If no exception occurs, the except block is skipped and execution of the try statement is finished.
3. If an exception occurs during execution of the try block statements, the rest of the statements in
the try block is skipped.
4. If its type matches the exception named after the except keyword, the except block is executed
5. Execution continues after the try statement.
6. When a variable receives an inappropriate value then it leads to ValueError exception.

17. Write a program to check for ZeroDivisionError Exception


27
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

x = int(input("Enter value for x: "))


y = int(input("Enter value for y: "))
try:
result = x / y
except ZeroDivisionError:
print("Division by zero!")
else:
print(f"Result is {result}")
finally:
print("Executing finally clause")

OUTPUT

Enter value for x: 7


Enter value for y: 0
Division by zero!
Executing finally clause

1. If the statements enclosed within the try clause raise an exception then the control is transferred
to except block.
2. ZeroDivisionError occurs when the second argument of a division or modulo operation is zero.
3. If no exception occurs, the except block is skipped and result is printed in the else block .
4. finally clause is executed in any event

18. How to return multiple values from a function definition? Explain with an example

def get_details():
name=input("Enter Employee name:")
dept=input("Enter Department:")
return name,dept

ename,edept = get_details()
print(f"{ename} belongs to {edept} section")

OUTPUT

Enter Employee name:Asha


Enter Department:Accounts

Asha belongs to Accounts section

In the above example get_details() returns multiple values as tuple. In the main function the tuple is
unpacked and stored in ename,edept respectively.

28
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Unit - ii
Two Mark questions

1.Give two methods of creating strings in Python.

The two methods of creating strings in Python are:

1) Creating string by enclosing them in either single or double quotation marks.


Eg:
1) x= 'python programming'
print(type(x))

OUTPUT

<class 'str'>

2) x= “python programming”
print(type(x))

OUTPUT

<class 'str'>

2) Using the str() function which returns a string


Eg:
x=str(34.5)

print(type(x))

OUTPUT

<class 'str'>

2.List any two built in functions used with python strings. Mention their use.

Function Purpose Example


Name
len() The len() function calculates the number of >>> total = len("apple")
characters in a string. The white space >>> print(total)
characters are also counted. 5

29
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

max() The max() function returns a character having >>> print(max('apple'))


highest ASCII value. p

3.Why strings are called immutable?


The characters in a string cannot be changed once a string value is assigned to string variable. They are
called immutable because they cannot be modified.
Eg:
x='busy'
x[2]='r'

OUTPUT:
TypeError: 'str' object does not support item assignment

4.What is use of negative indexing? Give example.


We can access end characters in a long string by counting backward from the end of the string starting
from an index number of −1. Using negative indexing we can access characters at the end of a long
string.

>>> word_phrase = 'be yourself'

>>> word_phrase[-1]
'f'

>>> word_phrase[-3]
'e'

Negative index number of −1 prints the character ‘f ’ and Negative index number of −1 prints the
character ‘e’.

5.Give the output of the following Python code:

30
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

str1 = 'This is Python'


print( "Slice of String : ", str1[1 : 4 : 1] )
print ("Slice of String : ", str1[0 : -1 : 2] )

OUTPUT

Slice of String : his


Slice of String : Ti sPto

6.Give the output of following Python code

newspaper = "new york times"


print(newspaper[0:12:4])
print (newspaper[::4])

OUTPUT

ny
ny e

7.Give the syntax and example for split function.


The split() method returns a list of string items by breaking up the string using the delimiter string.
The syntax of split() method is,

string_name.split([separator [, maxsplit]])

• Here separator is the delimiter string and is optional.


• A given string is split into list of strings based on the specified separator.
• If the separator is not specified then whitespace is considered as the delimiter string to separate
the strings.
• If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1
items).
• If maxsplit is not specified or −1, then there is no limit on the number of splits.

Eg:
fruits = 'mango,apple,orange,banana'
x=fruits.split(',')
print(x)

OUTPUT

31
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

['mango', 'apple', 'orange', 'banana']

8.Write Python code to print each character in a string.

string = input("Enter the string:")


for char in string:
print(char)

OUTPUT

Enter the string: Program


P
r
o
g
r
a
m

9.What is list? How to create list ?


List is a container that holds a number of items. Each element or value that is inside a list is called an
item. All the items in a list are assigned to a single variable. Lists can be simple or nested lists with
varying types of values. Lists are mutable.

The syntax for creating list is,


list_name = [item1, item2,….., itemn]

To create an empty list without any items, the syntax is,


list_name = [ ]

Eg:
x=[12,34,'apple',True]
print(type(x))

<class 'list'>

10.List any four built-in functions used on list.


Built-In Description Example
Functions
len() The len() function returns the numbers of >>> x=[12,34,'apple',True]
items in a list. >>> print(len(x))

32
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

sum() The sum() function returns the sum of >>> x=[1,2,3,4,5]


numbers in the list. >>> print(sum(x))
15

any() The any() function returns True if any of the >>> x=[1,0,1,0]
Boolean values in the list is True. >>>print(any(x))
True

>>>x=[0,0]
>>>print(any(x))
False
all() The all() function returns True if all the >>> x=[1,0,1,0]
Boolean values in the list are True, else >>> print(all(x))
returns False. False

>>> x=[1,1]
>>> print(all(x))
True
sorted() The sorted() function returns a modified copy
of the list while leaving the original list
untouched.

11. Write the output of the given python code :

aList = [123, 'xyz', 'zara', 'abc'];


aList.insert (3,2009)
print ("Final List:", aList)

OUTPUT

Final List: [123, 'xyz', 'zara', 2009, 'abc']

12.Give the syntax and example for list slicing


Slicing of lists is wherein a part of the list can be extracted by specifying index range along with the
colon (:) operator which itself is a list.

Syntax:

list_name[start : stop [:step] ]

• start and stop are integer values (positive or negative values).


• List slicing returns a part of the list from the start index value to stop index value
• It includes the start index value but excludes the stop index value.
33
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

• Step specifies the increment value to slice by and it is optional.

Example:
>>> fruits = ["apple", "cherry", "orange", "mango", "banana"]
>>>fruits[1:3]
['cherry', 'orange']
>>>fruits[1:4:2]
['cherry', 'orange']

13.What is dictionary? Give example


A dictionary is a collection of an unordered set of key:value pairs. Keys are unique within a dictionary.
Dictionaries are constructed using curly braces { }.

Syntax:
dictionary_name = { key1:value1, key2:value2, ………,keyn:valuen }

Example:
info={'Reg':112, 'Name':'Harish', 'Salary':25000}

14.How to access and modify key value pairs of dictionary ?


Each individual key:value pair in a dictionary can be accessed through keys by specifying it inside
square brackets. The key provided within the square brackets indicates the key:value pair being accessed.

The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]

The syntax for modifying the value of an existing key or for adding a new key:value pair to a dictionary
is,
dictionary_name[key] = value

If the key is already present in the dictionary, then the key gets updated with the new value.
If the key is not present then the new key:value pair gets added to the dictionary.

15.List any four built-in functions used on dictionary.

Built-in Description
Functions
len() The len() function returns the number of items (key:value pairs) in a dictionary.
all() The all() function returns Boolean True value if all the keys in the dictionary are True
else returns False.

34
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

any() The any() function returns Boolean True value if any of the key in the dictionary is True
else returns False.
sorted() The sorted() function by default returns a list of items, which are sorted based on
dictionary keys

16.Write a Python code to Traversing of key:value Pairs in Dictionaries


>>> country = {1:"India", 2:"USA", 3:"Russia", 4:"UK"}

>>> for k in country:


print(k)
1
2
3
4

>>> for v in country.values():


print(v)
India
USA
Russia
UK

>>> for k,v in country.items():


print(k,v)
1 India
2 USA
3 Russia
4 UK

17.What is tuple ? How is it created in Python ?


A tuple is a finite ordered list of values of possibly different types which is used to bundle related values
together without having to create a specific type to hold them. Tuples are immutable. Once a tuple is
created, you cannot change its values.
A tuple is defined by putting a comma-separated list of values inside parentheses ( ). Each value
inside a tuple is called an item.

1) Creating an empty tuple


a. fruits = ()
b. fruits = tuple()
2) Creating a tuple using parenthesis
fruits = (‘apple’, ‘orange’, ‘banana’)
3) Creating a tuple without using parenthesis
fruits = ‘apple’, ‘orange’, ‘banana’
35
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

4) Singleton tuple
fruits = (‘apple’ , )

18. What is the output of print (tuple[1:3]) if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?

tuple = ( 'abcd', 786 , 2.23, 'john', 70.2)


print(tuple[1:3])

OUTPUT

(786, 2.23)

19.Give syntax and purpose of two built-in functions used on tuples


Built-In Functions Description
len() The len() function returns the numbers of items in a tuple.
sum() The sum() function returns the sum of numbers in the tuple.
sorted() The sorted() function returns a sorted copy of the tuple as a list while leaving the original
tuple untouched

20.How to convert tuple in to List ? Give example


We can convert a tuple to a list by passing the tuple name to the list() function.
Example:
>>> cars_tuple = ('bmw', "audi", "ferrari")
>>>print(cars_tuple)
('bmw', 'audi', 'ferrari')

>>> cars_list = list(cars_tuple)


>>> print(cars_list)
['bmw', 'audi', 'ferrari']

21.Differentiate tuple and set datatype.

Sl No Tuple Set
1 Tuple is immutable Set is mutable
2 Tuple is an ordered collection of items. Set is an unordered collection of items.
3 Tuple can have duplicate items. Set does not have duplicate items.
4 Tuples are enclosed within parenthesis Set is enclosed within curly braces{}

36
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

22.List any two set methods and mention purpose of each method.

Set Syntax Description


Methods
add() set_name.add(item) The add() method adds an item to the set set_name.
clear() set_name.clear() The clear() method removes all the items from the set set_name.

Long Answer Questions

1. What is string slicing? Explain with examples


The "slice" syntax used refer to sub-parts of sequence of characters within an original string. A
substring is created when slicing the strings.It is a string that already exists within another string.

The syntax for string slicing is,


string_name[start:end[:step]]

• Colon is used to specify range values


• we can access a sequence of characters by specifying a range of index numbers separated by a
colon.
• String slicing returns a sequence of characters beginning at start and extending up to but not
including end.
• The start and end indexing values have to be integers.
• String slicing can be done using either positive or negative indexing.
• In string slicing, start index value (including) is where slicing starts and end index value
(excluding) is where the slicing ends.
• If the start index is omitted, the slicing starts from the first index number (0th Index).
• If the end index is omitted, slicing goes up to the end of the string index.

37
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

2. Write a note on negative indexing and slicing strings using negative indexing.

Slicing can also be done using the negative integer numbers. Negative indexing starts with −1 index
corresponding to the last character in the string and then the index decreases by one as we move to the
left.

We need to specify the lowest negative integer number in the start index position when using negative
index numbers as it occurs earlier in the string.

3. Explain split and join methods of string with example.

The split() method returns a list of string items by breaking up the string using the delimiter string.

The syntax of split() method is,


string_name.split ( [separator [, maxsplit] ] )

• separator is the delimiter string and is optional.


• A given string is split into list of strings based on the specified separator.
• If the separator is not specified then whitespace is considered as the delimiter string to separate
the strings.
• If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit + 1
items).
• If maxsplit is not specified or −1, then there is no limit on the number of splits.

Example:
>>> fruits= "apple, orange, mango"
>>> result=fruits.split(',')
>>> result
['apple', ' orange', ' mango']

>>> fruits= "apple orange mango"


>>> result=fruits.split()

38
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

>>> result
['apple', ' orange', ' mango']

Strings can be joined with the join() string.

The syntax of join() method is,


string_name.join(sequence)

• The sequence can be string or list.


• If the sequence is a string, then join() function inserts string_name between each character of the
string sequence and returns the concatenated string.
• If the sequence is a list, then join() function inserts string_name between each item of list
sequence and returns the concatenated string.
• All the items in the list should be of string type.

Example:
>>> date_of_birth = ["17", "09", "1950"]
>>> "-".join(date_of_birth)
'17-09-1950'

4. Explain concatenation , repetition and membership operations on string.


Concatenation: strings can be concatenated using + sign .The + operator cannot be used to concatenate
values of two different types. To concatenate an integer and string value we have to convert integer type
to string type and then concatenate the values.

Example:
>>> s1="Python"
>>> s2="Code"
>>> s3=s1+s2
>>> s3
'PythonCode'

Repetition: * operator is used to create a repeated sequence of strings. The multiplication operator * on
a string repeats the string the number of times you specify and the string value.

Example:
>>> s="Python"*3
>>> s
'PythonPythonPython'

Membership operator: To check the presence of a string in another string the in and not in membership
Operators are used. It returns either a Boolean True or False.

39
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

The in operator evaluates to True if the string value in the left operand appears in the sequence of
characters of string value in right operand.
The not in operator evaluates to True if the string value in the left operand does not appear in the
sequence of characters of string value in right operand.

Example:
>>> 't' in 'Python'
True

>>> 'y' not in 'Python'


False

5. Explain any five string functions with syntax and example.


Built-In Description Example
Functions
len() The len() function calculates the number >>> total_chars=len("Python
of characters in a string. The white space Programming")
characters are also counted. >>> total_chars
18
max() The max() function returns a character >>> max("Python")
having highest ASCII value. 'y'
min() The min() function returns character >>> min("Python")
having lowest ASCII value 'P'

upper() The method upper() converts lowercase s1='Roses are Red'


letters in string to uppercase. s2=s1.upper()
print(f'string1 :{s1}')
print(f'string2 :{s2}')

string1 :Roses are Red


string2 :ROSES ARE RED
lower() The method upper() converts lowercase s1='Roses are Red'
letters in string to uppercase. s2=s1.upper()
print(f'string1 :{s1}')
print(f'string2 :{s2}')

string1 :Roses are Red


string2 :ROSES ARE RED

6. Write a note on indexing and slicing lists.


As an ordered sequence of elements, each item in a list can be called individually, through indexing. The
expression inside the bracket is called the index. Lists use square brackets [ ] to access individual items,
with the first item at index 0, the second item at index 1 and so on. The index provided within the square
brackets indicates the value being accessed.

40
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

The syntax for accessing an item in a list is,


list_name[index]
where index should always be an integer value and indicates the item to be selected

Slicing of lists is wherein a part of the list can be extracted by specifying index range along with the
colon (:) operator which itself is a list.

Syntax:
list_name[start : stop [:step] ]
• start and stop are integer values (positive or negative values).
• List slicing returns a part of the list from the start index value to stop index value
• It includes the start index value but excludes the stop index value.
• Step specifies the increment value to slice by and it is optional.

Example:
>>> fruits = ["apple", "cherry", "orange", "mango", "banana"]
>>>fruits[1:3]
['cherry', 'orange']
>>>fruits[1:4:2]
['cherry', 'orange']

7. Explain any five list methods with syntax.

String Methods Syntax Description


append() list.append(item) The append() method adds a single item to the end of the list.
This method does not return new list and it just modifies the
original.

41
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

count() list.count(item) The count() method counts the number of times the item has
occurred in the list and returns it.
insert() list.insert(index, The insert() method inserts the item at the given index,
item) shifting items to the right
sort() list.sort() The sort() method sorts the items in place in the list. This
method modifies the original list and it does not return a new
list.
reverse() list.reverse() The reverse() method reverses the items in place in the list.
This method modifies the original list and it does not return a
new list.

8. Write a Python code to implement stack operations using lists

stack = []
stack_size = 3

def display_stack_items():
print("Current stack items are: ")
for item in stack:
print(item)

def push_item_to_stack(item):
print(f"Push an item to stack {item}")
if len(stack) < stack_size:
stack.append(item)
else:
print("Stack is full!")

def pop_item_from_stack():
if len(stack) > 0:
print(f"Pop an item from stack {stack.pop()}")
else:
print("Stack is empty.")

def main():
push_item_to_stack(1)
push_item_to_stack(2)
push_item_to_stack(3)
display_stack_items()
push_item_to_stack(4)
pop_item_from_stack()
display_stack_items()
pop_item_from_stack()
pop_item_from_stack()
pop_item_from_stack()

42
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

if __name__ == "__main__":
main()

OUTPUT:

Push an item to stack 1


Push an item to stack 2
Push an item to stack 3
Current stack items are:
1
2
3
Push an item to stack 4
Stack is full!
Pop an item from stack 3
Current stack items are:
1
2
Pop an item from stack 2
Pop an item from stack 1
Stack is empty.

9. Write a Python code to implement queue operations using lists


from collections import deque

def queue_operations():
queue = deque(["Java","C","Python"])
print(f"Queue items are {queue}")
print("Adding few items to Queue")
queue.append("PHP")
queue.append("C#")
print(f"Queue items are {queue}")
print(f"Removed item from Queue is {queue.popleft()}")
print(f"Removed item from Queue is {queue.popleft()}")
print(f"Queue items are {queue}")

def main():
queue_operations()

if __name__ == "__main__":
main()

43
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

OUTPUT

Queue items are deque(['Java', 'C', 'Python'])


Adding few items to Queue
Queue items are deque(['Java', 'C', 'Python', 'PHP', 'C#'])
Removed item from Queue is Java
Removed item from Queue is C
Queue items are deque(['Python', 'PHP', 'C#'])

10. Write a note on nested lists.

A list inside another list is called a nested list. A nested list is created by placing a comma-separated
sequence of sublists.
The for loop is used to traverse through the items of nested lists.

The syntax for nested lists is,


Nested_list =[ [item1,item2], [item3,item4,item5],[item6,item7] ]

Example:

L = ['a', 'b', ['cc', 'dd', ['eee', 'xyz']], 'g', 'h']


>>> L[0]
a

>>> L[1]
b

>>> L[2]
['cc', 'dd', ['eee', 'xyz']]

We can access an item inside a list that is itself inside another list by chaining two sets of square brackets
together.

>>> L[2][0]
'cc'
>>> L[2][1]
'dd'
>>> L[2][2]
['eee', 'xyz']

>>> L[2][2][0]
'eee'
>>> L[2][2][1]

44
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

'xyz'

11. With example explain how to Access and Modify key:value Pairs in Dictionaries
Each individual key:value pair in a dictionary can be accessed through keys by specifying it inside
square brackets. The key provided within the square brackets indicates the key:value pair being accessed.

The syntax for accessing the value for a key in the dictionary is,
dictionary_name[key]

The syntax for modifying the value of an existing key or for adding a new key:value pair to a dictionary
is,
dictionary_name[key] = value

If the key is already present in the dictionary, then the key gets updated with the new value.
If the key is not present then the new key:value pair gets added to the dictionary.

Example:
>>>data= {1:'Java', 2:'Python', 3:'C'}
>>>print(data)
{1: 'Java', 2: 'Python', 3: 'C'}

>>>data[3]='C#'
>>>print(data)
{1: 'Java', 2: 'Python', 3: 'C#'}

>>>data[4]='PHP'
>>>print(data)
{1: 'Java', 2: 'Python', 3: 'C#', 4: 'PHP'}

12. Explain any five dictionary methods with syntax.

Dictionary Syntax Description


Methods
clear() dictionary_name.clear() The clear() method removes all the key:value
pairs from the dictionary.

get() dictionary_name.get(key[, default]) The get() method returns the value associated
with the specified key in the dictionary. If the
key is not present then it returns the default
value. If default is not given, it defaults to None,
so that this method never raises a KeyError.

items() dictionary_name.items() The items() method returns a new view of


dictionary’s key and value pairs as tuples.

45
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

keys() dictionary_name.keys() The keys() method returns a new view consisting


of all the keys in the dictionary.

pop() dictionary_name.pop(key[, default]) The pop() method removes the key from the
dictionary and returns its value. If the key is not
present, then it returns the default value. If
default is not given and the key is not in the
dictionary, then it results in KeyError.

values() dictionary_name.values() The values() method returns a new view


consisting of all the values in the dictionary.

13. Write a Python Program to Dynamically Build dictionary using User Input as a List

items_of_list = []
total_items = int(input("Enter the number of items: "))
for i in range(total_items):
item = input("Enter list item: ")
items_of_list.append(item)
print(f"List items are {items_of_list}")

OUTPUT

Enter the number of items: 3

Enter list item: Java

Enter list item: PHP

Enter list item: Python


List items are ['Java', 'PHP', 'Python']

14. Explain with example how to traverse dictionary using key:value pair

A for loop can be used to iterate over keys or values or key:value pairs in dictionaries.
• By default, for loop will iterate over the keys in a dictionary.
• To iterate over the values, use values() method.

46
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

• To iterating over the key:value pairs, the dictionary’s items() method must be specified.

>>> country = {1:"India", 2:"USA", 3:"Russia", 4:"UK"}

>>> for k in country:


print(k)
1
2
3
4

>>> for v in country.values():


print(v)
India
USA
Russia
UK

>>> for k,v in country.items():


print(k,v)
1 India
2 USA
3 Russia
4 UK

15. Write a note on indexing and slicing tuples

Each item in a tuple can be called individually through indexing. The expression inside the bracket is
called the index. Square brackets [ ] are used by tuples to access individual items, with the first item at
index 0, the second item at index 1 and so on. The index provided within the square brackets indicates
the value being accessed.\

The syntax for accessing an item in a tuple is,


tuple_name[index]
where index should always be an integer value and indicates the item to be selected.

In addition to positive index numbers, you can also access tuple items using a negative index number, by
counting backwards from the end of the tuple, starting at −1.

Example:

>>> months=('Jan','Feb','Mar','Apr','May','Jun')
>>> months[1]
'Feb'

47
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

>>> months[-3]
'Apr'

Slicing of tuples is wherein a part of the tuple can be extracted by specifying an index range along with
the colon (:) operator, which itself results as tuple type.

The syntax for tuple slicing is,


tuple_name[start:stop[:step]]

• both start and stop are integer values (positive or negative values).
• Tuple slicing returns a part of the tuple from the start index value to stop index value
• It includes the start index value but excludes the stop index value.
• The step specifies the increment value to slice by and it is optional.
• Colon is used to specify range values

Example:

>>> months=('Jan','Feb','Mar','Apr','May','Jun')
>>> months[1:5:2]
('Feb', 'Apr')

16. Write a Python program to populate tuple with user input data.

new_list=list()
total_items = int(input("Enter the total number of items: "))
for i in range(total_items):
item = input("Enter an item to add: ")
new_list.append(item)
new_tuple=tuple(new_list)
print("New List:",new_list)
print("New tuple :",new_tuple)

OUTPUT

Enter the total number of items: 3

Enter an item to add: apple


Enter an item to add: orange
Enter an item to add: lemon

New List: ['apple', 'orange', 'lemon']


New tuple : ('apple', 'orange', 'lemon')

48
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

17. Explain any Five set methods.

Set Methods Syntax Description


add() set_name.add(item) The add() method adds an item to the set set_name.
clear() set_name.clear() The clear() method removes all the items from the set
set_name.

difference() set_name.difference(*others) The difference() method returns a new set with items
in the set set_name that are not in the others sets.
intersection() set_name.intersection(*others) The intersection() method returns a new set with
items common to the set set_name and all others sets.
pop() set_name.pop() The method pop() removes and returns an arbitrary
item from the set set_name. It raises KeyError if the
set is empty.

union() set_name.union(*others) The method union() returns a new set with items from
the set set_name and all others sets.

49
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

UNIT III
Two Mark questions

1. List file types supported by Python. Give example for each


Python supports two types of files – text files and binary files.
The bits in binary files represent custom data.
Example : such as image(jpg, png, gif), video(mp4, avi, mov) and audio (mp3, aac, wav) data files.

The bits in text files represent characters.


Example:web standards (html, xml, css,), source code( c, cpp, py, java), documents( txt, tex,
markdown, asciidoc, rtf) etc

2. List any four file access modes in Python.

Mode Description
“r” Opens the file in read only mode and this is the default mode.

“w” Opens the file for writing. If a file already exists, then it’ll get overwritten. If
the file does not exist, then
it creates a new file.

“a” Opens the file for appending data at the end of the file automatically. If the file
does not exist it creates
a new file.

“r+” Opens the file for both reading and writing.

3. Give the syntax of with statement to open the file.


When a file is opened using open() function, it returns a file object called a file handler that provides
methods for accessing the file.
Syntax:
file_handler = open(filename, mode)

• The open() function returns a file handler object for the file name.
• the first argument filename is a string containing the file name to be opened which can be
absolute or relative to the current working directory.
• The second argument mode is another string containing a few characters describing the way in
which the file will be used The mode argument is optional; r will be used if it is omitted.

50
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

4. List any two file object attributes and mention its purpose.

Attribute Description
file_handler.closed It returns a Boolean True if the file is closed or False otherwise
file_handler.mode It returns the access mode with which the file was opened.
file_handler.name It returns the name of the file.

5. What is use of seek() and tell() methods.


The seek() method is used to set the file handler’s current position.
The tell() method returns the file handler’s current position. The tell() method returns an integer giving
the file handler’s current position in the file.

6. Give syntax of constructor definition in Python.


Python uses a special method called a constructor method. Only one constructor per class can be
defined. Also known as the __init__() method, it will be the first method definition of a class. The
__init__() method defines and initializes the instance variables. It is invoked as soon as an object of a
class is instantiated. self parameter is a reference to the current instance of the class.

Syntax to define a constructor method:


def __init__(self, parameter_1, parameter_2, …., parameter_n):
statement(s)

7. What is self-variable ?
Self variable is a reference to the current instance of the class. It is the first parameter of methods in a
class. Though the self-variable is not explicitly passed as an argument, whenever you call a method
using an object, the object itself is automatically passed in as the first parameter to the self-parameter
variable.

8. How to return object from a method ? Give example


Iin Python is an object, including classes. The id() function is used to find the identity of the location of
the object in memory. The isinstance() function is used to check whether an object is an instance of a
given class or not.

Example:
class Rectangle:
def __init__(self,l,b):
self.length=l
self.breadth=b

def calculateArea(self):
self.area = self.length * self.breadth
return self

51
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

r1=Rectangle(2,3)
rect = r1.calculateArea()
print(rect.area)
print("Is point an instance of Circle Class?", isinstance(r1, Rectangle))
print("Is returned_object an instance of Circle Class?",isinstance(rect,Rectangle))

OUTPUT:
6
Is point an instance of Circle Class? True
Is returned_object an instance of Circle Class? True

9. How to define private instance variables and methods in Python.


Instance variables or methods, which can be accessed within the same class and can’t be seen outside,
are called private instance variables or private methods.
In Python, an identifier prefixed with a double underscore (e.g., __spam) and with no
trailing underscores should be treated as private (whether it is a method or an instance variable).
Any identifier of the form __spam is textually replaced with _ classname__spam, where classname is the
current class name .

10. What is multipath inheritance ?


When a class is derived from two or more classes which are derived from the same base class then such type
of inheritance is called multipath inheritance.

52
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

10. What is purpose of super() method in inheritance ?


The built-in super() function can be used to refer to base classes without naming them explicitly,
thus making the code more maintainable.
The super() function is useful for accessing the base class methods that have been overridden in a
derived class without explicitly specifying the base class name.
Syntax for using the super() function to invoke the base class method:
super().invoke_base_class_method(argument(s))

11. Give the general syntax of multiple inheritance.


General syntax of multiple inheritance:
class DerivedClassName(Base_1, Base_2, Base_3):
<statement-1>
.
.
.
<statement-N>

Derived class DerivedClassName is inherited from multiple base classes, Base_1, Base_2,Base_3.

12. What is operator Overloading ?


Operator Overloading is a specific case of polymorphism, where different operators have different
implementations depending on their arguments.
A class can implement certain operations that are invoked by special syntax (such as arithmetic
operations
or subscripting and slicing) by defining methods with special names called “Magic methods”. It allows
classes to define their own behavior with respect to language operators.

14. What is root window? How it is created in Python?


Root window is the highest level GUI component in a tkinter application.
Syntax to create root window or top level window:
from tkinter import *
root = Tk() # creates root window, object of Tk class
root.mainloop() #wait and watch for any event to that may take place in the root widow

15. What is Canvas? How it is created in Python?


Canvas is a container that is generally used to draw shapes,curves, arcs and circles.
Syntax to create a basic canvas:
from tkinter import *
root =Tk()
c=Canvas(root, bg="blue",height=700,width=1200, cursor='pencil')

53
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

#create a canvas as child to root window

c.pack()
#add canvas to the root window to make it visible

root.mainloop()

16. Differentiate Canvas and frame.


Canvas is a container that is generally used to draw shapes, curves, arcs and circles.
Syntax:
c=Canvas(root, bg="blue",height=700,width=1200, cursor='pencil')

Frame is a container is generally used to display widgets like buttons, check buttons or menus.
Syntax:
f = Frame(root, height=200, width=300)

17. How to add a scrollbar to a Text widget?


A scroll bar is a widget that is useful to scroll the text in another widget. For example, the text in the
Text, Canvas, Frame or Listbox can be scrolled from top to bottom or left to right using scroll bars.
There are two types of scroll bars. They are horizontal and vertical. The horizontal scroll bar is useful to
view the text from left to right. The vertical scroll bar is useful to scroll the text from top to bottom.

To create a scroll bar, we have to create Scrollbar class object as:


h = Scrollbar(root, orient=HORIZONTAL, bg='green', command=t.xview)

18. Differentiate Label and Text Widget.


Text widget is same as a label or message. But Text widget has several options and can display multiple
lines of text in different colors and fonts.It is possible to insert text into a Text widget, modify it or delete
it. We can also display images in the Text widget. One can create a Text widget by creating an object to
Text class as:
t = Text(root, width=20, height=10, font=('Verdana', 14, 'bold'), fg='blue', bg='yellow',
wrap=WORD)

Label widget is used to create a label represents that constant text that is displayed in the frame or
container. It can display one or more lines of text that cannot be modified.
A label is created as an object of Label class as follows:
bl2 = Label(self.f, text="Python Programming", width=20, height=2,
font=('Courier', 30, 'bold underline'), fg='blue')

19. What is an entry widget? How it is created?


Entry widget is useful to create a rectangular box that can be used to enter or display one line of text. For
example, we can display names, passwords or credit card numbers using Entry widgets.
54
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

An Entry widget can be created as an object of Entry class as:


e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show='*')

20. What is a spin box widget? How it is created?


A Spinbox widget allows the user to select values from a given set of values. The spin box appears as a
long rectangle attached with arrowheads pointing towards up and down. The user can click on the
arrowheads to see the next value or previous value.
To create a spin box with numbers ranging from 5 to 15, we can write the following statement:
s1 = Spinbox(f, from_= 5, to=15, textvariable=val1, width=15, fg='blue', bg='yellow',
font=('Arial', 14, 'bold'))

21. List the values that can be assigned to selectmode property of listbox
The option 'selectmode' may take any of the following values:
i) BROWSE : To can select one item (or line) out of a list box
ii) SINGLE : To select only one item( or line) from all available list of items
iii) MULTIPLE : To select 1 or more number of items at once by clicking on the items.
iv) EXTENDED : To select any adjacent group of items at once by clicking on the first item and
dragging to the last item.

Long Answer Questions


1. List and explain various file opening modes with examples.

Mode Description Example


“r” Opens the file in read only mode and this is the filename=open(“Example1.txt”, “r”)
default mode.
“w” Opens the file for writing. If a file already filename=open(“Example1.txt”, “w”)
exists, then it’ll get overwritten. If the file does
not exist, then it creates a new file.
“a” Opens the file for appending data at the end of filename=open(“Example1.txt”, “a”)
the file automatically. If the file does not exist
it creates a new file.
“r+” Opens the file for both reading and writing. filename=open(“Example1.txt”, “r+”)
“w+” Opens the file for reading and writing. If the filename=open(“Example1.txt”, “w+”)
file does not exist it creates a new file. If a file
already exists then it will get overwritten.
“a+” Opens the file for reading and appending. If a filename=open(“Example1.txt”, “a+”)
file already exists, the data is appended. If the
file does not exist it creates a new file.
“x” Creates a new file. If the file already exists, the filename=open(“Example1.txt”, “x”)
operation fails.
“rb” Opens the binary file in read-only mode. filename=open(“Example1.txt”, “rb”)

55
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

“wb” Opens the file for writing the data in binary filename=open(“Example1.txt”, “wb”)
format.
“rb+” Opens the file for both reading and writing in filename=open(“Example1.txt”, “rb+”)
binary format.

2. With program example explain how ‘with’ statement is used to open and close files
Instead of using try-except-finally blocks we can use the with statement to handle file opening and
closing operations. When we use a with statement in Python we do not have to close the file handler
object.
The syntax of the with statement for the file I/O is,
with open (file, mode) as file_handler:
Statement_1
Statement_2
...
Statement_N
Example:
Quotes.txt
Where there is will, there is way.
Honesty is the best policy.

Fileprg2.py
print("Printing each line in text file:")
with open("quotes.txt") as file_handler:
for each_line in file_handler:
print(each_line)

OUTPUT

Printing each line in text file:

Where there is will, there is way.


Honesty is the best policy.

3. With code example explain any two methods to read data from the file.

Quotes.txt
Where there is will, there is way.
Honesty is the best policy.

56
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

1)Method: read()
Syntax: file_handler.read([size])
Description: This method is used to read the contents of a file up to a size and return it as a string. The
argument size is optional, and, if it is not specified, then the entire contents of the file will be read and
returned.

Example:
filename=open("quotes.txt","r")
x=filename.read()
print(x)
filename.close()

OUTPUT:
Where there is will, there is way.
Honesty is the best policy.

2) Method: readline()

Syntax: file_handler.readline()

Description: This method is used to read a single line in file.

Example:
filename=open("quotes.txt","r")
x=filename.readline()
print(x)
filename.close()

OUTPUT:
Where there is will, there is way.

4. With Code example explain any two methods to write data to the file.
1)Method: write()
Syntax: file_handler.write(string)

Description: This method will write the contents of the string to the file, returning the number of
characters written. If you want to start a new line, you must include the new line character.

Example:
filename=open("moon.txt","w")
filename.write("Moon is a natural satellite of the earth.")
filename.close()

57
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

OUTPUT:
moon.txt
Moon is a natural satellite of the earth.

2) Method: writelines()

Syntax: file_handler.writelines(sequence)

Description: This method will write a sequence of strings to the file.

Example:

filename=open("moon.txt","w")
filename.writelines(["Moon"," ","is a natural satellite"," ", "of the
earth."])
filename.close()

OUTPUT:
moon.txt
Moon is a natural satellite of the earth.

5. Write Python Program to Count the Occurrences of Each Word and Also Count the Number
of Words in a text File.

Quotes.txt

Where there is will, there is way.

Honesty is the best policy.

58
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Prg1.py

def main():
filename=input("Enter the filename:")
occurrence_of_words = dict()
total_words = 0
with open(filename,"r") as file_handler:
for row in file_handler:
words = row.rstrip().split()
total_words += len(words)
for each_word in words:
occurrence_of_words[each_word] =
occurrence_of_words.get(each_word, 0) + 1
print("The number of times each word appears in a sentence is")
print(occurrence_of_words)
print(f"Total number of words in the file are {total_words}")

if __name__ == "__main__":
main()

OUTPUT:

Enter the filename: quotes.txt


The number of times each word appears in a sentence is
{'Where': 1, 'there': 2, 'is': 3, 'will,': 1, 'way.': 1, 'Honesty': 1, 'the': 1, 'best': 1, 'policy.': 1}
Total number of words in the file are 12

6. Explain declaring a class, defining an object and constructor with syntax and example.
A class is a blueprint from which individual objects are created.
An object is a bundle of related state (variables) and behavior (methods).
Objects contain variables, which represents the state of information about the thing you are trying to
model, and the methods represent the behavior or functionality that you want it to have.

59
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Syntax to declare a class:


Class ClassName:
Statement1
:
:
StatementN

Object refers to a particular instance of a class where the object contains variables(attributes) and
methods defined in the class. The act of creating an object from a class is called instantiation.

Syntax to create an object(instantiation):


object_name = ClassName(argument_1, argument_2, ….., argument_n)
Here (argument_1, argument_2, ….., argument_n) are optional.

The syntax to access data attribute is,


object_name.data_attribute_name

The syntax to assign value to data attribute is,


object_name.date_attribute_name = value

where value can be of integer, float, string types, or another object itself.

The syntax to call method attribute is,


object_name.method_attribute_name()

Python uses a special method called a constructor method. Only one constructor per class can be
defined. Also known as the __init__() method, it will be the first method definition of a class. The
__init__() method defines and initializes the instance variables. It is invoked as soon as an object of a
class is instantiated. self parameter is a reference to the current instance of the class.

Syntax to define a constructor method:


def __init__(self, parameter_1, parameter_2, …., parameter_n):
statement(s)

Example:
class Student:
def __init__(self,n,r):
self.name=n
self.regno=r

def display(self):
print("Name:",self.name)
print("RegNo:",self.regno)

s1=Student("Kiran",45)
s1.display()

60
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

OUTPUT:
Name: Kiran
RegNo: 45

7. What is inheritance? How to implement inheritance in Python? Give an example


Inheritance enables new classes to receive or inherit variables and methods of existing classes.
A class that is used as the basis for inheritance is called a superclass or base class. A class that inherits
from a base class is called a subclass or derived class. A derived class inherits variables and methods
from its base class while adding additional variables and methods of its own.

The syntax for a derived class definition looks like this:


class DerivedClassName(BaseClassName):
<statement-1>
...
<statement-N>
Example:

# Base class
class Vehicle:
def vehicle_info(self):
print('Inside Vehicle class')

# Child class
class Car(Vehicle):
def car_info(self):
print('Inside Car class')

# Create object of Car


car = Car()

# access Vehicle's info using car object


car.vehicle_info()
car.car_info()

OUTPUT:

Inside Vehicle class


Inside Car class

In the above example, Vehicle is the base class and Car is the derived class. Car inherits base class
method
vehicle_info().

61
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

By creating an object of the Cat class we can access both the base class method vehicle_info() and
derived class method car_info().

8. Explain with example overriding superclass constructor and method


When the programmer writes a constructor in the sub class, the super class constructor is not available to
the sub class . In this case, only the sub class constructor is accessible from the sub class object. That
means the sub class constructor is replacing the super class constructor. This is called constructor
overriding .

Example:

class Bank:
def __init__(self):
self.interest = 0.12

class SBI(Bank):
def __init__(self):
self.interest = 0.15

sbi_obj=SBI()
print("Interest:",sbi_obj.interest)

OUTPUT

Interest: 0.15

In the above example, the constructor of the derived class SBI overrides the base class constructor.
While creating the derived class object, sbi_object, the value of interest is initialized as 0,15 instead of
0.12.
Similarly in the sub class, if we write a method with exactly same name as that of super class method, it
will override the super class method. This is called method overriding .

Example:

class Bank:
def __init__(self):
self.interest = 0.12
def display(self):
print("Bank Details")

class SBI(Bank):
def __init__(self):
self.interest = 0.15

def display(self):
print("SBI bank details")
62
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

sbi_obj=SBI()
sbi_obj.display()

OUTPUT

SBI bank details

In the above example, the display() method of derived class overrides the display() method of the base
class. Hence the object of derived class sbi_obj calls the display() method of derived class instead of the
display() method of the base class.

9. Explain multi-level inheritance with example.


Multi-level inheritance is archived when a derived class inherits another derived class.
There is no limit on the number of levels up to which, the multi-level inheritance is archived in python.
Syntax:
class base1 :
body of base class

class derived1( base1 ) :


body of derived class

class derived2( derived1 ) :


body of derived class
Example:

class Parent:
def pt_display(self):
print("Inside Parent class")

class Child(Parent):
def ch_display(self):
print("Inside Child class")

class GrandChild(Child):
def gc_display(self):
print("Inside GrandChild class")

grandch = GrandChild()

grandch.pt_display()
grandch.ch_display()
grandch.gc_display()

63
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

OUTPUT:

Inside Parent class


Inside Child class
Inside GrandChild class

In the above example, Parent is the base class. Derived class Child inherits all Parent class members. The
derived class GrandChild inherits from the class Child .Hence Grandchild class inherits both Child class
members and Parent class members.

10. Explain multiple inheritance in Python with an example.


When a class is derived from more than one base class it is called multiple Inheritance. The derived class
inherits all the features of the base case.
Syntax:
class DerivedClassName(Base_1, Base_2, Base_3):
<statement-1>
.
.
<statement-N>

Example:
class Car:
def Benz(self):
print("This is a Benz Car ")

class Bike:
def Bmw(self):
print("This is a BMW Bike ")

class Bus:
def Volvo(self):
print("This is a Volvo Bus ")

class Transport(Car,Bike,Bus):
def dispay(self):
print("This is the Transport Class")

64
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

trans= Transport()
trans.Benz()
trans.Bmw()
trans.Volvo()
trans.dispay()

OUTPUT
This is a Benz Car
This is a BMW Bike
This is a Volvo Bus
This is the Transport Class

In the above there are three base classes – Car, Bike and Bus. The derived class Transport derives all the
three class. Hence it inherits all its methods – Benz(), Bmw() and Volvo respectively.
By creating a derived class object (trans) we can access all base class and derived class methods.

11. Explain multipath inheritance with example.


When a class is derived from two or more classes which are derived from the same base class then such type
of inheritance is called multipath inheritance.

Example:
class University:
def __init__(self):
print("Constructor of the Base class")
def display(self):
print(f"The University Class display method")

class Course(University):
def __init__(self):
print("Constructor of the Child Class 1 of Class University")
super().__init__()
def display(self):
print(f"The Course Class display method")
super().display()

65
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

class Branch(University):
def __init__(self):
print("Constructor of the Child Class 2 of Class University")
super().__init__()
def display(self):
print(f"The Branch Class display method ")
super().display()

class Student(Course, Branch):


def __init__(self):
print("Constructor of Child class of Course and Branch is called")
super().__init__()
def display(self):
print(f"The Student Class display method")
super().display()

ob = Student()
print()
ob.display()

OUTPUT:

Constructor of Child class of Course and Branch is called


Constructor of the Child Class 1 of Class University
Constructor of the Child Class 2 of Class University
Constructor of the Base class

The Student Class display method


The Course Class display method
The Branch Class display method
The University Class display method

12. Explain method overloading and overriding with example


In the case of method overloading, more than a single method belonging to a single class can share a
similar method name while having different signatures.
Python Method Overloading
If a method is written such that it can perform more than one task, it is called method overloading.

Example:
66
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

class Myclass:
def sum(self, a=None, b=None, c=None):
if a!=None and b!=None and c!=None:
print('Sum of three=', a+b+c)
elif a!=None and b!=None:
print('Sum of two=', a+b)
else:
print('Please enter two or three arguments')

m = Myclass()
m.sum(10, 15, 20)
m.sum(10.5, 25.55)
m.sum(100)

OUTPUT

Sum of three= 45
Sum of two= 36.05
Please enter two or three arguments

In the first call, we are passing two arguments and in the second call, we are passing three arguments.
It means, the sum() method is performing two distinct operations: finding sum of two numbers or sum
of three numbers. This is called method overloading.

Python method overriding :


Similarly in the sub class, if we write a method with exactly same name as that of super class
method, it will override the super class method. This is called method overriding .

A Python program to override the super class method in sub class.


class Bank:
def __init__(self):
self.interest = 0.12
def display(self):
print("Bank Details")

class SBI(Bank):
def __init__(self):
self.interest = 0.15

def display(self):
print("SBI bank details")

67
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

sbi_obj=SBI()
sbi_obj.display()

OUTPUT

SBI bank details

In the above example, the display() method of derived class overrides the display() method of the base
class. Hence the object of derived class sbi_obj calls the display() method of derived class instead of the
display() method of the base class.

13. Explain the steps involved in creating a GUI application in Python with a suitable example.
Python offers tkinter module to create graphics programs. tkinter represents 'toolkit interface' for GUI. It
is an interface for Python programmers that enable them to use the classes of TK module of TCL/TK
language.
The TCL (Tool Command Language) is a powerful dynamic programming language, suitable for web
and desktop applications, networking, administration, testing and many more. It is open source and
hence can be used by any one freely. TCL language uses TK (Tool Kit) language to generate graphics.
TK provides standard GUI not only for TCL but also for many other dynamic programming languages
like Python.

The following are the general steps involved in basic GUI programs:
1. Create the root window. The root window is the top level window that provides rectangular space
on the screen where we can display text, colors, images, components, etc.
2. In the root window, allocate space for our use. This is done by creating a canvas or frame.
Canvas and frame are child windows in the root window.
3. Generally, we use canvas for displaying drawings like lines, arcs, circles, shapes, etc. We use
frame for the purpose of displaying components like push buttons, check buttons, menus, etc.
These components are also called 'widgets'.
4. When the user clicks on a widget like push button, we have to handle that event. It means we
have to respond to the events by performing the desired tasks.

14. How to create a button widget and bind it to the event handler? Explain with example.
A push button is a component that performs some action when clicked. These buttons are created as
objects of Button class as:
b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue',
activebackground='green', activeforeground='red')

We can also display an image on the button as:


#first load the image into file1
file1 = PhotoImage(file="cat.gif")

68
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

#create a push button with image

b = Button(f, image=file1, width=150, height=100, bg='yellow', fg='blue',


activebackground='green', activeforeground='red')

Example:
A Python program to create a push button and bind it with an event handler function.

from tkinter import *

def buttonClick(self):
print('You have clicked me')

root = Tk()
f = Frame(root, height=200, width=300)
f.propagate(0)
f.pack()
b = Button(f, text='My Button', width=15, height=2, bg='yellow', fg='blue',
activebackground='green', activeforeground='red')
b.pack()
b.bind("<Button-1>", buttonClick)
root.mainloop()

15. Write a note on arranging Widgets in a frame using layout managers.


Once we create widgets or components, we can arrange them in the frame in a particular manner.
Arranging the widgets in the frame is called 'layout management'. There are three types of layout
managers.
• Pack layout manager
• Grid layout manager
• Place layout manager

Pack layout manager uses pack() method. This method is useful to associate a widget with its parent
component. While using the pack() method, we can mention the position of the widget using 'fill' or
'side' options.
b.pack(fill=X)
b.pack(fill=Y)
The 'fill' option can take the values: X, Y, BOTH, NONE.
The value X represents that the widget should occupy the frame horizontally and the value Y represents
that the widget should occupy vertically.
BOTH represents that the widget should occupy in both the directions.
NONE represents that the widget should be displayed as it is. The default value is NONE.
Along with 'fill' option, we can use 'padx' and 'pady' options that represent how much space should be
left around the component horizontally and vertically.
For example:
b1.pack(fill=Y, padx=10, pady=15)

69
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Grid layout manager uses the grid() method to arrange the widgets in a two dimensional table that
contains rows and columns. The horizontal arrangement of data is called 'row' and vertical arrangement
is called 'column'. The position of a widget is defined by a row and a column number. The size of the
table is determined by the grid layout manager depending on the widgets size.
For example,
b1.grid(row=0, column=0, padx=10, pady=15)

Place layout manager uses the place() method to arrange the widgets. The place() method takes x and y
coordinates of the widget along with width and height of the window where the widget has to be
displayed.
For example,
b1.place(x=20, y=30, width=100, height=50)

16. Explain the process of creating a Listbox widget with a suitable example. Also, explain
different values associated with selectmode option.
A list box is useful to display a list of items in a box so that the user can select 1 or more items.To create
a list box, we have to create an object of Listbox class, as:

lb = Listbox(f, font="Arial 12 bold", fg='blue', bg='yellow', height=8,


width=24, activestyle='underline', selectmode=MULTIPLE)

Here, 'lb' is the list box object.


The option 'height' represents the number of lines shown in the list box.
'width' represents the width of the list box in terms of number of characters and the default is 20
characters.
The option 'activestyle' indicates the appearance of the selected item.It may be 'underline', dotbox' or
'none'.The default value is 'underline'.
The option 'selectmode' may take any of the following values:
• BROWSE: Normally, we can select one item (or line) out of a list box.If we click on an item and
then drag to a different item, the selection will follow the mouse.This is the default value of
'selectmode' option.
• SINGLE: This represents that we can select only one item( or line) from all available list of
items.
• MULTIPLE: We can select 1 or more number of items at once by clicking on the items. If an
item is already selected, clicking second time on the item will un-select it.
• EXTENDED: We can select any adjacent group of items at once by clicking on the first item
and dragging to the last item.

17. Write a note on


i) Text Widget ii) Entry Widget

Python Text Widget

70
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Text widget is same as a label or message. But Text widget has several options and can display multiple
lines of text in different colors and fonts.It is possible to insert text into a Text widget, modify it or delete
it. We can also display images in the Text widget.
One can create a Text widget by creating an object to Text class as:

t = Text(root, width=20, height=10, font=('Verdana', 14, 'bold'), fg='blue',


bg='yellow', wrap=WORD)

't' represents the object of Text class.


'root' represents an object of root window or frame.
'width' represents the width of the Text widget in characters.
'height' represents the height of the widget in lines.
The option 'wrap' specifies where to cut the line.
• wrap=CHAR represents that any line that is too long will be broken at any character.
• wrap=WORD will break the line in the widget after the last word that fits in the line.
• wrap=NONE will not wrap the lines. In this case, it is better to provide a horizontal scroll
bar to view the lines properly in the Text widget.

Python Entry Widget


Entry widget is useful to create a rectangular box that can be used to enter or display one line of text. For
example, we can display names, passwords or credit card numbers using Entry widgets. An Entry widget
can be created as an object of Entry class as:
e1 = Entry(f, width=25, fg='blue', bg='yellow', font=('Arial', 14), show='*')

• f - Frame
• bg - background color
• fg - foreground color

71
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

UNIT IV

Two Mark questions


1. How to connect to the SQLite database ? Give example

To use SQLite3 in Python, first we have to import the sqlite3 module and then create a connection
object. Connection object allows to connect to the database and will let us execute the SQL statements.

Creating Connection object using the connect() function:


import sqlite3
con = sqlite3.connect('mydatabase.db')

The above code will create a new file with the name ‘mydatabase.db’.

2. Write SQL code to create table in SQLite database.


To create a table in SQLite3, you can use the Create Table query in the execute() method. Consider the
following steps:
1. Create a connection object.
2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table query as the parameter.
Code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

cursorObj.execute('''CREATE TABLE movie(title text, year int, score


real)''')

con.commit()
con.close()

In the above code, it establishes a connection and creates a cursor object to execute the create table
statement.

72
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

The commit() method saves all the changes we make.

3. Write SQL code to insert data in SQLite table.


To insert data in a table, we use the INSERT INTO statement.
Code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

cursorObj.execute('''CREATE TABLE movie(title text, year int, score


real)''')

cursorObj.execute('''INSERT INTO movie VALUES ("Titanic",1997, 9.5)''')

con.commit()
con.close()

4. Write SQL code to update SQLite table.


To update the table, simply create a connection, then create a cursor object using the connection and
finally use the UPDATE statement in the execute() method.
Code:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Spider' ")
con.commit()
con.close()

5. What is NumPy in Python ? Give any two uses of NumPy.


NumPy is the fundamental package for scientific computing with Python. It stands for

73
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

“Numerical Python.” It supports:


• N-dimensional array object
• Broadcasting functions
• Tools for integrating C/C++ and Fortran code
• Useful linear algebra, Fourier transform, and random number capabilities

6. Give Python code to create NumPy array using array function.


NumPy array can be created from a regular Python list or tuple using the np.array() function.
The type of the resulting array is deduced from the type of the elements.

Eg1:
import numpy as np
a=np.array([[1,2,3],[5,6,7]])
print(a)

OUTPUT:
[[1 2 3]
[5 6 7]]

Eg2:
b=np.array([(1,2,3),(5,6,7)])
print(b)

OUTPUT:
[[1 2 3]
[5 6 7]]

7. How to create two-dimensional arrays using NumPy.


import numpy as np
a=np.array([[1,2,3],[5,6,7]])
print(a)
print("a.ndim:",a.ndim)

OUTPUT:
[[1 2 3]
[5 6 7]]
a.ndim: 2

74
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

8. List any four NumPy array attributes. (Any 4)

ndarray Description
Attributes
ndarray.ndim Gives the number of axes or dimensions in the array
ndarray.shape Gives the dimensions of the array. For an array with n rows and m columns,
shape will be a tuple of integers (n, m).
ndarray.size Gives the total number of elements of the array.
ndarray.dtype Gives an object describing the type of the elements in the array.
ndarray.itemsize Gives the size of each element of the array in bytes.
ndarray.data Gives the buffer containing the actual elements of the array.

9. Give syntax and example for NumPy arrange() function


arange() returns evenly spaced values within a given interval where
• start (a number and optional) is the start of interval and its default value is zero,
• stop (a number) is the end of interval,
• step (a number and is optional) is the spacing between the values and dtype is the type of output
array.

The syntax for arange() is,


np.arange([start,]stop, [step,][dtype=None])

EG:

k=np.arange(0,50,7)
print(k)

OUTPUT:
[ 0 7 14 21 28 35 42 49]

10. What is Pandas Library ?


pandas is a Python library that provides fast, flexible, and expressive data structures. The two primary
data structures of pandas, Series (one-dimensional) and DataFrame (two-dimensional). pandas is built
on top of NumPy.
pandas is well suited for inserting and deleting columns from DataFrame, for handling of missing data
(represented as NaN) etc. It has robust input/output tools for loading data from CSV files, Excel files,
databases, and other formats.

11. What is Pandas Series ? Give example.

75
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

Series is a one-dimensional labeled array capable of holding any data type (integers, strings,floating
point numbers, Python objects, etc.). The axis labels are collectively referred to as the index. Pandas
Series is created using series() method.

Syntax:
s = pd.Series(data, index=None)

• s is the Pandas Series, data can be a Python dict,


• a ndarray, or a scalar value (like 5).
• The passed index is a list of axis labels.
• Both integer and label-based indexing are supported.
• If the index is not provided, then the index will default to range(n) where n is the length of data.

Example:

import numpy as np
import pandas as pd
series1=pd.Series([12,22,32,42,52], index=['a', 'b', 'c', 'd', 'e'])
print(series1)

OUTPUT

a 12
b 22
c 32
d 42
e 52
dtype: int64

12. Write Python code to create Dataframe from a dictionary and display its
contents.

import pandas as pd
data={'Reg':[101,102,103],
'Name':['Akash','Irfan','Kishore'],
'Course':['BCA','BCOM','BCA']}

df=pd.DataFrame(data)
print(df)

OUTPUT

Reg Name Course


0 101 Akash BCA

76
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

1 102 Irfan BCOM


2 103 Kishore BCA

13. Write Python code to create Dataframe from a tuple and display its contents.

data=[(101,'Akash','BCA'),
(102,'Irfan','BCOM'),
(103,'Kishore','BCA')]
df=pd.DataFrame(data)
print(df)

OUTPUT

0 1 2
0 101 Akash BCA
1 102 Irfan BCOM
2 103 Kishore BCA

14. What is Pandas DataFrame ? How it is created ?


DataFrame is a two-dimensional, labeled data structure with columns of potentially different types.
It is the most commonly used pandas object. DataFrame accepts many different kinds of input like Dict
of one-dimensional ndarrays, lists, dicts, or Series, two-dimensional ndarrays, structured or record
ndarray, a dictionary of Series, or another DataFrame.

Syntax to create a Dataframe:


df = pd.DataFrame(data=None, index=None, columns=None)
• df is the DataFrame
• data can be NumPy ndarray, dict, or DataFrame.
• index (row labels) and columns (column labels) attributes are optional arguments.

15. Give the Python code to create dataframe from .csv file
import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)

OUTPUT

regno name course CGPA


0 101 Akash BCA 9.4
1 102 Irfan BCOM 8.7
2 103 Kishore BCA 6.7

77
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

16. How to add new column to dataframes ?

import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)

OUTPUT

Regno Name Course CGPA


0 101 Akash BCA 9.4
1 102 Irfan BCOM 8.7
2 103 Kishore BCA 6.7

#Add a column at the end:


df['Mentor']=['Suraj','Harish R', 'Mukesh']
print(df)

OUTPUT

Regno Name Course CGPA Mentor


0 101 Akash BCA 9.4 Suraj
1 102 Irfan BCOM 8.7 Harish R
2 103 Kishore BCA 6.7 Mukesh

#Insert a column in between


df.insert(4,'Year',['III','I','II'])
print(df)

OUTPUT

Regno Name Course CGPA Year Mentor


0 101 Akash BCA 9.4 III Suraj
1 102 Irfan BCOM 8.7 I Harish R
2 103 Kishore BCA 6.7 II Mukesh

17. Give the Python code to create dataframe from Excel file.

import pandas as pd
df = pd.read_excel('StudentData.xlsx')
print(df)

78
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

OUTPUT

Regno Name Course CGPA


0 101 Akash BCA 9.4
1 102 Irfan BCOM 8.7
2 103 Kishore BCA 6.7

18. Give Python code to find maximum and minimum values for particular column
of dataframe.

import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)

highest = df['CGPA'].max()
print("Max:", highest)

lowest = df['CGPA'].min()
print("Max:", lowest)

OUTPUT

Regno Name Course CGPA


0 101 Akash BCA 9.4
1 102 Irfan BCOM 8.7
2 103 Kishore BCA 6.7

Max: 9.4
Max: 6.7

19. What is Data Visualization ?


Data visualization is the graphical representation of information and data. By using visual elements like
charts, graphs, and maps, data visualization tools provide an accessible way to see and understand
trends, outliers, and patterns in data.
The importance of data visualization is simple: it helps people see, interact with, and better understand
data. Whether simple or complex, the right visualization can bring everyone on the same page,
regardless of their level of expertise.

79
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

20. What is matplotlib and pyplot ?


Pyplot is an API (Application Programming Interface) for Python’s matplotlib that effectively makes
matplotlib a viable open-source alternative to MATLAB.
Matplotlib is a library for data visualization, typically in the form of plots, graphs and charts.

Long Answer Questions

1.Explain four SQLite module methods required to use SQLite database.


1) connect():
To use SQLite3 in Python, first we have to import the sqlite3 module and then create a connection
object. Connection object allows to connect to the database and will let us execute the SQL statements.

Creating Connection object using the connect() function:


import sqlite3
con = sqlite3.connect('mydatabase.db')

The above code will create a new file with the name ‘mydatabase.db’.

2) cursor():

To execute SQLite statements in Python, we need a cursor object. We can create it using the cursor()
method.
The SQLite3 cursor is a method of the connection object. To execute the SQLite3 statements, you should
establish a connection at first and then create an object of the cursor using the connection object as
follows:

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()

3) execute() :
Once the database and connection object is created, we can create a table using CREATE TABLE
statement. Then we execute the CREATE TABLE statement by calling cur.execute(...).

import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute(''' CREATE TABLE movie(title text, year int, score real)
''' )

80
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

4) Close()
Once we are done with our database, it is a good practice to close the connection. We can close the
connection by using the close() method.
To close a connection, use the connection object and call the close() method as follows:

con = sqlite3.connect('mydatabase.db')
#program statements
con.close()

2.Explain any four SQLite database operations with example.


I. Creating and connecting to Database
When you create a connection with SQLite, that will create a database file automatically if it doesn’t
already exist. This database file is created on disk with the connect function.
Following Python code shows how to connect to an existing database. If the database does not exist, then
it will be created and finally a database object will be returned.
Eg:
import sqlite3
conn = sqlite3.connect('test.db')
print ("Opened database successfully")

II. Create Table


To create a table in SQLite3, you can use the Create Table query in the execute() method. Consider the
following steps:
1. Create a connection object.
2. From the connection object, create a cursor object.
3. Using the cursor object, call the execute method with create table query as the parameter.
Eg:
import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int, score
real)''')
con.commit()
con.close()

III. Insert in Table


To insert data in a table, we use the INSERT INTO statement. Consider the following line of code:
Eg:
import sqlite3
con = sqlite3.connect('mydatabase.db')

81
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

cursorObj = con.cursor()
cursorObj.execute('''CREATE TABLE movie(title text, year int, score
real)''')
cursorObj.execute('''INSERT INTO movie VALUES ("Titanic",1997, 9.5)''')
con.commit()
con.close()

IV. Update Table


To update the table, simply create a connection, then create a cursor object using the connection and
finally use the UPDATE statement in the execute() method.
Suppose that we want to update the score with the movie title Dil. For updating, we will use the
UPDATE statement and for the movie whose title equals Dil. We will use the WHERE clause as a
condition to select this employee.
Consider the following code:
import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Dil' ")
con.commit()
con.close()

3.Write a Python Program to demonstrate various SQLite Database operations.


#importing the module
import sqlite3

#create connection object


con = sqlite3.connect('studdb.db')

#create a cursor
cursorObj = con.cursor()

#creating the table


cursorObj.execute('''CREATE TABLE Student(Regno, Name, Course)''')

#inserting the data


cursorObj.execute('''INSERT INTO Student VALUES (121,"Akshatha","BCA")''')
cursorObj.execute('''INSERT INTO Student VALUES (221,"Naima","BCOM")''')
cursorObj.execute('''INSERT INTO Student VALUES (321,"Kelly","BA")''')

82
Python Programming, ii BCa , 4 SEmth
BWC, mangalorE

#Print the Initial Data


print("Initial Data...")
cursorObj.execute("SELECT * FROM Student ")
for row in cursorObj.fetchall():
print(row)

#Updating
cursorObj.execute("UPDATE Student SET Course='BBA' WHERE Name='Kelly' ")

#Print the after updating


print("After updating...")
cursorObj.execute("SELECT * FROM Student ")
for row in cursorObj.fetchall():
print(row)

#Deleting
cursorObj.execute("Delete from Student where Regno=321 ")

#Print the after Deleting


print("After deleting...")
cursorObj.execute("SELECT * FROM Student ")
for row in cursorObj.fetchall():
print(row)

#Drop the table


cursorObj.execute(" DROP TABLE IF EXISTS MOVIE ")

#commit changes in the database


con.commit()

#close the connection


con.close()

OUTPUT:

Initial Data...
(121, 'Akshatha', 'BCA')
(221, 'Naima', 'BCOM')
(321, 'Kelly', 'BA')

After updating...
(121, 'Akshatha', 'BCA')
(221, 'Naima', 'BCOM')
(321, 'Kelly', 'BBA')

83
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

After deleting...
(121, 'Akshatha', 'BCA')
(221, 'Naima', 'BCOM')

4.Explain any five NumPy array attributes with syntax.(Any 5)


1. ndarray.ndim : Gives the number of axes or dimensions in the array
Syntax: ndarray.ndim
Example:

import numpy as np
x = np.array([[1,2,3], [4,5,6]])
x.ndim

Output:
2

2. ndarray.shape : Gives the dimensions of the array. For an array with n rows and m columns, shape will
be a tuple of integers (n, m).
Syntax: ndarray.shape
Example:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
x.shape

Output:
(2, 3)

3. ndarray.size : Gives the total number of elements of the array.


Syntax : ndarray.size
Example:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
x.size

Output:
6

84
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

4. ndarray.dtype : Gives an object describing the type of the elements in the array. One can create or
specify dtype’s using standard Python types. Additionally, NumPy provides its own types like np.int32,
np.int16, np.float64, and others.
Syntax: ndarray.dtype
Example:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
x.dtype

Output:
dtype('int32')

5.ndarray.itemsize: Gives the size of each element of the array in bytes.


Syntax: ndarray.itemsize
Example:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
x.itemsize

Output:
4

6.ndarray.data : Gives the buffer containing the actual elements of the array. This attribute is not used
because to access the elements in an array indexing facilities are used.
Syntax : ndarray.data
Example:
import numpy as np
x = np.array([[1,2,3], [4,5,6]])
x.data

Output:
<memory at 0x000001CD58679EE0>

85
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

5.Explain any four NumPy array creation functions with example.(any 4)


1. np.zeros() : Creates an array of zeros

y=np.zeros((3,3),dtype=int)
print(y)

Output:

[[0 0 0]
[0 0 0]
[0 0 0]]

2. np.ones() : Creates an array of ones

y=np.ones((3,3),dtype=int)
print(y)

Output:

[[1 1 1]
[1 1 1]
[1 1 1]]

3. np.full() : Creates a full array

c=np.full((2,2),7)
print(c)

Output:

[[7 7]
[7 7]]

4. np.eye() : Creates an identity matrix

d=np.eye(4,dtype=int)
print(d)

Output:
[[1 0 0 0]
[0 1 0 0]
[0 0 1 0]
[0 0 0 1]]

86
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

5. np.empty() : Creates an empty array

x=np.empty((2,2))

Output:

array([[0., 0., 0.],


[0., 0., 0.]])

6.Write a note on Indexing, slicing, and iterating operations on NumPy array.


One-dimensional arrays can be indexed, sliced, and iterated over, much like lists and other Python
sequences.

d2=np.arange(10,16)
>>> print(d2)
>>> [10 11 12 13 14 15]
Consider a one-dimensional numpy array d2.
Indexing can be done using both positive and negative indexes .
>>> print(d2[3])
>>> 13
>>> print(d2[-1])
>>> 15
Multiple indexes can also be indexed.
>>> print(d2[[2,4,5,3]])
>>>[12 14 15 13]
Slicing can be done by passing start, stop and split(optional) values.
>>> print(d2[1:4])
>>> [11 12 13]
>>> print(d2[::2])
>>> [10 12 14]

For multi-dimensional arrays you can specify an index or slice per axis.

import numpy as np
>>> d3=np.arange(10,14).reshape(2,2)
>>> print(d3)
>>>
[[10 11]
[12 13]]
>>> print(d3[0,0])
>>> 10
>>> print(d3[0,1])
>>>11
87
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

#select entire row


>>> print(d3[0,:])
>>> [10 11]
>>> print(d3[1,:])
>>> [12 13]
#select entire column
>>> print(d3[:,0])
>>> [10 12]
>>> print(d3[:,1])
>>> [11 13]
#Method 1: Iterating through multi-dimensional arrays
>>> for row in d3:
print(row)
>>>
[10 11]
[12 13]
#Method 2: Iterating through multi-dimensional arrays
for i in d3.flat:
>>> print(i)

>>> 10
11
12
13

7.Explain basic arithmetic operations on NumPy array with examples.


Basic mathematical functions perform element-wise operation on arrays and are available both as
operator overloads and as functions in the NumPy module.

a= np.array([10,20,30,40])
b=np.arange(1,5)
print("a=",a)
print("b=",b)

#Addition
c1=a+b
print(c1)
>>> [11 22 33 44]

c2=np.add(a,b)
print(c2)
>>> [11 22 33 44]

#Subtraction
d1=a-b

88
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

print(d1)
>>> [ 9 18 27 36]

d2=np.subtract(a,b)
print(d2)
>>> [ 9 18 27 36]

#Multiplication
e1=a*b
print(e1)
>>> [ 10 40 90 160]

e2=np.multiply(a,b)
print(e2)
>>> [ 10 40 90 160]

#Division
f1=a/b
print(f1)
>>> [10. 10. 10. 10.]

f2=np.divide(a,b)
print(f2)
>>> [10. 10. 10. 10.]

#Exponentiation

g1=b**2
print(g1)
>>> [ 1 4 9 16]
#Matrix multiplication
x=np.array([[1,1],[2,2]])
y=np.array([[5,5],[6,6]])
h1=np.dot(x,y)
print(h1)
>>>
[[11 11]
[22 22]]

8.With code examples explain creating pandas series using Scalar data and
Dictionary.

#Create Series from Scalar data

89
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

You can create a Pandas Series from scalar value. If data is a scalar value, an index must be provided.
The value will be repeated to match the length of the index.

import numpy as np
import pandas as pd
series1=pd.Series([12,22,32,42,52], index=['a', 'b', 'c', 'd', 'e'])
print(series1)

OUTPUT

a 12
b 22
c 32
d 42
e 52
dtype: int64

#Create Series from Dictionaries

Series can be created from the dictionary. Create a dictionary and pass it to Series() method. When a
series is created using dictionaries, by default the keys will be index labels. While creating series using a
dictionary, if labels are passed for the index, the values corresponding to the labels in the index will be
pulled out . The order of index labels will be preserved. If a value is not associated for a label, then NaN
is printed. NaN (not a number) is the standard missing data marker used in pandas.

import numpy as np
import pandas as pd
d = {'a' : 0., 'b' : 1., 'c' : 2.}
series2=pd.Series(d)
print(series2)

OUTPUT

a 1
b 2
c 3
d 4
e 5
dtype: int64

9.Explain any four string processing methods supported by Pandas Library with
example.
The Pandas Series supports a set of string processing methods that make it easy to operate on each
element of the array. These methods are accessible via the str attribute and they generally have the same
name as that of the built-in Python string methods.
x=pd.Series(['Java','C','Python','PHP'])

90
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

1) str.lower() : Converts the data to lower case

print(x.str.lower())

OUTPUT
0 java
1 c
2 python
3 php
dtype: object

2) str.upper() : Converts the data to upper case

print(x.str.upper())

OUTPUT

0 JAVA
1 C
2 PYTHON
3 PHP
dtype: object

3) str.len() : Counts the total characters in the data

print(x.str.len())

OUTPUT

0 4
1 1
2 6
3 3
dtype: int64

4) str.count() : Counts the occurrence of a particular character or substring in the data.

print(x.str.count('P'))
0 0
1 0
2 1
3 2
dtype: int64

91
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

10.Explain with example any two methods of creating DataFrame.

1) Create a dataframe from existing excel file.


import pandas as pd
df = pd.read_excel('StudentData.xlsx')
print(df)

OUTPUT

Regno Name Course CGPA


0 101 Akash BCA 9.4
1 102 Irfan BCOM 8.7
2 103 Kishore BCA 6.7

2) Create a dataframe from existing csv file.

import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)

OUTPUT

Regno Name Course CGPA


0 101 Akash BCA 9.4
1 102 Irfan BCOM 8.7
2 103 Kishore BCA 6.7

11.Explain any five operations on Dataframe with example.

import pandas as pd
data={'Reg':[101,102,103],
'Name':['Akash','Irfan','Kishore'],
'Course':['BCA','BCOM','BCA']}

df=pd.DataFrame(data)
print(df)

OUTPUT

Reg Name Course


0 101 Akash BCA
92
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

1 102 Irfan BCOM


2 103 Kishore BCA

1) Selection operation

print(df['Name'])

OUTPUT

0 Akash
1 Irfan
2 Kishore
Name: Name, dtype: object

In the above example, only the rows under Name column is selected and displayed.

2) Addition Operation

df['CGPA']=[9.7,8.6,7.5]
print(df)

OUTPUT

Reg Name Course CGPA


0 101 Akash BCA 9.7
1 102 Irfan BCOM 8.6
2 103 Kishore BCA 7.5

In the above example, a new column CGPA is added to the dataframe.

3) Deletion Operation

df.pop('CGPA')
print(df)

OUTPUT

Reg Name Course


0 101 Akash BCA
1 102 Irfan BCOM
2 103 Kishore BCA
In the above example, column CGPA is deleted from the dataframe.

93
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

4) Renaming a column

df.rename(columns = {'Name':'First Name'})

OUTPUT

Reg First Name Course


0 101 Akash BCA
1 102 Irfan BCOM
2 103 Kishore BCA
In the above example, column Name is renamed to First Name.

5) Insert a column

df.insert(2,'Year',['III','I','II'])
print(df)

OUTPUT

Reg Name Year Course


0 101 Akash III BCA
1 102 Irfan I BCOM
2 103 Kishore II BCA
In the above example, column Year is inserted after the 2nd column in the dataframe.

12.Explain Bar Graph creation using Matplot Library module.

A bar graph represents data in the form of vertical and horizontal lines. It is useful to compare quantities.

Example to create a bar graph with programming languages on the x-axis and students enrolled on y-
axis.

import matplotlib.pyplot as plt


langs = ['C', 'C++', 'Java', 'Python', 'PHP']
students = [23,17,35,79,12]
x=['orange','red','pink','green','black']
plt.bar(langs,students,color=x)
plt.xlabel("Programming Language")
plt.ylabel("Students Enrolled")
plt.title("Course Data")
plt.show()

94
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

plt.bar(langs,students,color=x) is used to create a bar graph.


• The data to be plotted on the x-axis and y-axis are passed as the first and second arguments
respectively.
• color is used to specify the color for the bars.

plt.xlabel("Programming Language")
plt.ylabel("Students Enrolled")
plt.title("Course Data")

• xlabel() and ylabel() displays text along the x and y axes.


• title() gives a heading to the graph.

13.Write a program to display histogram .

import matplotlib.pyplot as plt

marks=[90, 87, 66, 55, 79,50,45,20,98,35]


bins=[0,25,50,75,100]

plt.hist(marks,bins, histtype='bar',rwidth=0.8, color='red')

plt.xlabel("Marks")
plt.ylabel("No. of students")
plt.title("Histogram")

plt.show()

95
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

plt.hist(marks,bins, histtype='bar',rwidth=0.8, color='red') creates a histogram.


• The data to be plotted on the x-axis as the first argument .
• Bins: The towers or bars of a histogram are called bins. The height of each bin shows how many
values from that data fall into that range.
• color is used to specify the color for the bars.
• Histtype:type of histogram to be diaplayed

plt.xlabel("Marks")
plt.ylabel("No. of students")
plt.title("Histogram")

• xlabel() and ylabel() displays text along the x and y axes.


• title() gives a heading to the graph.

14.Write a Python program to display Pie Chart showing percentage of employees in


each department. Assume there are 4 departments namely Sales , Production , HR
and Finance.

import matplotlib.pyplot as plt

slices=[50,20,15,15]

dept = ['Sales', 'Production', 'HR', 'Finance']

colors = ['blue', 'green', 'red', 'orange']

exp=(0, 0.2, 0, 0)

96
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

plt.pie(slices,labels=dept, colors=colors, startangle=90, explode=exp,


shadow=True, autopct='%.1f%%')

plt.title("WIPRO")
plt.legend(loc="upper left")
plt.show()

In the above chart,


plt.pie(slices,labels=dept, colors=colors, startangle=90, explode=exp,
shadow=True, autopct='%.1f%%')
is used to create a pie chart.
• labels: To add labels, pass a list of labels to the labels parameter
• colors: pass a list of colors to set the color of each slice.
• explode :offsetting a slice using explode
• shadow :add a drop-shadow using shadow
• startangle:custom start angle using startangle
• autopct: Pass a function or format string to autopct to label slices.

plt.legend(loc="upper left")

• legen(): Place a legend on the Axes. loc attroibute specifiec the location the where the legend is
to be placed.

97
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

15.Write a Python Program to create Line Graph showing number of students of a


college in various Years. Consider 8 years data.
import matplotlib.pyplot as plt

years = [ '2015', '2016', '2017', '2018', '2019', '2020', '2021','2022']

students = [100, 125, 156, 177, 160, 50, 200, 255]

plt.plot(years, students, "green", marker="o", markerfacecolor="red",


linestyle="dotted")

plt.xlabel("Years")
plt.ylabel("No. of students")
plt.title("College Registration")
plt.show()

plt.plot(years, students, "green", marker="o", markerfacecolor="red",


linestyle="dotted") creates a line graph
• The data to be plotted on the x-axis and y-axis are passed as the first and second arguments
respectively.

98
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE

• The third argument color is used to specify the color of the line.
• marker specifies the type of marker to be displayed on the line
• markerfacecolor specifies the color of the marker
• xlabel() and ylabel() displays text along the x and y axes.
• title() gives a heading to the graph.

99

You might also like