Python Notes
Python Notes
UNIT – I
Part – A (Each question carries Two marks)
Part - B
(Each question carries Three marks)
Part – C
(Each question carries Five marks)
Q.1) What is Python? What are the benefits of using Python?
Ans : Python is a General purpose programming language that can be used effectively to build
almost any kind of program that does not need direct access to the computer’s hardware.
Python is not optimal for programs that have high reliability constraints or that are built and
maintained by many people or over a long period of time.
Benefits of using python :
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some
other programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as
it is written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-orientated way or a functional
way.
Advantages Python
The Python language has diversified application in the software development companies such
as in gaming, web frameworks and applications, language development, prototyping,
Extensive Support Libraries
Integration Feature
Improved Programmer’s Productivity
Productivity
Q.2) How will you execute python program (script) on windows platform?
Ans : To add the Python directory to the path for a particular session in Windows −
At the command prompt − type path %path%;C:\Python and press Enter.
Note − C:\Python is the path of the Python directory
Script from the Command-line
A Python script can be executed at command line by invoking the interpreter on your
application, as in the following –
C: >python script.py # Windows/DOS
A list can be defined as a collection of values or items of different types. The items in the list
are separated with the comma (,) and enclosed with the square brackets [].
Example : Create a List:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Q.12) Explain break and continue with example.
Ans : The break is a keyword in python which is used to bring the program control out of
the loop. The break statement breaks the loops one by one, i.e., in the case of nested loops,
it breaks the inner loop first and then proceeds to outer loops. In other words, we can say
that break is used to abort the current execution of the program and the control goes to the
next line after the loop.
Example :
list =[1,2,3,4]
count = 1;
for i in list:
if i == 4:
print("item matched")
count = count + 1;
break
print("found at",count,"location");
Continue :
The continue statement in python is used to bring the program control to the beginning of
the loop. The continue statement skips the remaining lines of code inside the loop and start
with the next iteration. It is mainly used for a particular condition inside the loop so that we
can skip some specific code for a particular condition.
Example :
i = 0;
while i!=10:
print("%d"%i);
continue;
i=i+1;
Q.13) What is set? Explain with methods.
Ans : The set in python can be defined as the unordered collection of various items enclosed
within the curly braces. The elements of the set can not be duplicate. The elements of the
python set must be immutable.
Python also provides the set method which can be used to create the set by the passed
sequence.
using set() method
Days = set(["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Su
nday"])
print(Days)
print(type(Days))
print("looping through the set elements ... ")
for i in Days:
print(i)
UNIT – II
Part - A (Each question carries Two marks)
Q.1) Define Errors and Exceptions in Python programs?
Ans : An exception can be defined as an abnormal condition in a program resulting in the
disruption in the flow of the program.
When writing a program, we, more often than not, will encounter errors.
Q.2) What is mean by default values in function? Explain
Ans : Function arguments can have default values in Python.
We can provide a default value to an argument by using the assignment operator (=).
Q.3) What is the purpose of module in python?
Ans : We use modules to break down large programs into small manageable and organized
files. Furthermore, modules provide reusability of code.
Q.4) How will you make available the stored procedure of module xyz into your
program?
Ans : Open MySQL console and run below query to create a MySQL Stored Procedure.
Q.5) How will you call the methods of given module without specifying dot-suffix their
name?
Ans :
that works in the same way as the arithmetic that people learn at school.” – excerpt from
the decimal arithmetic specification.
Q.11) What is the purpose of ‘re’ module?
Ans : A regular expression (or RE) specifies a set of strings that matches it; the functions in
this module let you check if a particular string matches a given regular expression
Q.12) How will you see the keyword list in python >>> prompt?
Ans : list of keywords in your current version by typing the following in the prompt.
>>> import keyword
>>> print(keyword.kwlist)
UNIT – II
Part - B (Each question carries Three marks)
Q.1) Write syntax for creating custom function in python.
Ans : Creating a function
In python, we can use def keyword to define the function. The syntax to define a function in
python is given below.
def my_function():
function-suite
return <expression>
Q.2) How will you specify a default value for an argument in the function definition?
Ans :
def printme(name,age=22):
print("My name is",name,"and age is",age)
printme(name = "john")
#the variable age is not passed into the function however the default value of age is conside
r
Q.3) How will you override default values in custom function?
Ans :
UNIT – II
Part – C (Each question carries Five marks)
Q.1) How will you create custom function in python? Explain with example
Ans : These are the basic steps in writing user-defined functions in Python. For additional
functionalities, we need to incorporate more steps as needed.
• Step 1: Declare the function with the keyword def followed by the function name.
• Step 2: Write the arguments inside the opening and closing parentheses of the
function, and end the declaration with a colon.
• Step 3: Add the program statements to be executed.
• Step 4: End the function with/without return statement.
The example below is a typical syntax for defining functions:
def userDefFunction (arg1, arg2, arg3 ...):
program statement1
program statement3
program statement3
....
return;
Q.2) Write a program that will return factorial of given number.
Ans :
num = 7
factorial = 1
if num < 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
Q. 3) Write a custom function to input any 3 numbers and find out the largest on
Ans : num1 = 10
num2 = 14
num3 = 12
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
Q.4) Write a custom function to calculate x raise to power y.
Ans : def power(x, y):
if (y == 0): return 1
elif (int(y % 2) == 0):
return (power(x, int(y / 2)) *
power(x, int(y / 2)))
else:
return (x * power(x, int(y / 2)) *
power(x, int(y / 2)))
# Driver Code
x = 2; y = 3
print(power(x, y))
pg. 11 Modern College, Wadi, Nagpur
Python Notes
fib = incrementer( )
for i in fib :
if >100:
break
else :
print(‘Generated :’,1)
Q.7) How will you invoke inbuilt exception explicitly? Explain with example
Ans :
Mathematical Functions :
Function Description
pow(x, y) Returns x raised to the power y
sqrt(x) Returns the square root of x
acos(x) Returns the arc cosine of x
asin(x) Returns the arc sine of x
Q.10) How will you generate random numbers? Explain with example
Ans : Check out the code snippet below to see how it works to generate a number
between 1 and 100.
import random
for x in range(10):
print random.randint(1,101)
The code above will print 10 random values of numbers between 1 and 100. The
second line, for x in range(10), determines how many values will be printed (when
you use range(x), the number that you use in place of x will be the amount of values
that you'll have printed. if you want 20 values, use range(20). use range(5) if you
only want 5 values returned, etc.). Then the third line: print random.randint(1,101)
will automatically select a random integer between 1 and 100 for you. The process
is fairly simple.
What if, however, you wanted to select a random integer that was between 1 and
100 but also a multiple of five? This is a little more complicated. The process is the
same, but you'll need to use a little more arithmetic to make sure that the rand om
integer is in fact a multiple of five. Check out the code below:
Q.11) List the date time directives with meaning.
Ans :
Directive Description Example
%H Hour 00-23 17
%I Hour 00-12 05
%p AM/PM PM
%M Minute 00-59 41
%S Second 00-59 08
%Z Timezone CST
%% A % character %
def isPhoneNumber(text):
if len(text) != 12:
return False
for i in range(0, 3):
if not text[i].isdecimal():
return False
if text[3] != '-':
return False
for i in range(4, 7):
if not text[i].isdecimal():
return False
if text[7] != '-':
return False
for i in range(8, 12):
if not text[i].isdecimal():
return False
return True
UNIT – III
Part – A (Each question carries Two marks)
Q.1) What is an acronym for ASCII?
Ans : ASCII is the acronym for the American Standard Code for Information Interchange.
It is a code for representing 128 English characters as numbers, with each letter assigned a
number from 0 to 127. For example, the ASCII code for uppercase M is 77.
Q.2) What is class?
Ans : A ‘Class’ is a specified prototype describing a set of properties that characterize an object.
Each class has a data structure that can contain both functions and variables to characterize
the object.
Q.3) What is mean by class attribute?
Ans : The properties of a class are referred to as its data “members” class function member are
known as its “methods” and class variable members are known as its “Attributes”
Q.4) How can class members be referenced?
Ans : Class members ca be referenced throughout a program using dot notation, suffixing the
member name after the class name with syntax of class-name.method-name().
Q.5) Define encapsulation.
Ans : This technique of data “encapsulation” ensures that data is securely stored within the
class structure and is the first principle of OOP.
Q.6) What is polymorphism?
Ans : The term “Polymorphism” (from Greek, meaning “Many Forms”) describes the ability to
assign a different meaning, or purpose, to an entire according to its context.
Q.7) What is inheritance?
Ans : Inheritance stands for derivation. The mechanism of deriving a new class from an old
class is called inheritance. The old class is known as base class and new class is known as
derived class.
Q.8) How will you declare a class in python?
Ans : class Polygon :
width = 0
height = 0
def set_values(self, width, height):
polygon.width =width
polygon.height = height
Q.9) What is instance variable in python?
Ans : At the class level, variables are referred to as class variables, whereas variables at the
instance level are called instance variables.
Q.10) What is class variable?
Ans : Class variables are defined within the class construction. Because they are owned by
the class itself, class variables are shared by all instances of the class. They therefore will
generally have the same value for every instance unless you are using the class variable to
initialize a variable.
UNIT – III
Part – B (Each question carries Three marks)
Q.1) What is the purpose of encode() and decode() method.
Ans : encode() method can be used to covert from the default Unicode encoding.
Decode() method can be used to covert back to the Unicode default encoding.
Q.2) How will you add, update or delete an attribute of class instance without using
in-built functions.
Ans : Add a new attribute with an assigned value
chick = Bird(‘Cheep, Cheep!’)
chick.age= ‘1 week’
modify the new attribute
setattr (chick, ‘age’ , ‘3 weeks’)
Remove the new attribute
delattr (chick, ‘age’)
print(‘\n Chick age Attribute?’ , hasattr(click, ‘age’))
Q.3) What in-built functions are used to add, modify or remove an attribute of
an instance?
Ans :
UNIT – III
Part – C (Each question carries Five marks)
Q.3) What are the ways to add, update or delete an attribute of class instance.
Ans : Add : add a statement to create an instance of the class
polly=Bird(‘squawk,squawk!’
Delete : Remove the new attribute and confirm its removal using a built-in function
Delattr (chick, ‘age’)
Q.7) How will you print the Unicode name of each character of string?
Ans : Provide a name() method that reveals the Unicode name of each character. Accented
and non-Latin character can be referenced by their Unicode name or by decoding their
Unicode hexadecimal code point value.
s = ‘ROD’
print ( ‘\nRed String:’ , s)
print(‘Type :’ , type (s), ‘\tLenght:’ , len(s))
s=s.encode(‘utf-8’)
print(‘\Encoded String:’,s)
printf(‘Type:’,type(s), ‘\tLength:’,len(s))
s=s.decode(‘utf-8’)
print(‘\nDecoded String:’,s)
pg. 19 Modern College, Wadi, Nagpur
Python Notes
print(‘Type:’,type(s), ‘\tLength:’,len(s))
import unicodedate
for i in range(len(s)):
print(s[i], unicodedata.name(s[i]), sep= ‘:’)
s = b ‘Gr\xc3\xb6n’
print( ‘\nGreen String:’,s.decode(‘utf-8’))
s= ‘Gr\N{LATIN SMALL LETTER O with DIAERESIS}n’
print(‘Green String:’ ,s)
UNIT – IV
Part – A (Each question carries Two marks)
Q.7) What statement you will write to specify text to appear on the face of the Button
widget.
Ans : We will extend and modify the previous example for this purpose. The method
create_text() can be applied to a canvas object to write text on it. The first two parameters are
the x and the y positions of the text object. By default, the text is centred on this position.
You can override this with the anchor option.
Q. 8) What are the states of the button recognized by tkinter?
Ans : The Button widget is a standard Tkinter widget used to implement various kinds of
buttons. Buttons can contain text or images, and you can associate a Python function or
method with each button. When the button is pressed, Tkinter automatically calls that
function or method.
Q.9) What is the role of cgi module?
Ans : the ‘cgi’ module, the support module for CGI scripts in Python
This will parse a query in the environment. We can also make it do so from a file, the default
for which is sys.stdin.
While this is deprecated, Python maintains it for backwards-compatibility. But we can use
urllib.parse.parse_qs() instead.
Q.10) What is the role of enc type attribute?
Ans : The enctype attribute specifies how the form-data should be encoded when submitting
it to the server. Note: The enctype attribute can be used only if method="post".
UNIT – IV
Part – B (Each question carries Three marks)
Q.1) What is the limitation of GET method.
Ans : The request string length cannot exceed characters, and the values appear in the
browser address field.
Internet Explorer also has a maximum path length of 2,048 characters. This limitapplies to
both POST request and GET request URLs. If you are using the GET method, you are limited
to a maximum of 2,048 characters, minus the number of characters in the actual path
button objects nominate an individual control variable object to assign a value to whether
checked or unchecked.
Q.10) What is the purpose of path.basename() method.
Ans : The full path address of the file selected for upload is a value stored in the FieldStorage
object list that can be accessed using its associated key name. Usefully the file name can be
stripped from the path address by the “OS” module’s path.basename() method.
UNIT – IV
Part – C (Each question carries Five marks)
Q.1) Create a new HTML document containing a form with two text fields and a
submit button.
Ans :
<!DOCTYPE HTML>
<html lang= “en”>
<head>
<meta charset= “UTF-8”>
<title> Python Form Values </title>
</head>
<body>
<form method= “Post” action = “post.py”>
Make: <input type= “text” name = “make” value = “ford”>
Model :
<input type = “text” name = “model” value = “Mustang”>
<P> <Input type = “submit” value = “Submit”></p>
</form>
</body>
</html>
Import cgi
data = cgi.FieldStorage()
make = data.getvalue(‘make’)
model = data.getvalue(‘model’)
print(‘content-type:text/html\r\n\r\n’)
print(‘<DOCTYPE HTML>’)
print(‘<html lang= “en”>’)
print(‘<head>’)
print(‘<meta charset = “UTF-8”>’)
print(‘<title>Python Response</title>’)
print(‘</head>’)
print(‘<body>’)
print(‘<h1>’, make, model, ‘</h1>’)
print(‘<a href= “post.html”>Back</a>’)
print(‘</body>’)
print(‘</html>’)
entry=Entry(frame)
def dialog() :
box.showinfo(‘Greetings’, ‘welcome’ + entry.get())
btn=Button(frame, text = ‘Entry Name’, command=dialog)
btn.pack(side=Right, padx=5)
entry.pack(side=LEFT)
frame.pack(padx=20, pady =20)
window.mainloop()
Ans :
Form random import random, sample
Num =random()
print(‘Random float 0.0-1.0 :’,num)
num = int(num * 10)
nums =[]; i=0
while i<6:
nums.append(int(random()*10)+1)
i+=1
print(‘Random Multiple integers 1-10:’, nums)
nums =sample(range(1,59),6)
print(‘Random Integer Sample 1-59 :’,nums)
Q.6) Create a new HTML document containing a form with a text area field and a
submit button.
Ans :
<!DOCTYPE HTML>
<html lang= “en”>
<head>
<meta charset= “UTF-8”>
<title> Text Area example </title>
</head>
<body>
<form method= “Post” action = “text.py”>
<textarea name= “Future Web” rows= “5” cols = “40”>
</textarea>
<input type= “Submit” value = “Submit”>
</form>
</body>
</html>
Import cgi
data = cgi.FieldStorage()
if data.getvalue(‘Future Web’) :
text=data.getvalue(‘future Web’)
else :
text = ‘Please Enter Text!’
print(‘content-type:text/html\r\n\r\n’)
print(‘<DOCTYPE HTML>’)
print(‘<html lang= “en”>’)
print(‘<head>’)
print(‘<meta charset = “UTF-8”>’)
print(‘<title>Python Response</title>’)
print(‘</head>’)
print(‘<body>’)
print(‘<h1>’, text , ‘</h1>’)
print(‘<a href= “text.html”>Back</a>’)
print(‘</body>’)
print(‘</html>’)
Q.7) Create a new HTML document containing a form with one group of three radio
buttons and a submit button.
Ans :
form tkinter import*
import tkinter.messagebox as box
window = Tk()
window.title(‘Redio Button Example’)
frame =Frame(window)
book = StringVar( )
radio_1 = Radiobutton(frame, text = ‘HTML5’,variable=book, value= ‘HTML5 in easy steps’)
radio_2 = Radiobutton(frame, text = ‘CCS3’, variable=book, value= ‘CCS3 in easy steps’)
radio_3 = Radiobutton(frame, text = ‘Java’, variable=book, value= ‘Java in easy steps’)
radio_1.select()
def dialog()
box.showinfo(‘Selection’, ‘Your Choice : \n’ + book.get())
btn =Button(frame, text = ‘Choose’, command=dialog)
btn.pack(side = Right, padx =5)
radio_1.pack(side = LEFT)
radio_2.pack(side = LEFT)
radio_3.pack(side = LEFT)
frame.pack(padx =30, pady =30)
window.mainloop()
Q.8) Create a new HTML document containing a form with a drop-down options list
and a submit button.
Ans :
<!DOCTYPE HTML>
<html lang= “en”>
<head>
<meta charset= “UTF-8”>
<title> selection list example </title>
</head>
<body>
<form method= “Post” action = “selection.py”>
<select name= “Citylist”>
<option value= “New York”>New York</option>
<option value= “London”>London</option>
<option value= “Paris”>Paris</option>
<option value= “Beijing”>Beijing</option>
</select>
<input type= “Submit” value = “Submit”>
</form>
</body>
</html>
Import cgi
data = cgi.FieldStorage()
city = data.getvalue(‘CityList’)
print(‘content-type:text/html\r\n\r\n’)
print(‘<DOCTYPE HTML>’)
print(‘<html lang= “en”>’)
print(‘<head>’)
print(‘<meta charset = “UTF-8”>’)
print(‘<title>Python Response</title>’)
pg. 26 Modern College, Wadi, Nagpur
Python Notes
print(‘</head>’)
print(‘<body>’)
print(‘<h1>’,City, city, ‘</h1>’)
print(‘<a href= “selection.html”>Back</a>’)
print(‘</body>’)
print(‘</html>’)