0% found this document useful (0 votes)
11 views27 pages

Python Notes

Uploaded by

usghormare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
11 views27 pages

Python Notes

Uploaded by

usghormare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 27

Python Notes

UNIT – I
Part – A (Each question carries Two marks)

Q.1) What is 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.
Q.2) What is comment? Give an example.
Ans : Comments can use them to write notes or remind yourself what the code is trying to
do. Any text for the rest of the line following a hash mark (#) is part of a comment.
Ex : # This program says hello and asks for my name.
Q.3) What are the supported data types in Python?
Ans : Python has five standard data types −
• Numbers : int, float, complex
• String :
• List
• Tuple
• Dictionary

Q.4) List any 8 keywords of python.


Ans : False, Class, Finally, is, return, None, continue, for, lambda, try, true, def, from,
nonlocal, while, and, del, global, not, with as, elif, if, or, yield, assert, else, import, pass,,
break, else, import, pass, except, in, raise
Q 5) Define lists in Python.
Ans: A list is a collection which is ordered and changeable. In Python lists are written with
square brackets.
Q.6) What is negative index in Python?
Ans : While indexes start at 0 and go up, you can also use negative integers for the index.
The integer value -1 refers to the last index in a list, the value -2 refers to the second-to-last
index in a list, and so on.
Q.7) How you can convert a number to a string?
Ans : Step 1 :
Type "str (number)".
Step 2 :
Press "Enter". This runs the string function to convert an integer to a string.
Q.8) What are the built-in types available in Python?
Ans : The principal built-in types are numerics, sequences, mappings, classes, instances
and exceptions.
Q.9) What is a string in Python?
Ans : A string is a sequence of characters.
A character is simply a symbol. For example, the English language has 26 characters.
Computers do not deal with characters, they deal with numbers (binary). Even though you
may see characters on your screen, internally it is stored and manipulated as a combination
of 0's and 1's.
Q. 10) What is keyword? List any 4 keywords in Python.
Ans : Keywords is a reserved words in Python.
False, Class, Finally, is, return, None, continue, for, lambda, try, true, def, from, nonlocal,
while, and, del, global, not, with as, elif, if, or, yield, assert, else, import, pass,, break, else,
import, pass, except, in, raise
pg. 1 Modern College, Wadi, Nagpur
Python Notes

Q. 11) What is Assignment operator in Python? Give example.


Ans :
Operator Description Example
Assigns values from right side operands to
= c = a + b assigns value of a + b into c
left side operand
+= Add It adds right operand to the left operand
c += a is equivalent to c = c + a
AND and assign the result to left operand
-= It subtracts right operand from the left
Subtract operand and assign the result to left c -= a is equivalent to c = c - a
AND operand
*= It multiplies right operand with the left
Multiply operand and assign the result to left c *= a is equivalent to c = c * a
AND operand
It divides left operand with the right
/= Divide c /= a is equivalent to c = c / ac /= a
operand and assign the result to left
AND is equivalent to c = c / a
operand
%=
It takes modulus using two operands and
Modulus c %= a is equivalent to c = c % a
assign the result to left operand
AND
**= Performs exponential (power) calculation
Exponent on operators and assign value to the left c **= a is equivalent to c = c ** a
AND operand
//= Floor It performs floor division on operators and
c //= a is equivalent to c = c // a
Division assign value to the left operand

Q.12) How will you print multiple fields using print()?


Ans : print() function. Below are equivalent codes in Python 3.0.
Code :
Print (1,2,3)
Output : 1 2 3
Q.13) What is the role of ** operator in Python.
Ans : ** exponent : performs exponential (power) calculation on operators
Ex : a**b= 10 to the power of 20
Ex. : x = 5
x **= 3
print(x)
Ans : 125

Q.14) Write down the syntax of while loop.


Ans : The syntax of a while loop
while expression:
statement(s)

Q.15) Write down the syntax of for loop.


Ans : Syntax
for iterating_var in sequence:
statements(s)

pg. 2 Modern College, Wadi, Nagpur


Python Notes

Part - B
(Each question carries Three marks)

Q.1) What are the built-in type does python provides?


Ans : The principal built-in types are numerics, sequences, mappings, classes, instances and
exceptions. Some collection classes are mutable. The methods that add, subtract, or
rearrange their members in place, and don’t return a specific item, never return the collection
instance itself but. Some operations are supported by several object types; in particular,
practically all objects can be compared, tested for truth value, and converted to a string (with
the repr() function or the slightly different str() function). The latter function is implicitly used
when an object is written by the print() function.
Q.2) What is keyword? List any 8 keywords of python.
Ans : Ref Q. 4 and 10 in 2 marks
Q.3) What are tuples in Python?
Ans : A tuple is a collection which is ordered and unchangeable. In Python tuples are
written with round brackets.
Example
Create a Tuple:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Q.4) How will you take the prompt input from user?
Ans : The parameter inside the parentheses after input is important. It is a prompt, prompting
you that keyboard input is expected at that point, and hopefully indicating what is being
requested. Without the prompt, the user would not know what was happening, and the
computer would just sit there waiting!
Q.5) Write down the syntax of if else in python?
Ans : The syntax of the if...else statement is −
if expression:
statement(s)
else:
statement(s)
Q.6) What is slicing in Python?
Ans : The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or
any object which supports sequence protocol (implements __getitem__() and __len__()
method).
Slice object represents the indices specified by range(start, stop, step).
The syntax of slice() are:
slice(stop)
slice(start, stop, step)
Q.7) How can you share global variables across modules?
Ans : In Python, a conventional global variable is only used to share a value within classes
and function. A variable- once declared as a global within a function or class- can then be
modified within the segment.
num = 1
def increment():
global num
num += 1
Q. 8) What is the purpose of // operator?
Ans : // Floor Division - The division of operands where the result is the quotient in which
the digits after the decimal point are removed. But if one of the operands is negative, the
result is floored, i.e., rounded away from zero .

pg. 3 Modern College, Wadi, Nagpur


Python Notes

Q.9) Mention the use of // operator in Python?


Ans : ref. Q. 8
a = 10
b=5
c = a//b
print "Line 7 - Value of c is ", c
10. What is floor division? Give example
Ans : ref Q.8 & Q. 9
11. Mention the use of the split function in Python?
Ans : split() method returns a list of strings after breaking the given string by the specified
separator.
Syntax :
str.split(separator, maxsplit)
Parameters :
separator : The is a delimiter. The string splits at this specified separator. If is not provided
then any white space is a separator.
maxsplit : It is a number, which tells us to split the string into maximum of provided
number of times. If it is not provided then there is no limit.
Q.12) What is the purpose of ** operator?
Ans : Ref. Q. 13 in 2 marks
Q.13) How do you write a conditional expression in Python?
Ans : conditions can be used in several ways, most commonly in "if statements" and loops.
An "if statement" is written by using the if or if else keyword.
Ref. Q. 5 in 3 marks
14. How will you create a dictionary in python?
Ans : A dictionary is a collection which is unordered, changeable and indexed. In Python
dictionaries are written with curly brackets, and they have keys and values.
Example
Create and print a dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Q.15) Define the term pickling and un-pickling?
Ans : Pickling : An process of pickling objects stores a string representation of an object
that can later be “unpickled” to its former state and is a very common python programming
procedure.
Q.16) Describe logical operators with example?
Ans : 1) AND : If both the operands are true then condition become true.
Ex. x = 5
print(x > 3 and x < 10)
2) OR : if any of the two operands are non-zero then condition become true.
Ex. : x = 5
print(x > 3 or x < 4)
3) NOT : Used to reverse the logical state of its operand
Ex : x = 5
print(not(x > 3 and x < 10))
Example :
Q.17) Write the syntax of loops in python.
Ans : ref . Q. 14 and 15 in 2 marks
pg. 4 Modern College, Wadi, Nagpur
Python Notes

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

Q.3) Write down important features of python.


Ans : 1) Easy to Learn and use 2) Expressive Language 3) Interpreted Language 4) Cross-
platform Language 5) Free and Open Source 6) Object Oriented Language 7) Extensible 8)
Large Standard Library 9) GUI Programming Support 10) Integrated

Q.4) Describe any five list methods.


Ans : 1) list.append(obj) : The element represented by the object obj is added to the list
2) list.clear() : It removes all the elements from the list.
3) list.copy() : It returns a shallow copy of the list
4) list.count(obj) :It returns the number of occurrences of the specified object in the list
7) list.insert(index,obj) : The object is inserted into the list at the specified index
9) list.remove(obj) : It removes the specified object from the list.
10) list.reverse() : It reverses the list
Q.5) What is module and package in Python?
Ans : A python module can be defined as a python program file which contains a python code
including python functions, class, or variables. In other words, we can say that our python
code file saved with the extension (.py) is treated as the module. We may have a runnable
code inside the python module.
Modules in Python provides us the flexibility to organize the code in a logical way.
To use the functionality of one module into another, we must have to import the specific
module. Let's create the module named as file.py.

pg. 5 Modern College, Wadi, Nagpur


Python Notes

1. #displayMsg prints a message to the name being passed.


2. def displayMsg(name)
3. print("Hi "+name);
The packages in python facilitate the developer with the application development environment
by providing a hierarchical directory structure where a package contains sub-packages,
modules, and sub-modules. The packages are used to categorize the application level code
efficiently.
Q.6) What is the difference between tuples and lists in Python?
Ans :
List Tuples
Lists are surrounded by square Tuples are surrounded by parenthesis
brackets [] ().
Creating List : Creating Tuple
list_num = [1,2,3,4] tup_num = (1,2,3,4)
a variable called list_num which hold a a variable tup_num; which contains a
list of numbers tuple of number
List has mutable nature tuple has immutable nature

Q.7) What is conditional expression in Python? Explain with example.


Ans : ref. Q. 13 in 3 Marks
Example :
a = 33
b = 200
if b > a:
print("b is greater than a")
Q.8) How will you define alternative separator for multiple fields in print()?Give
example.
Ans :
Q.9) Explain three types of errors that can occur in python.
Ans : 1) Syntex error : Error caused by not following the proper structure (syntax) of the
language is called syntax error or parsing error.
2) Run time error : Errors can also occur at runtime and these are called exceptions.
3) EOFErroor : Raised when the input() functions hits end of file condition.
4) IndexError : Raised when index of a sequence is out of range.
Q.10) Explain bitwise operators of python.
Ans : The bitwise operators perform bit by bit operation on the values of the two operands.
1) & (and) : If both the bits at the same place in two operands are 1, then 1 is copied to
the result. Otherwise, 0 is copied
2) |(or) : The resulting bit will be 0 if both the bits are zero otherwise the resulting bit
will be 1
3) ^(xor) : The resulting bit will be 1 if both the bits are different otherwise the resulting
bit will be 0
4) ~ (negation) : It calculates the negation of each bit of the operand, i.e., if the bit is 0,
the resulting bit will be 1 and vice versa
5) << (left Shift) : The left operand value is moved left by the number of bits present in
the right operand
6) >> (right shift) : The left operand is moved right by the number of bits present in the
right operand
Q.11) What is list? Explain with example.
Ans : List in python is implemented to store the sequence of various type of data. However,
python contains six data types that are capable to store the sequences but the most
common and reliable type is list.

pg. 6 Modern College, Wadi, Nagpur


Python Notes

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)

pg. 7 Modern College, Wadi, Nagpur


Python Notes

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 :

Q.6) How will you see python version on >>> prompt?


Ans : C:\Users\Your Name>python
Python 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
OR
1. Open Windows Search
2. Type py t h o n into the search bar.
3. Click Python [command line]. This opens a black terminal window to a Python prompt.
4. Find the version in first line. It’s the number right after the word “Python” at the top-
left corner of the window (e.g. 2.7.14).

Q.7) Define datetime module.


Ans : A date in Python is not a data type of its own, but we can import a module named
datetime to work with dates as date objects.
The datetime Module
The datetime module enables us to create the custom date objects, perform various
operations on dates like the comparison, etc.
To work with dates as date objects, we have to import datetime module into the python
source code.
Q.8) What is the purpose of today() method?
Ans : today() Return the current local date.
This is equivalent to date.fromtimestamp(time.time()).

Q.9) What is the purpose of getattr() method?


Ans: The getattr() method returns the value of the named attribute of an object. If not
found, it returns the default value provided to the function.
Q.10) What is the purpose of decimal function?
Ans : Decimal “is based on a floating-point model which was designed with people in mind,
and necessarily has a paramount guiding principle – computers must provide an arithmetic
pg. 8 Modern College, Wadi, Nagpur
Python Notes

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 :

Q.4) Describe variable scope in python


Ans : All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −
• Global variables
• Local variables

Q.5) What is the purpose of yield keyword in python?
Ans : the yield keyword is only used with generators, it makes sense to recall the concept of
generators first.
The idea of generators is to calculate a series of results one-by-one on demand (on the fly).
In the simplest case, a generator can be used as a list, where each element is calculated
lazily. Lets compare a list and a generator that do the same thing - return powers.
Q.6) What is the purpose of try block?
Ans : The try block lets you test a block of code for errors.
When an error occurs, or exception as we call it, Python will normally stop and generate an
error message.
These exceptions can be handled using the try statement:

pg. 9 Modern College, Wadi, Nagpur


Python Notes

Q.7) What is the purpose of finally block?


Ans : finally block lets you execute code, regardless of the result of the try- and except
blocks.
The finally block, if specified, will be executed regardless if the try block raises an error or
not.
Ex : try:
print(x)
except:
print("Something went wrong")
finally:
print("The 'try except' is finished")

Q.8) How will you display the list of python keywords?


Ans : Ref. Q. 12 in two marks

Q.9) Write a program to print current day, month and year.


Ans : import datetime
x = datetime.datetime.now()
print(x.strtime(“%d))
print(x.year)
print(x.strftime("%A"))

Q. 10) Define any three built-in exceptions.


Ans : - exception ArithmeticError
The base class for those built-in exceptions that are raised for various arithmetic
errors: OverflowError, ZeroDivisionError, FloatingPointError.
exception BufferError
Raised when a buffer related operation cannot be performed.
exception LookupError
The base class for the exceptions that are raised when a key or index used on a
mapping or sequence is invalid: IndexError, KeyError. This can be raised directly by
codecs.lookup().

Q.11) What is mean by lambda expression?


Ans : A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.
The syntax to define an Anonymous function is given below.
1. lambda arguments : expression
Example 1
1. x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluate
d and returned.
2. print("sum = ",x(20))
Output:
sum = 30
Q.12) What is the purpose of ‘pass’ keyword?
Ans : pass keyword is used to execute nothing; it means, when we don't want to execute
code, the pass can be used to execute empty. It is same as the name refers to. It just makes
the control to pass by without executing any code. If we want to bypass any code pass
statement can be used.
Ex. :
for i in [1,2,3,4,5]:
if i==3:
pass
print "Pass when value is",i
print i,
pg. 10 Modern College, Wadi, Nagpur
Python Notes

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

Q.5) What is mean by lambda expression? Explain


Ans : Python allows us to not declare the function in the standard manner, i.e., by using the
def keyword. Rather, the anonymous functions are declared by using lambda keyword.
However, Lambda functions can accept any number of arguments, but they can return only
one value in the form of expression.
The anonymous function contains a small piece of code. It simulates inline functions of C
and C++, but it is not exactly an inline function.
The syntax to define an Anonymous function is given below.
1. lambda arguments : expression
Example 1
1. x = lambda a:a+10 # a is an argument and a+10 is an expression which got evaluate
d and returned.
2. print("sum = ",x(20))
Q.6. Write a program to generate Fibonacci series using yield keyword.
Ans :
def incrementer():
a=b=1
while True :
yield a
a, b = b, a + b

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 :

Q.8) What is the difference between assert and exception.


Ans :
Assert Exception
An assertion is a (debugging) boolean An exception is similar to an assertion but
expression to self check an assumption the meaning is different. An exception is an
about the internal state of a function or unexpected execution event that disrupts
object. If true, nothing happens otherwise, the normal flow of the program. Exceptions
execution halts and an error is thrown. are used to signal an error condition where
Assertion is a way to declare a condition that a corrective action can be taken (ex. file not
is impossible to occur. If it does that means found). Exceptions can be caught and
the code is not just buggy but broken or recovered from as opposed to assertions. The
unrecoverable. Assertions are typically used next section gives few example scenarios
to do sanity checking that is too expensive where exceptions can be used…
for production use. The feedback given by an
assertion is for the development team as
opposed to the user. In the next section, we
will mention scenarios in which assertions
are a good choice to use…

Q.9) What is function? Describe any four mathematical functions in Python.


Ans : A function is a block of organized, reusable code that is used to perform a single,
related action. Functions provide better modularity for your application and a high degree
of code reusing.
pg. 12 Modern College, Wadi, Nagpur
Python Notes

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

%a Weekday, short version Wed

%A Weekday, full version Wednesday

%w Weekday as a number 0-6, 0 is Sunday 3

%d Day of month 01-31 31

%b Month name, short version Dec

%B Month name, full version December

%m Month as a number 01-12 12

%y Year, short version, without century 18

%Y Year, full version 2018

%H Hour 00-23 17

%I Hour 00-12 05

pg. 13 Modern College, Wadi, Nagpur


Python Notes

%p AM/PM PM

%M Minute 00-59 41

%S Second 00-59 08

%f Microsecond 000000-999999 548513

%z UTC offset +0100

%Z Timezone CST

%j Day number of year 001-366 365

%U Week number of year, Sunday as the first day 52


of week, 00-53

%W Week number of year, Monday as the first day 52


of week, 00-53

%c Local version of date and time Mon Dec 31 17:41:00


2018

%x Local version of date 12/31/18

%X Local version of time 17:41:00

%% A % character %

Q.12) Write a program to generate numbers from 10 to 1 at the intervals of 1 second.


Ans :
from time import*
start_timer=time()
struct=localtime(start_timer)
print(‘\n starting countdown at :’,strftime(‘%X’,struct))
i=10
while i>-1:
print (i)
i - =1
sleep (1)
end_timer=time()
difference = round(end_timer - short_timer)
print(‘\n runtime:’, difference, ‘seconds’)
Q.13) Explain the meta characters used for pattern matching with example
Ans : Most letters and characters simply match themselves. However, there are some
characters called metacharacters, that don’t match themselves. Instead, they indicate that
some pattern should be matched, or they repeat or change parts of the regular expression.
Here’s a complete list of the metacharacters
.^$*+?{}[]\|()
EX :
pg. 14 Modern College, Wadi, Nagpur
Python Notes

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

print('415-555-4242 is a phone number:')


print(isPhoneNumber('415-555-4242'))
print('Moshi moshi is a phone number:')
print(isPhoneNumber('Moshi moshi'))

pg. 15 Modern College, Wadi, Nagpur


Python Notes

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.

pg. 16 Modern College, Wadi, Nagpur


Python Notes

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 :

Q.4) Define method overriding.


Ans : A method can be declared in a derived class to override a matching methods in the base
class – if both method declarations have the same name and the same number of listed
arguments.
Q.5) What is DocString?
Ans : Python documentation strings provide a convenient way of associating documentation
with python module, functions, classes, and methods.
As object’s docsting is defined by including a string constant as the first statement in the
object’s definition.
It’s specified in source code that is used, like a comment, to document a specific segment of
code
Q.6) What is the purpose of built-in dir() function.
Ans : The Python built-in dir() function can be useful to examine the names of functions and
variable defined in module by specifying the module name within its parentheses. Interactive
mode can easily be used for this purpose by importing the module name then calling the dir()
function.
Q.7) Explain file opening modes in Python.
Ans : Firstly must always be opened using the open() method. This requires two string
arguments to specify the name and location of the file, and one of the following mode specifiers
in which to open the file
File mode : Opration
r : Open an existing file to read
w : open an existing file to write. Create a new file in none exists or open exiting file.
a : Append text.
r+ : Open a text file to read from or write to
w+ : Open a text file to write to or read from
a+ : Open or creates a text file to read from or write to at the end of the file.
Q.8) Describe the file object properties.
Ans :
File object properties are following
name : Name of the opened file
mode : mode in which the file was opened
pg. 17 Modern College, Wadi, Nagpur
Python Notes

closed : status boolen value of True or False


readable() : read permission Boolean value of True or False
Writable() : write permission boolen value of true or false.
Q.9) What is the role of __init__() method.
Ans : __init__ is a special method in Python classes, it is the constructor method for a class.
__init__ is called when ever an object of the class is constructed. That means when ever we
will create a student object we will see the message “A student object is created” in the
prompt. You can see the first argument to the method is self. It is a special variable which
points to the current object (like this in C++). The object is passed implicitly to every method
available in it, but we have to get it explicitly in every method while writing the methods.
Example shown below. Remember to declare all the possible attributes in the __init__ method
itself. Even if you are not using them right away, you can always assign them as None
Q.10) What are the contents of __builtins__ modules?
Ans : This module provides direct access to all ‘built-in’ identifiers of Python.
__builtin__.open is the full name for the built-in function open(). See Built-in
Functions and Built-in Constants for documentation.
This module is not normally accessed explicitly by most applications, but can be useful in
modules that provide objects with the same name as a built-in value, but in which the built-
in of that name is also needed. For example, in a module that wants to implement
an open() function that wraps the built-in open(), this module can be used directly:

UNIT – III
Part – C (Each question carries Five marks)

Q.1) Describe various operators available for string manipulation.


Ans :
Operation Description Example
+ Concatenate – join strings together ‘Hello’ + ‘Mike’
* Repeat – Multiply the string ‘Hello’ * 2
[] Slice – Select a character at a specified index ‘Hello’ [0]
position
[:] Range Slice – select characters in a specified index ‘Hello’ [ 0:4]
range
in Membership inclusive – return True if character ‘H’ in ‘Hello’
exists in the string
Not in Membership Exclusive – return True if character ‘h’ not in ‘Hello’
doesn’t exist in string
r/R Raw String – suppress meaning of escape character print( r ‘\n’)
“‘ ’” Docstring – describe a module, function, class or def sum (a,b): ‘“Add
method Args”’

Q.2) List different meta characters with meaning and example.


Ans :
Metacharacter Matches Example
. Any Characters py..on
^ First Characters ^py
$ Final Characters …..on$
* Zero or More Repetitions py*
+ One or more repetitions py+
? Zero or one Repetitions py?
{} Multiple Repetitions a{ 3 }
pg. 18 Modern College, Wadi, Nagpur
Python Notes

[] Character class [ a-z ]


\ Special sequence \s
| Either Optional Character a|b
() Expression Group ( …. )

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!’

Update : Update the new attribute using dot notation


Chick.age = ‘2 weeks’

Delete : Remove the new attribute and confirm its removal using a built-in function
Delattr (chick, ‘age’)

Q.4) Write a program to display class dictionary attributes.


Ans : class MyClass(object):
class_var = 1
def __init__(self, i_var):
self.i_var = i_var

Q.5) What is the purpose of dump() and load() method in Python.


Ans : An object can be converted for storage in a file by specifying the object and file as
arguments to the pickle object’s dump() Method.
Ex. : Add a statement to dump the values contained in variable as data into the binary file
Pickle.dump(data, file)
It can later be restored from that file by specifying the file name as the sole argument to the
pickle object’s load() method.
Ex. : add a statements to load the data stored in that existing file.
Data = pickle.load(file)

Q.6) Describe any 5 string methods.


Ans : 1) capitalize( ) : Change string’s first letter to uppercase
2) title() : Change all first letters to uppercase
3) join(seq) : Merge string into separator sequence seq
4) replace (old, new) : Replace all occurrences of old with new
5) center (w, c) : Pad string each side to total column width w with character c(default is space)
6) find(sub) Return the index number of the first occurrence of sub or return -1 if not found
7) upper(), lower(), swapcase() : Change the case of all letter to uppercase, to lowercase, or to
the inverse of the current case respectively.

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)

Q.8) Explain seek() and tell() function with example.


Ans : Seek() : This position within the file, from which to read or at which to write , can be finely
controlled using the file objects seek() method.
Tell() : the current position within a file can be discovered at any time by calling the file object’s
tell() method to return an integer location.
Example :
Text = ‘the political slogan “Workers of the world unite!” is from the Communist manifesto
with open( ‘undate.txt’ , ‘w’) as file :
file.write(text)
print( ‘\nFile Now Closed?:’. file.closed)
print( ‘File Now Closed?:’, file.closed)
with open(‘update.txt’, ‘r+’) as file :
text = file.read()
print( ‘\nString :’, text)
print( ‘\n Position in File Now :’, file.tell())
position = file.seek(33)
print( ‘Position in file Now :’, file.tell())
file.write(‘All Lands’)
file.seek(59)
file.write(‘the tombstone of Karl Marx.’)
file.seek(0)
text = file.read()
print( ‘\nString :’, text)

Q.9) Describe readable() and writable() method in python.


Ans : readable() : read permission Boolean value of True or False
writable() : write permission boolen value of true or false.

Q.10) Explain read() and write() method in python.


Ans : read() : The read() method returns the entire content of the file. A file object’s read()
method will, by default, read the entire contents of the file from the very beginning at index
position zero, to the very end- at the index position of the file character.
write () : the write() method adds content to the file.
Ex . file=write( ‘(Oscar Wilde)’)

pg. 20 Modern College, Wadi, Nagpur


Python Notes

UNIT – IV
Part – A (Each question carries Two marks)

Q.1) What is purpose of image_create() method?


Ans : Images are placed into the text widget by calling that widget's .image_create() method.
See below for the calling sequence and other methods for image manipulation.
Q.2) What is the purpose of create_image() method?
Ans : To display a graphics image on a canvas C, use: id = C.create_image ( x, y, option, ...
) This constructor returns the integer ID number of the image object for that canvas.
Q.3) Which methods are used to add widget to an GUI application.
Ans : The Scale widget is used to provide a slider widget. The Scrollbar widget is used to
add scrolling capability to various widgets, such as list boxes. The Text widget isused to
display text in multiple lines. The Toplevel widget is used to provide a separate window
container.
Q.4) What is purpose of range() function.
Ans : The range() function is used to generate a sequence of numbers over time. At its
simplest, it accepts an integer and returns a range object (a type of iterable). In Python 2,
the range() returns a list which is not very efficient to handle large data.
Q.5) What is the role of sample() method.
Ans : sample() is an inbuilt function of random module in Python that returns a particular
length list of items chosen from the sequence i.e. list, tuple, string or set. Used for random
sampling without replacement.
Q.6) What statement you will write to prevent the user from resizing the window at
runtime?
Ans : Form the form properties window set :
1. FormBorderStyle -> FixedSingle
2. MaximizeBox -> False
3.

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

pg. 21 Modern College, Wadi, Nagpur


Python Notes

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

Q.2) What are the advantages of POST method?


• Ans : It is more secure than GET because user-entered information is never visible in the
URL query string or in the server logs.
• There is a much larger limit on the amount of data that can be passed and one can send
text data as well as binary data (uploading a file) using POST.
• Since the data sent by the POST method is not visible in the URL, so it is not possible to
bookmark the page with specific query.
Q.3) What is the purpose of FieldStorage() constructor?
Ans : This module’s Fieldstorage() constructor can create an object to store the posted data as a
dictionary of key: value pairs for each form field. Any individual value can be retrieved by
specifying its associated key name to the object’s getvalue() method.
Q.4) What is the role of mainloop() method?
Ans : The mainloop() method to capture events, such as when the user closes the window to
quit the program. This loop should appear at the end of the program as its also handles
windows updates that may be implemented during execution.
Q.5) What is purpose of Entry() constructor?
Ans : The Entry widget provides a single-line input field in an application where the program
can gather entries from the user. An entry object is created by specifying the name of its
parent container, such as a window or frame name, and options as arguments to an Entry()
constructor.
Q.6) What is purpose of Frame() constructor?
Ans : A frame object is crated by specifying the name of the window to a frame() constructor. The
frame’s name can then be specified as the first argument to the widget constructors to identify it
as that widget’s container.
Q.7) List any 6 methods used for showing buttons message.
Ans : Methods Buttons
1) showinfo() = OK
2) showwarning() OK
3) showerror() OK
4) askquestion() Yes (return the string ‘Yes’) and No (Returns the string ‘no’)
5) askokcancel OK(returns 1) and Cancel
6) askyesno() Yes (return 1) and No
7) askretrycancel() Retry (return 1) and Cancel
Q.8) Describe radio button constructor.
Ans : a Radiobutton widget provides a single item in an application that the user may select.
Where a number of radio buttons are grouped together, the user may only select any one item in
the group. A radio button object is created by specifying four arguments to a Radiobutton()
constructor.
Q.9) What are the arguments of Checkbutton() constructor in python.
Ans : A checkbutton widget provides a single item in an application that the user may select.
Where a number of check buttons appear together the user may select one or more items. Check

pg. 22 Modern College, Wadi, Nagpur


Python Notes

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

Finally save both file in the web server’s /htdocs directory

Q.2) Write a program to create entry widget in python.


Ans :
form tkinter import*
import tkinter.messagebox as box
window = Tk()
window.title(‘Entry Example’)
frame =Frame(window)

pg. 23 Modern College, Wadi, Nagpur


Python Notes

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

Q.3) Write a program to create list box in python.


Ans :
form tkinter import*
import tkinter.messagebox as box
window = Tk()
window.title(‘ ListBox Example’)
frame =Frame(window)
listbox.insert(1, ‘HTML5’)
listbox.insert(2, ‘JAVA’)
listbox.insert(1, ‘JAVASCRIPT’)
def dialog()
box.showinfo(‘Selection’, ‘Your Choice : ‘ +\
listbox.get( listbox.curselection()))
btn =Button(frame, text = ‘Choose’, command=dialog)
btn.pack(side = Right, padx =5)
listbox.pack(side = LEFT)
frame.pack(padx =30, pady =30)
window.mainloop()

Q.4) Write a program to demonstrate click event of button.


Ans : import tkinter as tk
def write_slogan():
print("Tkinter is easy to use!")
root = tk.Tk()
frame = tk.Frame(root)
frame.pack()
button = tk.Button(frame,
text="QUIT",
fg="red",
command=quit)
button.pack(side=tk.LEFT)
slogan = tk.Button(frame,
text="Hello",
command=write_slogan)
slogan.pack(side=tk.LEFT)
root.mainloop()

Q.5) Write a program to generate random number in the range of 1 to 10.


pg. 24 Modern College, Wadi, Nagpur
Python Notes

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

pg. 25 Modern College, Wadi, Nagpur


Python Notes

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

Q.9) Describe three geometry manager methods.


Ans : pack() = places the widget against a specified side of the window using TOP, BOTTOM,
LEFT or Right constant values specified to its side=argument.
place() = place the widget at XY coordinates in the windows using numerical values specified to
its x= and y= arguments.
grid() = places the widget in a cell within the window using numerical values specified to its
row= and column= arguments.

Q.10) Describe five arguments to a Checkbutton() constructor


Ans : 1) Name of the parent container, such as the frame name
2) Text for a display label, as a text=text pair
3) control variable object, as a variable = variable pair
4) Value to assign if checked, as an onvalue = value pair
5) Value to assign if unchecked, as an offvalue = value pair.

pg. 27 Modern College, Wadi, Nagpur

You might also like