Python Solved Question-Bank
Python Solved Question-Bank
PYTHON
PROGRAMMING
SOLVED
QUESTION
BANK
By :
NOUMYA R R
CCG
PYTHON PROGRAMMING
UNIT -1
2Marks
1. How to write a comment line in Python? Mention two types.
Comments in Python are the lines in the code that the compiler ignores during
the execution of the program. Comments enhance the readability of the code
and help the programmers to understand the code very carefully. There are
three types of comments in Python –
• Single line Comments
• Multiline Comments
• Docstring Comments
ccg Page 1
PYTHON PROGRAMMING
6. How to determine the data type of a variable? Give the syntax and
example
To know the datatype of a variable or object, we can use the type() function.
For example, type(a) displays the datatype of the variable ‘a’.
a=15
print(type(a))
<class ‘int’>
Function Description
It converts y to a
str(y)
string.
ccg Page 2
PYTHON PROGRAMMING
if Boolean_Expression_1:
statement_1
elif Boolean_Expression_2:
statement_2
elif Boolean_Expression_3:
statement_3
:
:
:
else:
statement_last
13. What is the purpose of else suit in Python loops? Give example
Python allows the else keyword to be used with the for and while loops too.
The else block appears after the body of the loop. The statements in the else
block will be executed after all iterations are completed. The program exits
the loop only after the else block is executed.
ccg Page 3
PYTHON PROGRAMMING
ccg Page 4
PYTHON PROGRAMMING
Example:
language = 'Python'
Here, language is a variable (an identifier) which holds the value 'Python'.
18. What are the rules for naming variables?
• Variable names can consist of any number of letters, underscores and
digits.
• Variable should not start with a number.
• Python Keywords are not allowed as variable names.
• Variable names are case-sensitive. For example, computer and Computer
are different variables.
Example:
language = 'Python'
Here, language is a variable (an identifier) which holds the value 'Python'.
ccg Page 5
PYTHON PROGRAMMING
ccg Page 6
PYTHON PROGRAMMING
Exceptions come in different types, and the type is printed as part of the
message: the types in the example are ZeroDivisionError ➀
OUTPUT:
Something went wrong
The try...except block is finished
ccg Page 7
PYTHON PROGRAMMING
#O/P: 3 4 5
ccg Page 8
PYTHON PROGRAMMING
OUTPUT:
This parrot wouldn't voom, if you put 1000, volts through it.
ccg Page 9
PYTHON PROGRAMMING
OUTPUT:
Sum: 5
Sum: 10
Sum: 15
Here, we have provided default values 7 and 8 for parameters a and b
respectively
ccg Page 10
PYTHON PROGRAMMING
• Easy to learn: Python uses very few keywords. Its programs use very
simplestructure. So, developing programs in Python become easy. Also,
Python resembles C language. Most of the language constructs in C are
also available in Python. Hence,migrating from C to Python is easy for
programmers.
• Open source: There is no need to pay for Python software. Python can
be freelydownloaded from www.python.org website. Its source code
can be read, modified and can be used in programs as desired by the
programmers.
ccg Page 11
PYTHON PROGRAMMING
ccg Page 12
PYTHON PROGRAMMING
• Numeric Types: In Python, numeric data type represents the data that has a
numeric value. The numeric value can be an integer, floating number, or even
complex number. These values are defined as int, float, and complex classes
in Python.
➢ int datatype – This data type is represented with the help of int class. It
consists of positive or negative whole numbers (without fraction or decimal).
In Python, there is no limit for the size of an int datatype. It can store very
large integer numbers conveniently. Example: a=-57
➢ float datatype: The float datatype represents floating point numbers. A
floating point number is a number that contains a decimal point. Example
nm=56.994456. Floating point numbers can also be written in scientific
notations using ‘e’ or ‘E’ as x=22.55e3. The meaning is x=22.55× 103
➢ complex datatype: A complex number is a number that is written in the form
a + bj or a + bJ. Here a represents the real part and b represents the imaginary
part. The suffix j or J associated with b indicates that the square root value of -
1. Example 3 + 3j, 5.5 + 8.0J.
Example Program -1:
#Python Program to add two complex numbers
c1= 2+ 3J
c2=3-2J
c3=c1+c2
print("Sum = ", c3) # Output: Sum = (5+1j)
• Boolean
Booleans may not seem very useful at first, but they are essential when you
start using conditional statements. In fact, since a condition is really just a yes-
or-no question, the answer to that question is a Boolean value, either True or
False. The Boolean values, True and False are treated as reserved words.
• 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. You can use single quotes or double quotes to represent strings and it
is also called a string literal. Multiline strings can be denoted using triple
quotes, ''' or """. These are fixed values, not variables that you literally provide
in your script.
For example, 1. >>> s = 'This is single quote string'
ccg Page 13
PYTHON PROGRAMMING
ccg Page 14
PYTHON PROGRAMMING
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
SDMCBM Page 15
PYTHON PROGRAMMING
SDMCBM Page 16
PYTHON PROGRAMMING
5. How to read different types of input from the keyboard. Give examples
Python provides input() function to accept input from the user. This function takes a
value from the keyboard and returns it as a string. It is always better to display a
message to the user so that the user can understand what to enter.
Example
str=input("Enter your name ")
print("Hello", str)
If the inputs need to be converted to a datatype other than string then the
corresponding conversion function is to be used. For example int() for integers
float() for floating point datatype and so on. Python accepts a character as string. If
only one character is needed then indexing is to be used.
Example:
ch=input('Enter a character ')
print('You entered', ch[0])
Accepting Integers
Output:
Enter a character Asdf
You entered A
Method-1
#Accepting integers
x=int(input('Enter first number '))
y=int(input('Enter second number ‘))
y=int(input('Enter second number '))
print('X=', x, ‘Y=’, y, ‘Z=’,z)
Method-2
#Accepting three numbers
a, b, c=[int(x) for x in input("Enter three numbers ").split()]
print(a, b, c)
SDMCBM Page 17
PYTHON PROGRAMMING
To accept more than one input in the same line a for loop can be used along with the
input statement as mentioned in the above statement. The split() method by default
splits the values where a space is found. Hence, when entering numbers, the user
should separate them using a blank space. The square brackets [] indicate that
the input accepted will be in the form of elements of a list.
lst=[x for x in input('Enter strings : ').split(',')] #accepts strings separated by comma
print('Your List', lst)
a,b,c=[int(x) for x in input('Enter three numbers ').split(',')]
sum=a+b+c
print('Sum=',sum)
The eval() function
The eval() function takes a string and evaluates the result of the string by taking it as
a Python expression. Example “a+b-5” where a=10, b=15 will be evaluated as 20. If
a string expression is passed to eval() the result of the expression passed will be
returned
Example
#Use of eval() function
a, b= 5, 10
result=eval("a+b-5")
print("Result=", result)# will display 10 as Result
Use str.format() method if you need 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.
SDMCBM Page 18
PYTHON PROGRAMMING
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. An f at the
beginning of the string tells Python to allow any currently valid variable
names within the string.
PYTHON PROGRAMMING
float() function :
The float() function returns a floating point number constructed from a number or
string.
1. int_to_float = float(4)
2. string_to_float = float("1") #number treated as string
3. print(f"After Integer to Float Casting the result is {int_to_float}")
4. print(f"After String to Float Casting the result is {string_to_float}")
Output
After Integer to Float Casting the result is 4.0
After String to Float Casting the result is 1.0
Convert integer and string values to float ➀–➁ and display the result ➂–➃
str() function
The str() function returns a string which is fairly human readable.
1. int_to_string = str(8)
2. float_to_string = str(3.5)
3. print(f"After Integer to String Casting the result is {int_to_string}")
4. print(f"After Float to String Casting the result is {float_to_string}")
Output
After Integer to String Casting the result is 8
After Float to String Casting the result is 3.5
Here, integer and float values are converted ➀–➁ to string using str() function and
results are displayed ➂–➃.
SDMCBM Page 20
PYTHON PROGRAMMING
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.
1. ascii_to_char = chr(100)
2. print(f'Equivalent Character for ASCII value of 100 is {ascii_to_char}')
Output
Equivalent Character for ASCII value of 100 is d
An integer value corresponding to an ASCII code is converted ➀ to the character
and printed ➁.
complex() function
Use complex() function to print a complex number with the value real + imag*j or
convert a string or number to a complex number.
1. complex_with_string = complex("1")
2. complex_with_number = complex(5, 8)
3. print(f"Result after using string in real part {complex_with_string}")
4. print(f"Result after using numbers in real and imaginary part
{complex_with_ number}")
Output
Result after using string in real part (1+0j)
Result after using numbers in real and imaginary part (5+8j)
• The first argument is a string ➀. Hence you are not allowed to specify the
second argument.
• In ➁ the first argument is an integer type, so you can specify the second
argument which is also an integer. Results are printed out in ➂ and ➃.
while loop: The while loop starts with the while keyword and ends with a colon.
With a while statement, the first thing that happens is that the Boolean expression
is evaluated before the statements in the while loop block is executed.
SDMCBM Page 21
PYTHON PROGRAMMING
while Boolean_Expression:
statement(s)
If the Boolean expression evaluates to False, then the statements in the while loop
block are never executed. If the Boolean expression evaluates to True, then the
while loop block is executed. After each iteration of the loop block, the Boolean
expression is again checked, and if it is True, the loop is iterated again.
Each repetition of the loop block is called an iteration of the loop. This process
continues until the Boolean expression evaluates to False and at this point the
while statement exits. Execution then continues with the first statement after the
while loop.
Write Python Program to Display First 10 Numbers Using while Loop Starting
from 0
1. i = 0
2. while i < 10:
3. print(f"Current value of i is {i}")
4. i = i + 1
OUTPUT
Current value of i is 0
Current value of i is 1
Current value of i is 2
SDMCBM Page 22
PYTHON PROGRAMMING
Current value of i is 3
Current value of i is 4
Current value of i is 5
Current value of i is 6
Current value of i is 7
Current value of i is 8
Current value of i is 9
for loop: The for loop starts with for keyword and ends with a colon.
The syntax for the for loop is,
The first item in the sequence gets assigned to the iteration variable
iteration_variable. Here, iteration_variable can be any valid variable name. Then the
statement block is executed. This 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.
We take the liberty of introducing you to range() function which is a built-in
function at this stage as it is useful in demonstrating for loop. The range() function
generates a sequence of numbers which can be iterated through using for loop. The
syntax for range() function is,
range([start ,] stop [, step])
Both start and step arguments are optional and the range argument value should
always be an integer.
SDMCBM Page 23
PYTHON PROGRAMMING
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.
NOTE: The square brackets in the syntax indicate that these arguments are
optional. You can leave them out.
Program 3.16: Write a Program to Find the Sum of All Odd and Even Numbers up
to a Number Specified by the User.
1. number = int(input("Enter a number"))
2. even = 0
3. odd = 0
4. for i in range(number):
5. if i % 2 == 0:
6. even = even + i
7. else: 8. odd = odd + i
9. print(f"Sum of Even numbers are {even} and Odd numbers are {odd}")
Output
Enter a number 10
Sum of Even numbers are 20 and Odd numbers are 25
A range of numbers are generated using range() function ➃. The numbers are
segregated as odd or even by using the modulus operator ➄. All the even numbers
are added up and assigned to even variable and odd numbers are added up and
assigned to odd variable ➅–➇ and print the result ➈.
SDMCBM Page 24
PYTHON PROGRAMMING
Try..except...finally:
divide_by_zero = 7 / 0
try: statement_1
except Exception_Name_1:
statement_2
except Exception_Name_2:
statement_3 . . .
else: statement_4
finally: statement_5
SDMCBM Page 25
PYTHON PROGRAMMING
• Instead of having multiple except blocks with multiple exception names for
different exceptions, you can combine multiple exception names together
separated by a comma (also called parenthesized tuples) in a single except
block.
The syntax for combining multiple exception names in an except block is,
statement(s)
Example
try:
numerator = 10
denominator = 0
result = numerator/denominator
SDMCBM Page 26
PYTHON PROGRAMMING
print(result)
except:
print("Error: Denominator cannot be 0.")
finally:
print("This is finally block.")
OUTPUT:
11. Give the syntax of range function. Explain use range function in for loop
with examples.
A range of numbers are generated using range() function. The range() function
returns a sequence of numbers, starting from 0 by default, and increments by 1 (by
default), and stops before a specified number.
Syntax: range(start, stop, step)
Example: Write a Program to Find the Sum of All Odd and Even Numbers up to
a Number Specified by the User.
1. number = int(input("Enter a number"))
2. even = 0
3. odd = 0
4. for i in range(number):
5. if i % 2 == 0:
6. even = even + i
SDMCBM Page 27
PYTHON PROGRAMMING
OUTPUT
Enter a number 10
Sum of Even numbers are 20 and Odd numbers are 25
A range of numbers are generated using range() function ➃. The numbers are
segregated as odd or even by using the modulus operator ➄. All the even numbers
are added up and assigned to even variable and odd numbers are added up and
assigned to odd variable ➅–➇ and print the result ➈.
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)
In Python, a function definition consists of the def keyword, followed by
1. The name of the function. The function’s name has to adhere to the same
naming rules as variables: use letters, numbers, or an underscore, but the name
cannot start with a number. Also, you cannot use a keyword as a function
name.
2. A list of parameters to the function are enclosed in parentheses and
separated by commas. Some functions do not have any parameters at all while
others may have one or more parameters.
3. 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.
4. 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.
SDMCBM Page 28
PYTHON PROGRAMMING
Defining a function does not execute it. Defining a function simply names the
function and specifies what to do when the function is called. 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)
Arguments are the actual value that is passed into the calling function. There
must be a one to one correspondence between the formal parameters in the
function definition and the actual arguments of the calling function.
When a function is called, the formal parameters are temporarily “bound” to
the arguments and their initial values are assigned through the calling
function.
A function should be defined before it is called and the block of statements in
the function definition are executed only after calling the function.
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.
Here,
SDMCBM Page 29
PYTHON PROGRAMMING
1. When the function is called, the control of the program goes to the function
definition.
3. The control of the program jumps to the next statement after the function call.
Example:
Program to Find the Area of Trapezium Using the Formula Area = (1/2) * (a + b) * h
Where a and b Are the 2 Bases of Trapezium and h Is the Height
1. def area_trapezium(a, b, h):
2. area = 0.5 * (a + b) * h
3. print(f"Area of a Trapezium is {area}")
4. def main():
5. area_trapezium(10, 15, 20)
6. if name == "__main__":
7. main()
OUTPUT
Area of a Trapezium is 250.0
Here the function definition area_trapezium(a, b, h) uses three formal parameters a,
b, h➀ to stand for the actual values passed by the user in the calling function
area_trapezium(10, 15, 20) ➄. The arguments in the calling function are numbers.
The variables a, b and h are assigned with values of 10, 15 and 20 respectively. The
area of a trapezium is calculated using the formula 0.5 * (a + b) * h and the result is
assigned to the variable area ➁ and the same is displayed ➂.
SDMCBM Page 30
PYTHON PROGRAMMING
Example: Using *args to pass the variable length arguments to the function
def adder(*num):
sum = 0
for n in num:
sum = sum + n
print("Sum:",sum)
adder(3,5)
adder(4,5,6,7)
adder(1,2,3,5,6)
OUTPUT:
Sum: 8
Sum: 22
Sum: 17
In the above program, we used *num as a parameter which allows us to pass variable
length argument list to the adder() function. Inside the function, we have a loop
which adds the passed argument and prints the result. We passed 3 different tuples
with variable length as an argument to the function.
**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
Example: Using **kwargs to pass the variable keyword arguments to the
function
def intro(**data):
print("\nData type of argument:",type(data))
for key, value in data.items():
print("{} is {}".format(key,value))
SDMCBM Page 31
PYTHON PROGRAMMING
OUTPUT
Data type of argument: <class 'dict'>
Firstname is Sita
Lastname is Sharma
Age is 22
Phone is 1234567890
PYTHON PROGRAMMING
14. With example explain keyword arguments and default arguments to the
function.
Keyword arguments are a list of arguments of type keyword = value, that
can be accessed with the name of the argument inside curly braces like
{keyword}.
OUTPUT:
This parrot wouldn't voom, if you put 1000, volts through it.
SDMCBM Page 33
PYTHON PROGRAMMING
add_numbers(2, 3)
OUTPUT:
Sum: 5
Sum: 10
Sum: 15
Here, we have provided default values 7 and 8 for parameters a and b
respectively
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. You need to import sys module to access
command
line arguments. All the command line arguments in Python can be printed as a list of
string by executing sys.argv.
PYTHON PROGRAMMING
OUTPUT
C:\Introduction_To_Python_Programming\Chapter_4>python
Program_4.12.py arg_1
arg_2 arg_3
sys.argv prints all the arguments at the command line including file name
['Program_4.12.
p y ', 'a r g _ 1', 'a r g _ 2 ', 'a r g _ 3 ' ]
len(sys.argv) prints the total number of command line arguments including file
name 4
You can use for loop to traverse through sys.argv
Program_4.12.py
arg_1
arg_2
arg_3
To execute a command line argument program, you need to navigate to the directory
where your program is saved. Then issue a command in the format python file_name
argument_1 argu-ment_2argument_3……argument_n. Here argument_1
argument_2 and so on can be any argument and should be separated by a space.
Import sys module ➀ to access command line arguments. Print all the arguments
including file name using sys.argv ➂ but excluding the python command. The
number of arguments passed at the command line can be obtained by len(sys.argv)
➃. A for loop can be used to traverse through each of the arguments in sys.argv ➄–
➆.
SDMCBM Page 35
PYTHON PROGRAMMING
OUTPUT
Please enter a number: g
Oops! That was no valid number. Try again…
Please enter a number: 4
The number you have entered is 4
First, the try block (the statement(s) between the try and except keywords) is
executed ➁ –➄ inside the while loop ➀. If no exception occurs, the except block is
skipped and execution of the try statement is finished. If an exception occurs during
execution of the try block statements, the rest of the statements in the try block is
skipped. Then if its type matches the exception named after the except keyword, the
except block is executed ➅ –➆, and then execution continues after the try statement.
When a variable receives an inappropriate value then it leads to ValueError
exception.
SDMCBM Page 36
PYTHON PROGRAMMING
6. print("Division by zero!")
7. else:
8. print(f"Result is {result}")
9. fi na l ly:
10. print("Executing finally clause")
OUTPUT
Case 1
Enter value for x: 8
Enter value for y: 0
Division by zero!
Executing finally clause
Case 2
Enter value for x: p
Enter value for y: q
Executing finally clause
ValueError Traceback (most recent call last)
<ipython-input-16-271d1f4e02e8> in <module>()
ValueError: invalid literal for int() with base 10: 'p'
In the above example divide by zero exception is handled. In line ➀ and ➁, the user
entered val-ues are assigned to x and y variables. Line ➃ is enclosed within line ➂
which is a try clause. If the statements enclosed within the try clause raise an
exception then the control is transferred to line ➄ and divide by zero error is printed
➅. As can be seen in Case 1, ZeroDivisionError occurs when the second argument
of a division or modulo operation is zero. If no exception occurs, the except block is
skipped and result is printed out ➆–➇. In Case 2, as you can see, the finally clause is
executed in any event ➈– ➉. The ValueError raised by dividing two strings is not
handled by the except clause and therefore re-raised after the finally clause has been
executed.
SDMCBM Page 37
PYTHON PROGRAMMING
18. How to return multiple values from a function definition? Explain with an
example
return statement
The function to perform its specified task to calculate a valueand return the
value to the calling function so that it can be stored in a variable and usedlater.
This can be achieved using the optional return statement in the function
definition.
The syntax for return statement is,
return [expression_list]
SDMCBM Page 38
PYTHON PROGRAMMING
OUTPUT
Which alliance won World War 2? Allies
When did World War 2 end? 1945
The war was won by Allies and the war ended in 1945
Line ➇ is the entry point of the program and you call the function main() ➈. In the
func-tion definition main() you call another function world_war() ➅. The block of
statements in function definition world_war() ➀ includes statements to get input
from the user and a return statement ➁ –➃. The return statement returns multiple
values separated by a comma. Once the execution of function definition is
completed, the values from function definition world_war() are returned to the
calling function. At the calling function on the left-hand side of the assignment ➅
there should be matching number of variables to store the values returned from the
return statement. At ➆ returned values are displayed.
SDMCBM Page 39
PYTHON PROGRAMMING
UNIT II
Two Mark questions
1. Give two methods of creating strings in Python.
Strings are another basic data type available in Python. They consist of one or
more char-acters surrounded by matching quotation marks. To create a string,
put the sequence of characters inside either single quotes, double quotes, or triple
quotes and then assign it to a variable.
Example:
2. List any two built in functions used with python strings. Mention their use.
1. islower()
2. isupper()
1. islower()
string_name.islower()
The method islower() returns Boolean True if all characters in the string are
lowercase, else it returns Boolean False.
2. isupper()
string_name.isupper()
SDMCBM Page 40
PYTHON PROGRAMMING
The method isupper() returns Boolean True if all cased characters in the string
are uppercase and there is at least one cased character, else it returns Boolean
False.
1. >>> word_phrase[-1]
'f'
2. >>> word_phrase[-2]
'l'
By using negative index number of −1, you can print the character ‘f’ ➀, the
negative index number of −2 prints the character ‘l’ ➁.
SDMCBM Page 41
PYTHON PROGRAMMING
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
SDMCBM Page 42
PYTHON PROGRAMMING
Example:
1. >>> inventors = "edison, tesla, marconi, newton"
2. >>> inventors.split(",")
['edison', ' tesla', ' marconi', ' newton']
3. >>> watches = "rolex hublot cartier omega"
4. >>> watches.split()
['rolex', 'hublot', 'cartier', 'omega']
OUTPUT
Individual characters from given string:
characters
Example:
1. >>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]
2. >>> superstore
['metro', 'tesco', 'walmart', 'kmart', 'carrefour']
SDMCBM Page 43
PYTHON PROGRAMMING
OUTPUT:
Final List: [123, 'xyz', 'zara', 2009, 'abc']
SDMCBM Page 44
PYTHON PROGRAMMING
SDMCBM Page 45
PYTHON PROGRAMMING
17. What is the output of print (tuple[1:3]) if tuple = ( 'abcd', 786 , 2.23, 'john',
70.2 )?
It will print elements starting from 2nd till 3rd. Output would be (786, 2.23)
18. Give syntax and purpose of two built-in functions used on tuples
SDMCBM Page 46
PYTHON PROGRAMMING
SDMCBM Page 47
PYTHON PROGRAMMING
Example: Example:
my_tuple = (10, 20, "codes", my_set = {10, 20, "codes",
"cracker") "cracker"}
21. List any two set methods and mention purpose of each method.
SDMCBM Page 48
PYTHON PROGRAMMING
With string slicing, you 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.
Positive index slicing
Example:
1. >>> healthy_drink = "green tea"
2. >>> healthy_drink[0:3]
'g r e'
3. >>> healthy_drink[:5]
'g r e e n'
4. >>> healthy_drink[6:]
'tea'
5. >>> healthy_drink[:]
'green tea'
Negative index slicing
Example:
1. >>> healthy_drink = "green tea"
2. >>> healthy_drink[-3:-1]
'te'
3. >>> healthy_drink[6:-1]
'te'
SDMCBM Page 49
PYTHON PROGRAMMING
2. Write a note on negative indexing and slicing strings using negative indexing.
Negative Indexing
You can also access individual characters in a string using negative indexing. If
you have a long string and want to access end characters in the string, then you
can count backward from the end of the string starting from an index number of
−1.
1. >>> word_phrase[-1]
'f'
2. >>> word_phrase[-2]
'l'
By using negative index number of −1, you can print the character ‘f’ ➀, the
negative index
number of −2 prints the character ‘l’ ➁. You can benefit from using negative
indexing when
you want to access characters at the end of a long string.
Example:
1. >>> healthy_drink = "green tea"
2. >>> healthy_drink[-3:-1]
'te'
3. >>> healthy_drink[6:-1]
'te'
SDMCBM Page 50
PYTHON PROGRAMMING
You 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 ➀. You can also
combine positive and negative indexing numbers ➁.
Example:
1. >>> inventors = "edison, tesla, marconi, newton"
2. >>> inventors.split(",")
['edison', ' tesla', ' marconi', ' newton']
join() string
Strings can be joined with the join() string. The join() method provides a flexible
way to concatenate strings. The syntax of join() method is,
string_name.join(sequence)
Example:
1. >>> date_of_birth = ["17", "09", "1950"]
2. >>> ":".join(date_of_birth)
'17:09:1950'
Here colon is joines with date
4. Explain concatenation , repetition and membership operations on string.
concatenation:strings can also be concatenated using + sign
Example:
1. >>> string_1 = "face"
2. >>> string_2 = "book"
3. >>> concatenated_string = string_1 + string_2
SDMCBM Page 51
PYTHON PROGRAMMING
4. >>> concatenated_string
'facebook'
Two string variables are assigned with "face"➀ and "book" ➁ string values. The
string_1 and string_2 are concatenated using + operator to form a new string. The
new string concatenated_string ➃ has the values of both the strings ➂.
repetition : * operator is used to create a repeated sequence of strings.
Example
5. >>> repetition_of_string = "wow" * 5
6.>>> repetition_of_string
'wowwowwowwowwow'
You can use the multiplication operator * on a string 5. It repeats the string the
number of times you specify and the string value “wow” is repeated five times 6.
member-ship operators(in and not in)
You can check for the presence of a string in another string using in and not in
member-ship operators. It returns either a Boolean Tr u e or False. The in operator
evaluates to Tr u e 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 Tr u e if
the string value in the left operand does not appear in the sequence of characters of
string value in right operand.
Example:
1. >>> fruit_string = "apple is a fruit"
2. >>> fruit_sub_string = "apple"
3. >>> fruit_sub_string in fruit_string
True
4. >>> another_fruit_string = "orange"
5. >>> another_fruit_string not in fruit_string
True
Statement ➂ returns True because the string "apple" is present in the string "apple
is a fruit". The not in operator evaluates to True as the string "orange" is not present
in "apple is a fruit" string ➄.
5. Explain any five string functions with syntax and example.
1. count():
The method count(), returns the number of non-overlapping
occurrences of substring in the range [start, end]. Optional arguments
start and end are interpreted as in slice notation.
SDMCBM Page 52
PYTHON PROGRAMMING
Example:
>>>>>> warriors = "ancient gladiators were vegetarians"
>>> warriors.count("a")
5
2. upper():
The method upper() converts lowercase letters in string to uppercase.
Syntax: string_name.upper()
Example:
>>> "galapagos".upper()
' G A L A PAG O S '
3. lower():
The method lower() converts uppercase letters in string to lowercase.
Syntax: String_name.lower()
Example:
>>> "Tortoises".lower()
'tortoises'
4. capitalize():
The capitalize() method returns a copy of the string with its first
character capitalized and the rest lowercased.
Syntax: string_name.capitalize()
Example:
>>> species = "charles darwin discovered galapagos tortoises"
>>> species.capitalize()
'Charles darwin discovered galapagos tortoises'
5. find():
Checks if substring appears in string_name or if substring appears in
string_name specified by starting index start and ending index end.
Return position of the first character of the first instance of string
SDMCBM Page 53
PYTHON PROGRAMMING
Example:
>>> "cucumber".find("cu")
0
>>> "cucumber".find("um")
3
>>> "cucumber".find("xyz")
-1
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.
Example:
>>> superstore = ["metro", "tesco", "walmart", "kmart", "carrefour"]
>>> superstore[0]
'metro'
>>> superstore[1]
'tesco'
Negative index
SDMCBM Page 54
PYTHON PROGRAMMING
In addition to positive index numbers, you can also access items from the list
with a negative
index number, by counting backwards from the end of the list, starting at −1.
Negative index-
ing is useful if you have a long list and you want to locate an item towards the
end of a list.
>>> superstore[-3]
'walmart'
If you would like to print out the item 'walmart' by using its negative index
number, you
can do so as in ➀
7. Explain any five list methods with syntax.
1. append():
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.
Syntax:
list.append(item)
Example:
>>> cities.append('brussels')
>>> cities
['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo', 'brussels']
2.count():
The count() method counts the number of times the item has occurred in the list and
returns it.
Syntax:
list.count(item)
Example:
>>> cities = ["oslo", "delhi", "washington", "london", "seattle", "paris",
"washington"]
SDMCBM Page 55
PYTHON PROGRAMMING
>>> cities.count('seattle')
1
3. remove():
The remove() method searches for the first instance of the given item in the list and
removes it. If the item is not present in the list then ValueError is thrown by this
method.
Syntax:
list.remove(item)
Example:
>>>cities=['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'brussels',
'copenhagen']
>>> cities.remove("brussels")
>>> c it i e s
['delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'brussels', 'copenhagen']
4. 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.
Syntax:
list.sort()
Example:
>>> cities=['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo',
'brussels']
>>> cities.sort()
>>> c it i e s
['brussels', 'delhi', 'london', 'oslo', 'paris', 'seattle', 'washington', 'washington']
5. 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.
SDMCBM Page 56
PYTHON PROGRAMMING
Syntax:
list.reverse()
Example:
>>> cities = ["oslo", "delhi", "washington", "london", "seattle", "paris",
"washington"]
>>> cities.reverse()
>>> cities
['washington', 'paris', 'seattle', 'london', 'washington', 'delhi', 'oslo']
SDMCBM Page 57
PYTHON PROGRAMMING
19. push_item_to_stack(1)
20. push_item_to_stack(2)
21. push_item_to_stack(3)
22. display_stack_items()
23. push_item_to_stack(4)
24. pop_item_from_stack()
25. display_stack_items()
26. pop_item_from_stack()
27. pop_item_from_stack()
28. pop_item_from_stack()
29. if name == " main ":
30. 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
SDMCBM Page 58
PYTHON PROGRAMMING
OUTPUT:
Queue items are deque(['Eric', 'John', 'Michael'])
Adding few items to Queue
Queue items are deque(['Eric', 'John', 'Michael', 'Terry', 'Graham'])
Removed item from Queue is Eric
Removed item from Queue is John
Queue items are deque(['Michael', 'Terry', 'Graham'])
SDMCBM Page 59
PYTHON PROGRAMMING
You can access an item inside a list that is itself inside another list by chaining
two sets ofsquare brackets together. For example, in the above list variable
asia you have three lists ➀which represent a 3 × 3 matrix. If you want to
display the items of the first list then specifythe list variable followed by the
index of the list which you need to access within the
brackets, like asia[0] ➁. If you want to access "Japan" item inside the list then
you need tospecify the index of the list within the list and followed by the
index of the item in the list, like asia[0][1] ➂. You can evenmodify the
contents of the list within the list. For example,to replace "Thailand" with
"Philippines" use the code in ➃.
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,
SDMCBM Page 60
PYTHON PROGRAMMING
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.
SDMCBM Page 61
PYTHON PROGRAMMING
Example:
>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015,
"harry-potter":2011, "avengers":2012}#original dictionery
.>>>box_office_billion_fromkeys = box_office_billion.fromkeys(box_office_
billion, "billion_dollar")
>>> box_office_billion_fromkeys
{'avatar': 'billion_dollar', 'titanic': 'billion_dollar', 'starwars': 'billion_dollar',
'harry-potter': 'billion_dollar', 'avengers': 'billion_dollar'}
2. Keys(): The keys() method returns a new view consisting of all the keys in the
dictionary.
Syntax: dictionary_name.keys()
Example:
>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015,
"harry-potter":2011, "avengers":2012} #original dictionery
>>> box_office_billion.keys()
dict_keys(['avatar', 'titanic', 'starwars', 'harrypotter', 'avengers'])
3. Values(): The values() method returns a new view consisting of all the values in the
dictionary.
Syntax dictionary_name.values()
Example:
>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015,
"harry-potter":2011, "avengers":2012} #original dictionery
SDMCBM Page 62
PYTHON PROGRAMMING
>>> box_office_billion.values()
dict_values([2009, 1997, 2015, 2011, 2012])
4. Update(): The update() method updates the dictionary with the key:value pairs
from other dictionary object and it returns None.
Syntax: dictionary_name.update([other])
Example:
>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015, "harry-
potter":2011, "avengers":2012} #original dictionery
>>> box_office_billion.update({"frozen":2013})
>>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers':
2012, ' frozen': 2013}
5. Setdefault(): The setdefault() method returns a value for the key present in the
dictionary. If the key is not present, then insert the key into the dictionary with a
default value and return the default value. If key is present, default defaults to None,
so that this method never raises a KeyError.
Syntax: dictionary_name.setdefault(key[, default])
Example:
>>> box_office_billion = {"avatar":2009, "titanic":1997, "starwars":2015,
"harry-potter":2011, "avengers":2012} #original dictionery
>>> box_office_billion.setdefault("minions")
>>> box_office_billion
{'avatar': 2009, 'titanic': 1997, 'starwars': 2015, 'harrypotter': 2011, 'avengers':
2012, ' frozen': 2013, 'minions': None}
SDMCBM Page 63
PYTHON PROGRAMMING
SDMCBM Page 64
PYTHON PROGRAMMING
OUTPUT
Method 1: Building Dictionaries
Enter key microsoft
Enter val windows
Enter key canonical
Enter val ubuntu
Dictionary is {'microsoft': 'windows', 'canonical': 'ubuntu'}
Method 2: Building Dictionaries
Enter key apple
Enter val macos
Enter key canonical
Enter val ubuntu
Dictionary is {'apple': 'macos', 'canonical': 'ubuntu'}
Method 3: Building Dictionaries
Enter key microsoft
Enter val windows
Enter key apple
Enter val macos
Dictionary is {'microsoft': 'windows', 'apple': 'macos'}
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. If you iterate over a dictionary using a for loop, then, by default,
you will iterate over the keys.If you want to iterate over the values, use
values() method and for iterating over the key:value pairs, specify the
dictionary’s items() method explicitly. The dict_keys, dict_values, and
dict_items data types returned by dictionary methods can be used in for loops
to iterate over the keys or values or key:value pairs.
PYTHON PROGRAMMING
OUTPUT
List of Countries
India
USA
Russia
Japan
Germany
List of Currencies in different Countries
Rupee
Dollar
Ruble
Yen
Euro
'India' has a currency of type 'Rupee'
'USA' has a currency of type 'Dollar'
'Russia' has a currency of type 'Ruble'
'Japan' has a currency of type 'Yen'
'Germany' has a currency of type 'Euro'
Using the keys() ➃–➄, values() ➆–➇, and items() ➈–➉ methods, a for loop can
iterate over the keys, values, or key:value pairs in a dictionary, respectively. By
default, a for loop iterates over the keys. So the statement for key in
currency.keys(): results in the same output as for key in currency:. When looping
through dictionaries, the key and its corresponding value can be retrieved
simultaneously using the items() method. The values in the dict_items type returned
SDMCBM Page 66
PYTHON PROGRAMMING
by the items() method are tuples where the first element in the tuple is the key and
the second element is the value. You can use multiple iterating variables in a for
loop to unpack the two parts of each tuple in the items() method by assigning the key
and value to separate variables ➈
you can also access tuple items using a negative index number, by counting
backwards from the end of the tuple, starting at −1. Negative indexing is useful if
you have a large number of items in the tuple and you want to locate an item
towards the end of a tuple.
Example:
>>>holy_places = ("jerusalem", "kashivishwanath", "harmandirsahib", "bethlehem",
"mahabodhi" )
>>> holy_places[0]
'jerusalem'
>>> holy_places[2]
'harmandirsahib'
>>> holy_places[-2]
SDMCBM Page 67
PYTHON PROGRAMMING
'beth lehem'
Slicing of tuples is allowed in Python 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. Syntax:
tuple_name[start:stop[:step]]
where 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,
which includes the start index value but excludes the stop index value. The step
specifies the increment value to slice by and it is optional.
16. Write a Python program to populate tuple with user input data.
1. tuple_items = ()
2. total_items = int(input("Enter the total number of items: "))
3. for i in range(total_items):
4. user_input = int(input("Enter a number: "))
5. tuple_items += (user_input,)
6. print(f"Items added to tuple are {tuple_items}")
7. list_items = []
8. total_items = int(input("Enter the total number of items: "))
9. for i in range(total_items):
10. item = input("Enter an item to add: ")
SDMCBM Page 68
PYTHON PROGRAMMING
11. list_items.append(item)
12. items_of_tuple = tuple(list_items)
13. print(f"Tuple items are {items_of_tuple}")
OUTPUT
Enter the total number of items: 4
Enter a number: 4
Enter a number: 3
Enter a number: 2
Enter a number: 1
Items added to tuple are (4, 3, 2, 1)
Enter the total number of items: 4
Enter an item to add: 1
Enter an item to add: 2
Enter an item to add: 3
Enter an item to add: 4
Tuple items are ('1', '2', '3', '4')
Syntax: set_name.add(item)
Example:
1. >>> european_flowers = {"sunflowers", "roses", "lavender",
"tulips", "goldcrest"}
2. >>> american_flowers = {"roses", "tulips", "lilies", "daisies"}
3. >>> american_flowers.add("orchids")
4. >>> american_flowers.difference(european_flowers)
SDMCBM Page 69
PYTHON PROGRAMMING
Syntax: set_name.issubset(other)
Example:
1>>>european_flowers = {"sunflowers", "roses", "lavender", "tulips"}
2>>> american_flowers.issubset(european_flowers)
False
5. issuperset()
Syntax: set_name.issuperset(other)
Example:
1>>>european_flowers = {"sunflowers", "roses", "lavender", "tulips"}
2>>> american_flowers.issuperset(european_flowers)
False
SDMCBM Page 70
PYTHON PROGRAMMING
UNIT III
2Marks
1. List file types supported by Python. Give example for each?
SDMCBM Page 71
PYTHON PROGRAMMING
Example:
• The words with and as are keywords and the with keyword is followed by
the open() function and ends with a colon.
• The as keyword acts like an alias and is used to assign the returning object
from the open() function to a new variable file_handler.
• The with statement creates a context manager and it will automatically
close the file handler object for you when you are done with it.
SDMCBM Page 72
PYTHON PROGRAMMING
4. List any two file object attributes and mention its purpose.
tell () :
• This method returns an integer giving the file handler’s current position
within the file, measured in bytes from the beginning of the file.
Syntax: file_handler.tell ()
seek ():
• This method is used to change the file handler’s position. The position is
computed from adding offset to a reference point.
• The reference point is selected by the from_what argument.
• A from_what value of 0 measures from the beginning of the file, 1 uses
the current file position, and 2 uses the end of the file as the reference
point.
• If the from_what argument is omitted, then a default value of 0 is used,
indicating that the beginning of the file itself is the reference point.
Syntax: file_handler.seek(offset, from_what)
SDMCBM Page 73
PYTHON PROGRAMMING
7. What is self-variable ?
The self variable is used to represent the instance of the class which is often
used in object-oriented programming. It works as a reference to the object.
When an instance to the class is created, the instance name contains the
memory location of the instance. This memory location is
internally passed to 'self'.
Example:
def _ _init_ _(self, parameter_1, parameter_2, …., parameter_n):
statement(s)
SDMCBM Page 74
PYTHON PROGRAMMING
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.
class ClassA:
# Super class code here
class ClassB(ClassA):
# Derived class B code here
class ClassC(ClassA):
# Derived class C code here
SDMCBM Page 75
PYTHON PROGRAMMING
SDMCBM Page 76
PYTHON PROGRAMMING
.
.
.
<statement-N>
SDMCBM Page 77
PYTHON PROGRAMMING
Canvas Frames
This is a container that is generally This is a container that is generally
used to draw shapes like lines, curves, used to display widgets like buttons,
arcs and circles. check buttons or menus.
C = Canvas (root, bg="blue", frame= Frame (root, height=n,
height=500, width=600, width=m, bg="color",
cursor='pencil') cursor="cursortype")
• c is the Canvas class object, root is • f is the object of Frame class.
the name of the parent window. The frame is created as a child
• bg represents background color, of root' window.
• height and width represent the • The options 'height' and width'
height and width of the canvas in represent the height and width
pixels. of the frame in pixels.
• The option 'cursor' represents the • Bg represents the back ground
shape of the cursor in the canvas. color to be displayed .
• 'cursor' indicates the type of the
cursor to be displayed in the
frame.
SDMCBM Page 78
PYTHON PROGRAMMING
After creating the scroll bar, it should be attached to the widget like Text
widget or Listbox as:
t.configure (xscrollcommand=h.set)
Here, t'indicates Text widget. xscrollcommand calls the set() method of
horizontal scroll bar.
In the same way, we can attach vertical scroll bar as:
t.configure(yscrollcommand=v.set)
18. Differentiate Label and Text Widget.
Label Text
A label represents constant text that is Text widget is same as a label or
displayed in the frame or container. A message. But Text widget has several
label can display one or more lines of options and can
text that cannot be modified. display multiple lines of text in
different colors and fonts. It is
possible to insert text into atext
widget, modify it or delete it. We can
also display images in the Text
widget.
A label is created as an object of create a Text widget by creating an
Label class as: object to Text class as:
SDMCBM Page 79
PYTHON PROGRAMMING
SDMCBM Page 80
PYTHON PROGRAMMING
21. List the values that can be assigned to selectmode property of listbox
• BROWSE
• SINGLE
• MULTIPLE
• EXTENDED
Long Answer
1. List and explain various file opening modes with examples.
1. “r” - Opens the file in read only mode and this is the default mode
2. “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.
3. “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.
SDMCBM Page 81
PYTHON PROGRAMMING
2. With program example explain how ‘with’ statement is used to open and
close files
we can use a with statement in Python such that you 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
SDMCBM Page 82
PYTHON PROGRAMMING
the words with and as are keywords and the with keyword is followed by the open()
function and ends with a colon. The as keyword acts like an alias and is used to
assign the returning object from the open() function to a new variable file_handler.
The with statement creates a context manager and it will automatically close the file
handler object.
In the below example, The with statement automatically closes the file after
executing its block ofstatements ➂. You can read the contents of the file japan.txt
line-by-line using a for loop without running out of memory ➃. This is both
efficient and fast.
EXAMPLE:
1. def read_file():
2. print("Printing each line in text file")
3. with open("japan.txt") as file_handler:
4. for each_line in file_handler:
5. print(each_line, end="")
6. def main():
7. r e a d _ fi l e ( )
8. if name == " main ":
9. ma i n()
OUTPUT:
Printing each line in text file
National Treasures of Japan are the most precious of Japan's Tangible Cultural
Properties.A Tangible Cultural Property is considered to be of historic or artistic
value, classified either as"buildings and structures", or as "fine arts and crafts".
SDMCBM Page 83
PYTHON PROGRAMMING
3. With code example explain any two methods to read data from the file.
read():
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.
Syntax: file_handler.read([size])
Example:
1. def main():
2. with open("rome.txt") as file_handler:
3. print("Print entire file contents")
4. print(file_handler.read(), end=" ")
5. if name == " main ":
6. main()
OUTPUT
Print entire file contents
Ancient Rome was a civilization which began on the Italian Peninsula in the 8th
century BC.
The Roman Emperors were monarchial rulers of the Roman State.
The Emperor was supreme ruler of Rome.
Rome remained a republic.
readlines():
This method is used to read all the lines of a file as list items.
Syntax: file_handler.readlines()
Example:
1. def main():
2. with open("rome.txt") as file_handler:
3. print("Print file contents as a list")
SDMCBM Page 84
PYTHON PROGRAMMING
4. print(file_handler.readlines())
5. if name == " main ":
6. main()
OUTPUT
['Ancient Rome was a civilization which began on the Italian Peninsula in the 8th
century
BC.\n', 'The Roman Emperors were monarchial rulers of the Roman State.\n', 'The
Emperor
was supreme ruler of Rome.\n', 'Rome remained a republic.']
4. With Code example explain any two methods to write data to the file.
write() : 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.
Syntax: file_handler.write(string)
Example:
f = open("demofile2.txt", "a")
f.write("See you soon!")
f.close()
#open and read the file after the appending:
f = open("demofile2.txt", "r")
print(f.read())
OUTPUT:
See you soon!
PYTHON PROGRAMMING
OUTPUT:
See you soon!Over and out
5. Write Python Program to Count the Occurrences of Each Word and Also
Count the Number of Words in a text File.
Data.tat(text file)
Am python easy but not lazy
Am very particular in indentation
Source Code:
file = open("data.txt", "rt")
c = dict()
data = file.read()
words = data.split()
for t in words:
if t in c:
c[t] += 1
else:
c[t] = 1
print('Number of words in text file :', len(words))
print('Occurrences of Each Word :',c)
SDMCBM Page 86
PYTHON PROGRAMMING
OUTPUT
Number of words in text file : 11
Occurrences of Each Word : {'Am': 2, 'python': 1, 'easy': 1, 'but': 1, 'not': 1, 'lazy': 1,
'very': 1, 'particular': 1, 'in': 1, 'indentation': 1}
class ClassName:
<statement-1>
.
.
<statement-N>
• Classes are defined by using the class keyword, followed by the Class Name
and a colon. Class definitions must be executed before they have any effect.
Methods are a special kind of function that is defined within a class.
SDMCBM Page 87
PYTHON PROGRAMMING
Example:
Output
This message is from Constructor Method
Receive message using Mobile
Send message using Mobile
SDMCBM Page 88
PYTHON PROGRAMMING
• The terms parent class and child class are also acceptable terms to use
respectively.
• A derived class inherits variables and methods from its base class while
adding additional variables and methods of its own. Inheritance easily enables
reusing of existing code.
The syntax for a derived class definition looks like this:
class DerivedClassName(BaseClassName):
<statement-1>
.
.
<statement-N>
• To create a derived class, you add a BaseClassName after the
DerivedClassName within the parenthesis followed by a colon. The derived
class is said to directly inherit from the listed base class.
• Example:
classParent():
deffirst(self):
print('first function')
classChild(Parent):
defsecond(self):
print('second function')
ob =Child()
ob.first()
ob.second()
Output:
first function
second function
# In the above program, you can access the parent class function using the child
class object.
PYTHON PROGRAMMING
you must explicitly call the base class init () method using super()
yourself, since that will not happen automatically.
• The syntax for using super() in derived class init () method definition
looks like this:
• Example: #Accessing base class constructor and method in the sub class
class Square:
def init (self, x): #constructor of Base Class
self.x = x
def area(self):
print('Area of square=', self.x*self.x)
class Rectangle(Square):
def init (self, x, y): #constructor of derived Class
super(). init (x) #super class constructor
self.y = y
def area(self):
super().area() #super class method
print('Area of rectangle=', self.x*self.y)
#find areas of square and rectangle
a,b = [float(x) for x in input("Enter two measurements: ").split()]
r = Rectangle(a,b)
r.area()
#Output
Enter two measurements:
22
Area of square= 4.0
Area of rectangle= 4.0
SDMCBM Page 90
PYTHON PROGRAMMING
class SuperClass:
def super_method(self):
print("Super Class method called")
PYTHON PROGRAMMING
BaseClassName.methodname(self, arguments)
issubclass(DerivedClassName, BaseClassName)
SDMCBM Page 92
PYTHON PROGRAMMING
OUTPUT:
True #Derived class is subclass of Baseclass2
False # Baseclass1 & Baseclass2 both are base class.
SDMCBM Page 93
PYTHON PROGRAMMING
class ClassB(ClassA):
# Derived class B code here
class ClassC(ClassA):
# Derived class C code here
Example:
#Program to demonstrate Multipath Inheritance
class University:
def init (self):
print("Constructor of the Base class")
def display(self):
print(f"The University Class display method")
SDMCBM Page 94
PYTHON PROGRAMMING
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()
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()
# Object Instantiation:
ob = Student() # Object named ob of the class Student.
print()
ob.display() # Calling the display method of Student class.
SDMCBM Page 95
PYTHON PROGRAMMING
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
SDMCBM Page 96
PYTHON PROGRAMMING
• Here the sum () method is calculating sum of two or three numbers and hence
it is performing more than one task. Hence it is an overloaded method.
• In this way, overloaded methods achieve polymorphism. When there is a
method in the super class, writing the same method in the sub class so that it
replaces the super class method is called 'method overriding'. The programmer
overrides the super class methods when he does not want to use them in sub
class. Instead, he wants a new functionality to the same method in the sub
class.
A Python program to override the super class method in sub class.
#method overriding
import math
class Square:
def area(self, x):
print('Square area= %.4f'% x*x)
class Circle(Square):
def area(self, x):
print('Circle area= %.4f'% (math.pi*x*x))
c = Circle()
c.area(15)
SDMCBM Page 97
PYTHON PROGRAMMING
13. Explain the steps involved in creating a GUI application in Python with a
suitable example.
The following are the general steps involved in basic GUI programs:
1. First of all, we should 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, we have to allocate space for our use. This is done by
creating a canvas or frame: So, canvas and frame are child windows in the root
window.
3Generally, 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.
Example:
from tkinter import *
window=Tk()
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:
• Here, „b‟ is the object of Button class. ‟ f'‟ represents the frame for which the
button is created as a child. It means the button is shown in the frame.
• The 'text' option represents the text to be displayed on the button.
SDMCBM Page 98
PYTHON PROGRAMMING
Program 9: A Python program to create a push button and bind it with an event
handler function.
from tkinter import *
# method to be called when the button is clicked
def buttonclick(self):
print ('You have clicked me)
# create root window
root = TkO
# create frame as child to root window
f= Frame (root, height-200, width=300)
# let the frame wil1 not shrink
f-propagate (0)
# attach the frame to root w1ndow
SDMCBM Page 99
PYTHON PROGRAMMING
f. pack()
# create a push button as child to frame
b= Button(f, text='My Button', width=15, height=2, bg='yellow' fg= ‘blue’,
activebackground= ‘green’, activeforeground=’red')
OUTPUT:
PYTHON PROGRAMMING
PYTHON PROGRAMMING
• The pack() method can take another option ‘side’ which is used to place the
widgets side by side. „side‟ can take the values LEFT, RIGHT, TOP or
BOTTOM. The default value is TOP.
For example,
# align towards left with 10 px and 15 px spaces
b1.pack(side=LEFT, padx=10, pady=15)
# align towards bottom with 10 px and 15 px spaces
b2.pack(side=BOTTOM, padx=10, pady=15)
# align towards right with 0 px space around the widget
b3.pack(side=RIGHT)
# align towards top with 0 px space around the widget
b4.pack()
PYTHON PROGRAMMING
Example
# display in 0th row, 0th column with spaces around
bl.grid(row=0, column=0, padx=10, pady=15)
# display in Oth row, 1st column with spaces around
b2.grid(row=0, column=1, padx=10, pady=15
# display in Oth row, 2nd column without spaces around
b3.grid(row=0, column=2)
# display in 1st row, 3rd column without spaces around
b4.grid(row=1, column=3)
PYTHON PROGRAMMING
OUTPUT:
For example:
# display at (20, 30) coordinates in the window 100 pxwidth and 50
pxheight
bl.place(x=20, y=30, width=100, height=50)
b2.place(x=20, y=100, width=100, height=50) # display at (20, 100)
b3.place(x=200, y=100, width=100,height=50)# display at (200, 100)
b4.place(x=200, y=200, width=100, height=50) # display at (200, 100)
OUTPUT:
PYTHON PROGRAMMING
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:
• 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.
Text Widget
• 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:
PYTHON PROGRAMMING
PYTHON PROGRAMMING
self.t.pack(side=LEFT)
OUTPUT:
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:
el=Entry(f, width=m, fg='color', bg='color', font=('fontname'. 14),show=‟*‟)
• When the user presses Enter (or Return) button, the event is passed to
display() method, Hence, we are supposed to catch the event in the display
method, using the following statement:
def display (self, event):
PYTHON PROGRAMMING
• As seen in the preceding code, we are catching the event through an argument
'event' in the display() method. This argument is never used inside the method.
The method consists of the code that is to be executed when the user pressed
Enter button.
OUTPUT
PYTHON PROGRAMMING
Unit4
2Marks
1. How to connect to the SQLite database ? Give example
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')
#This will create a new file with the name ‘mydatabase.db’.
PYTHON PROGRAMMING
con.close()
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
• Create a series using ndarray which is NumPy’s array class using Series()
method ➂ which returns a Pandas Series type s ➃.
• You can also specify axis labels for index, i.e., index= ['a', 'b', 'c', 'd', 'e'] ➂ .
• When data is a ndarray, the index must be the same length as data. In series s
➄ , by default the type of values of all the elements is dtype: float64.
12. Write Python code to create Dataframe from a dictionary and display its
contents.
13. Write Python code to create Dataframe from a tuple and display its
contents.
# Importing pandas package
import pandas as pd
# Creating two list of tuples
data = [
('Ram', 'APPLE', 23),
('Shyam', 'GOOGLE', 25),
('Seeta', 'GOOGLE', 22),
('Geeta', 'MICROSOFT', 24),
('Raman', 'GOOGLE', 23),
PYTHON PROGRAMMING
OUTPUT
PYTHON PROGRAMMING
15. Give the Python code to create dataframe from .csv file
You can read from CSV and Excel files using read_csv() and read_excel() methods.
Also, you can write to CSV and Excel files using to_csv() and to_excel() methods.
Example:
PYTHON PROGRAMMING
17. Give the Python code to create datafram from Excel file.
You can read from CSV and Excel files using read_csv() and read_excel() methods.
Also, you can write to CSV and Excel files using to_csv() and to_excel() methods.
18. Give Python code to find maximum and minimum values for particular
column of dataframe.
• min() Compute minimum of group values
• max() Compute maximum of group values
1>>>import pandas as pd # Import pandas library
# Create pandas DataFrame
2>>>data = pd.DataFrame({'x1':[5, 2, 4, 2, 2, 3, 9, 1, 7, 5], 'x2':range(10, 20),
'group':['A', 'A', 'B', 'B', 'C', 'A', 'C', 'C', 'A', 'B']})
3>>>print(data) # Print pandas DataFrame
4>>>print(data['x1'].max()) # Get max of one column
PYTHON PROGRAMMING
#9
5>>>print(data['x1'].min()) # Get min of one column
#1
LONG Answer
1. Explain four SQLite module methods required to use SQLite database.
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
#crete a cursor
cursorObj = con.cursor()
#Updating
cursorObj.execute("UPDATE MOVIE SET SCORE=10 WHERE
TITLE='Dil' ")
PYTHON PROGRAMMING
PYTHON PROGRAMMING
import numpy as np
array_attributes = np.array([[10, 20, 30], [14, 12, 16]])
array_attributes.itemsize
O/P: 4
6. ndarray.data : Gives the buffer containing the actual elements of the array.
Normally, we will not use this attribute because we will access the elements in an
array using indexing facilities.
Syntax : ndarray.data
Example:
import numpy as np
array_attributes = np.array([[10, 20, 30], [14, 12, 16]])
array_attributes.data
O/P: <memory at 0x000001E61DB963A8>
PYTHON PROGRAMMING
PYTHON PROGRAMMING
4. >>> a[2]
2
5. >>> a[2:4]
array([2, 3])
6. >>> a[:4:2] = -999
7. >>> a
array([-999, 1, -999, 3, 4])
8. >>> a[::-1]
array([ 4, 3, -999, 1, -999])
9. >>> for each_element in a:
10.print(each_element)
-999
1
-999
3
4
Indexing, slicing, and iterating operations on one-dimensional NumPy arrays
➀–➉.
PYTHON PROGRAMMING
5. >>> a + b
array([20, 31, 42, 53])
6. >>> np.add(a, b)
array([20, 31, 42, 53])
7. >>> a – b
array([20, 29, 38, 47])
8. >>> np.subtract(a, b)
array([20, 29, 38, 47])
13. >>> A / B
array([[0.5 , 0.125],
[2. , 0.25 ]])
14. >>> np.divide(A, B)
array([[0.5 , 0.125],
[2. , 0.25 ]])
15. >>> np.dot(A, B)
SDMCBM Page 128
PYTHON PROGRAMMING
array([[ 5, 12],
[15, 52]])
16. >>> B**2
array([[ 4, 64],
[ 9, 16]], dtype=int32)
Element-wise sum, subtract, multiply, and divide operations are performed resulting
in an array 5 –14. Matrix product is carried out in 15. Every element is squared in
array B as shown in 16.
8. With code examples explain creating pandas series using Scalar data and
Dictionary. (Refer Q.No:10)
PYTHON PROGRAMMING
PYTHON PROGRAMMING
0 0
1 1
2 1
3 1
dtype: int64
You can create a Pandas Series from scalar value. Here scalar value is five ➂. If data
is a scalar value, an index must be provided. The value will be repeated to match the
length of the index.
PYTHON PROGRAMMING
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 ➄.
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
PYTHON PROGRAMMING
# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 20, 15, 25]
# Create a bar graph
plt.bar(categories, values)
# Add labels and title
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Graph')
# Display the graph
plt.show()
PYTHON PROGRAMMING
PYTHON PROGRAMMING
histogram using the `plt.hist()` function. We pass the`data` as the first argument to
the function.
To enhance the histogram, we add labels and a title using the
`plt.xlabel()`,`plt.ylabel()`, and `plt.title()` functions, respectively. These labels
provideinformation about the x-axis, y-axis, and the title of the histogram.Finally,
we display the histogram using `plt.show()`.
Running this code will generate a histogram with bins representing therange of
values and the frequency of occurrence for each bin. The x-axisrepresents the values,
and the y-axis represents the frequency or count of valuesfalling within each bin.
OUTPUT:
PYTHON PROGRAMMING
```
In this example, we start by importing the `matplotlib.pyplot` module as`plt`. We
define the sample data that we want to visualize. The `departments` listcontains the
department names, and the `employee_counts` list contains thecorresponding
number of employees in each department.Next, we create a pie chart using the
`plt.pie()` function. We pass the`employee_counts` as the first argument and the
`departments` as the `labels`parameter to the function. The `autopct='%1.1f%%'`
parameter is used to displaythe percentage values on each slice of the pie chart.To
enhance the pie chart, we add a title using the`plt.title()` function.Finally, we display
the pie chart using `plt.show()`.
Running this code will generate a pie chart where each department isrepresented by
a slice. The size of each slice represents the percentage ofemployees in that
department. The legend labels indicate the department names,and the percentage
values are displayed on each slice.
You can further customize the appearance of the pie chart by adjustingparameters
such as colors, explode (to highlight a particular slice), shadow, and more using
additional arguments in the `plt.pie()` function. Matplotlib provides various options
to create visually appealing and informative pie charts.
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
# Sample data
years = [2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022]
SDMCBM Page 139
PYTHON PROGRAMMING
OUTPUT:
PYTHON PROGRAMMING
list contains the respective number of students in each year. Next, we create a line
graph using the `plt.plot()` function.
We pass the `years` as the first argument and `student_counts` as the second
argument to the function. The `marker='o'` parameter is used to display circular
markers at each data point.To enhance the line graph, we add labels and a title using
the `plt.xlabel()`, `plt.ylabel()`, and `plt.title()` functions, respectively.
Finally, we display the line graph using `plt.show()`. Running this code will
generate a line graph where the x-axis represents the years, and the y-axis represents
the number of students in the college. Each data point is connected by a line, and
circular markers are displayed at each data point. You can further customize the
appearance of the line graph by adjusting parameters such as line color, line style,
marker type, and more using additional arguments in the `plt.plot()` function.
Matplotlib offers various options to create visually appealing and informative line
graphs.