PythonQB Complete BESANT
PythonQB Complete BESANT
BWC, mangalorE
Unit - i
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.
1
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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
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
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)
3
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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.
5
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
6
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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.
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.
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.
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
OUTPUT
0
3
6
9
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.
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
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.
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:
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:
In the above example, since salary of Suhana is not passed, the default value for salary will be used.
Eg:
def show_details(*args):
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
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.
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.
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
• 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.
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:
salary=float(input("Enter salary:"))
OUTPUT:
Enter Name:Rahul
Enter salary:34000
Name=Rahul, phone=7788996655 , salary=34000.0
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
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
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
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
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.
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.
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:
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.
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.
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.
*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):
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:
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:
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
import sys
def main():
print("Arguments:",sys.argv)
print("Total arguments:", {len(sys.argv)})
if __name__ == "__main__":
main()
OUTPUT
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
OUTPUT
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
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
OUTPUT
<class 'str'>
2) x= “python programming”
print(type(x))
OUTPUT
<class 'str'>
print(type(x))
OUTPUT
<class 'str'>
2.List any two built in functions used with python strings. Mention their use.
29
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
OUTPUT:
TypeError: 'str' object does not support item assignment
>>> 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’.
30
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
OUTPUT
OUTPUT
ny
ny e
string_name.split([separator [, maxsplit]])
Eg:
fruits = 'mango,apple,orange,banana'
x=fruits.split(',')
print(x)
OUTPUT
31
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
OUTPUT
Eg:
x=[12,34,'apple',True]
print(type(x))
<class 'list'>
32
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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.
OUTPUT
Syntax:
Example:
>>> fruits = ["apple", "cherry", "orange", "mango", "banana"]
>>>fruits[1:3]
['cherry', 'orange']
>>>fruits[1:4:2]
['cherry', 'orange']
Syntax:
dictionary_name = { key1:value1, key2:value2, ………,keyn:valuen }
Example:
info={'Reg':112, 'Name':'Harish', 'Salary':25000}
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.
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
4) Singleton tuple
fruits = (‘apple’ , )
18. What is the output of print (tuple[1:3]) if tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )?
OUTPUT
(786, 2.23)
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.
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.
The split() method returns a list of string items by breaking up the string using the delimiter string.
Example:
>>> fruits= "apple, orange, mango"
>>> result=fruits.split(',')
>>> result
['apple', ' orange', ' mango']
38
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
>>> result
['apple', ' orange', ' mango']
Example:
>>> date_of_birth = ["17", "09", "1950"]
>>> "-".join(date_of_birth)
'17-09-1950'
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
40
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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']
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.
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:
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
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.
Example:
>>> 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'}
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.
45
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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.
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
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.
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.\
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.
• 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
48
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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
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.
• 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.
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.
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
52
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
Derived class DerivedClassName is inherited from multiple base classes, Base_1, Base_2,Base_3.
53
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
c.pack()
#add canvas to the root window to make it visible
root.mainloop()
Frame is a container is generally used to display widgets like buttons, check buttons or menus.
Syntax:
f = Frame(root, height=200, width=300)
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')
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.
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
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()
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)
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
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:
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
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.
where value can be of integer, float, string types, or another object itself.
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.
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
# 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')
OUTPUT:
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().
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
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.
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:
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.
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.
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()
ob = Student()
print()
ob.display()
OUTPUT:
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.
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
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')
68
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
Example:
A Python program to create a push button and bind it with an event handler function.
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()
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:
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:
• f - Frame
• bg - background color
• fg - foreground color
71
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
UNIT IV
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.
The above code will create a new file with the name ‘mydatabase.db’.
import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
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
import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
con.commit()
con.close()
import sqlite3
con = sqlite3.connect('mydatabase.db')
cursorObj = con.cursor()
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE TITLE='Spider' ")
con.commit()
con.close()
73
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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]]
OUTPUT:
[[1 2 3]
[5 6 7]]
a.ndim: 2
74
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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.
EG:
k=np.arange(0,50,7)
print(k)
OUTPUT:
[ 0 7 14 21 28 35 42 49]
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)
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
76
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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
15. Give the Python code to create dataframe from .csv file
import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)
OUTPUT
77
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)
OUTPUT
OUTPUT
OUTPUT
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
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
Max: 9.4
Max: 6.7
79
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
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()
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()
#create a cursor
cursorObj = con.cursor()
82
Python Programming, ii BCa , 4 SEmth
BWC, mangalorE
#Updating
cursorObj.execute("UPDATE Student SET Course='BBA' WHERE Name='Kelly' ")
#Deleting
cursorObj.execute("Delete from Student where Regno=321 ")
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')
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)
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')
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
y=np.zeros((3,3),dtype=int)
print(y)
Output:
[[0 0 0]
[0 0 0]
[0 0 0]]
y=np.ones((3,3),dtype=int)
print(y)
Output:
[[1 1 1]
[1 1 1]
[1 1 1]]
c=np.full((2,2),7)
print(c)
Output:
[[7 7]
[7 7]]
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
x=np.empty((2,2))
Output:
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
>>> 10
11
12
13
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.
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
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
print(x.str.lower())
OUTPUT
0 java
1 c
2 python
3 php
dtype: object
print(x.str.upper())
OUTPUT
0 JAVA
1 C
2 PYTHON
3 PHP
dtype: object
print(x.str.len())
OUTPUT
0 4
1 1
2 6
3 3
dtype: int64
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
OUTPUT
import pandas as pd
df = pd.read_csv('StudentData.csv')
print(df)
OUTPUT
import pandas as pd
data={'Reg':[101,102,103],
'Name':['Akash','Irfan','Kishore'],
'Course':['BCA','BCOM','BCA']}
df=pd.DataFrame(data)
print(df)
OUTPUT
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
3) Deletion Operation
df.pop('CGPA')
print(df)
OUTPUT
93
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
4) Renaming a column
OUTPUT
5) Insert a column
df.insert(2,'Year',['III','I','II'])
print(df)
OUTPUT
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.
94
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
plt.xlabel("Programming Language")
plt.ylabel("Students Enrolled")
plt.title("Course Data")
plt.xlabel("Marks")
plt.ylabel("No. of students")
plt.title("Histogram")
plt.show()
95
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
plt.xlabel("Marks")
plt.ylabel("No. of students")
plt.title("Histogram")
slices=[50,20,15,15]
exp=(0, 0.2, 0, 0)
96
Python Programming, ii BCa , 4 SEm th
BWC, mangalorE
plt.title("WIPRO")
plt.legend(loc="upper left")
plt.show()
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
plt.xlabel("Years")
plt.ylabel("No. of students")
plt.title("College Registration")
plt.show()
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