Python and Web Programming Assignment
Python and Web Programming Assignment
Individual Assignment
IDNo.: TTMR/271/15
April, 2023
Python and Web programming assignment-1
1. a. Write a python program that uses input to prompt a user for their name and then
welcomes them.
Eg: Enter your name: Berhanu
Hello Berhanu
Answer:
Name=input("Enter your name :")
print(f"Hello {Name}")
b. Write a program to prompt the user for hours and rate per hour to compute gross
pay
Eg: Enter Hours: 35
Enter Rate: 2.75
Pay: 96.25
Answer:
hours=int(input('Enter Hours:'))
rate=float(input('Enter Rate: '))
grosspay=hours*rate
print('Pay: ',grosspay)
The python __init__ method is declared within a class and is used to initialize the attributes of an
object as soon as the object is formed. __init__ is one of the reserved methods in Python. In object
oriented programming, it is known as a constructor.
Answer:
Local variables can only be accessed within the function or module in which they are defined, in
contrast to global variables, which can be used throughout the entire program. In Python, a Global
variable can be defined using the global Keyword, also we can make changes to the variable in the
local context.
1
2. a. Write a for loop that prints all elements of a list and their position in the list.
a = [4,7,3,2,5,9]
Answer:
a = [4,7,3,2,5,9]
print(a)
for c,i in enumerate(a):
print(c, i)
Answer:
dict1 = {'a': 1, 'b':2}
for c,i in dict1.items():
inv_map = {v: k for k, v in dict1.items()}
print(inv_map)
Using randrange() and randint() functions of a random module, we can generate a random integer
within a range. I will show some of them with as follows.
import random
print(random.randrange(100,999,3))
print(random.randint(0,9))
print(random.sample(range(0, 1000), 10))
3. a. Write a program to prompt for a score between 0.0 and 1.0. If the score is out of
range, print an error. If the score is between 0.0 and 1.0, print a grade using the
following table:
Eg: Score Grade
>= 0.9 A
>= 0.8 B
>= 0.7 C
2
>= 0.6 D
< 0.6 FAIL
Sample Output:
Enter score: 0.95
A
Enter score:
11.5
Bad score
Enter score: 10.0
Bad score
Enter score: 0.75
C
Enter score: 0.5
FAIL
Answer:
score =float(input("Enter score: "))
if (score>= 0.0) and (score <= 1.0):
if score >= 0.9:
print("A")
elif score >= 0.8:
print("B")
elif score >= 0.7:
print("C")
elif score >= 0.6:
print("D")
else:
print("Fail")
else:
print("Bad Score")
Answer:
#Import math Library
import math
x=int(input('enter the first'))
y=int(input('enter the second'))
print (f'The Greatest Common Divisor(GCD) of {x} , {y} is: ', math.gcd(x, y))
3
#when i value equals to 6 the loop is continue to the next statement
for i in range(2,10,2):
if i==6:
continue
print(i)
print('----------------------------------')
#pass control statement used to make nothing happen on it
i=6
if i==6:
pass
4. a. Below is the program to calculate the area of a box. Check how it is working.
Correct the program (if required).
class Box:
def area(self):
return width * height
def __init__(self, width, height):
self.width = width
self.height = height
# Create an instance of Box.
x = Box(10, 2)
# Print area.
print(x.area()
Answer:
class Box:
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
# Create an instance of Box.
x = Box(10,2)
# Print area.
print(x.area())
b. Write a program to calculate distance so that it takes two Points (x1, y1) and (x2,
y2) as arguments and displays the calculated distance using Class.
class dis:
def distance(self, x1, y1, x2, y2):
# Calculating distance
return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
# Drivers Code
p = dis()
print(p.distance(3, 4, 4, 3))
c. Is multiple inheritance supported in Python?
4
Answer: Python is one of the few modern programming languages that supports multiple
inheritance. Multiple inheritance is the ability to derive a class from multiple base classes at the
same time.
5. a. Explain with a suitable example the differences between list, set, tuple and
dictionary data types in python.
Solution:
#intializing and dsiplay a list can be changeable ordered list
l=['a', 'b','s','d']
print(l)
#add list elemnt
l.append("Hi")
print(l)
#insert list elements on specified index
l.insert(2,'Baby')
print(l)
#combine to list elements /extend
list=['ex','By']
l.extend(list)
print(l)
#declaring and accessing a Tuple but is not modifiable
# means that is not possible to add or delete elements
tup=(1,2,3,4)
print(tup)
#declaring and accessing dictionary data type,
# unlike list and tuples it is unordered collections of objects
dic={1:'Abebe',2:'Solomon',3:'Dawit'}
print(dic)
print(dic[2])
#display dictionary elements only
print(dic.items())
#display key only
print(dic.keys())
#display dictionary values
print(dic.values())
#dictionary can be adding,changing and deleting
d={4:'PYTHON'}
dic.update(d)
print(dic)
#deleting
dic.pop(1)
print(dic)
#to display the length of dictionary
print(len(dic))
#Sets are neither mappings nor sequences, unorder collections and unchangeble
objects
s=set([9,2,3,4])
s2=set([1,2,4])
print(s,s2)
#union display all unique elements
print(s | s2)
#difference display all in 's2' that does not mach to 's'
print(s2 - s)
# intersection display intersect of 's' and 's2'
print(s & s2)
5
b. Explain different types of parameter passing techniques that are supported in python
functions.
Sometimes functions require input to provide data for their code. This input is defined using
parameters. Parameters are variables that are defined in the function definition. They are assigned
the values which were passed as arguments when the function was called, elsewhere in the code.
For example, the function definition defines parameters for a character, a setting, and a skill, which
are used as inputs to write the first sentence of a book.
def write_a_book(character, setting, special_skill):
print(character + " is in " + setting + " practicing her " +
special_skill)
Multiple Parameters
Python functions can have multiple parameters. Just as you wouldn’t go to school without both a
backpack and a pencil case, functions may also need more than one input to carry out their
operations.
To define a function with multiple parameters, parameter names are placed one after another,
separated by commas, within the parentheses of the function definition.
def ready_for_school(backpack, pencil_case):
if (backpack == 'full' and pencil_case == 'full'):
print ("I'm ready for school!")
When we define and call a Python function, the term parameter and argument is used to pass
information to the function.
parameter: It is the variable listed inside the parentheses in the function definition.
argument: It is a value sent to the function when it is called. It is data on which function
performs some action and returns the result.
Here’s what you need to know about the five common types of arguments in Python function
definition.
1. default arguments
2. keyword arguments
3. positional arguments
4. arbitrary positional arguments
5. arbitrary keyword arguments
findvolume(1, 2, 3)
findvolume(length=5, depth=2, width=4)
findvolume(2, depth=3, width=4)
3. Positional Arguments in Python
During a function call, values passed through arguments should be in the order of parameters in the
function definition. This is called positional arguments.
Keyword arguments should follow positional arguments only.
def add(a,b,c):
return (a+b+c)
The above function can be called in two ways:
First, during the function call, all arguments are given as positional arguments. Values passed
through arguments are passed to parameters by their position. 10 is assigned to a, 20 is assigned to b
and 30 is assigned to c.
print (add(10,20,30))
#Output:60
The second way is by giving a mix of positional and keyword arguments. Keyword arguments
should always follow positional arguments.
print (add(10,c=30,b=20))
#Output:60
We can declare a variable-length argument with the * (asterisk) symbol. Place an asterisk (*) before
a parameter in the function definition to define an arbitrary positional argument. we can pass
7
multiple arguments to the function. Internally all these values are represented in the form of a tuple .
Let’s understand the use of variable-length arguments with an example.
This is a simple function that takes three arguments and returns their average:
Use the unpacking operator(**) to define variable-length keyword arguments. Keyword arguments
passed to a kwargs are accessed using key-value pair (same as accessing a dictionary in Python).
Example:
6. a. Correct the below code so that it checks whether the database exists or not
import os
import sqlite3
db_filename = 'todo.db'
db_is_new = not xxxxxxx(db_filename)
conn = sqlite3.connect(db_filename)
if db_is_new:
print('Need to create schema')
print('Creating database')
8
else:
print('Database exists, assume schema does, too.')
conn.close()
Answer:
import os
import sqlite3
db_filename = 'todo.db'
if not os.path.isfile(db_filename):
db_is_new=True
conn = sqlite3.connect(db_filename)
print('Need to create schema')
print('Creating database')
else:
conn = sqlite3.connect(db_filename)
print('Database exists, assume schema does, too.')
conn.close()
b. Suppose Cars is a table already created. What is the keyword in place of “XXXX” to be
used to display the column names of the Cars table?
import sqlite3 as lite
import sys
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM Cars")
for colinfo in cur.XXXX:
Answer
import os
import sqlite3 as lite
con = lite.connect(test.db)
cur=con.cursor()
with con:
cur.execute("SELECT * FROM Cars")
for colinfo in cur.description:
print(colinfo)
Answer:
for i in range(1,10):
for n in range(0,i*2-1):
print("*",end=' ')
print(' ')
Answer:
import sqlite3 as lite
import sys
uId = 1
uPrice = 62300
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute("UPDATE Cars SET Price=? WHERE Id=?", (uPrice, uId))
con.commit()
print(f"Number of rows updated: %d" % cur.rowcount)
b. Correct the below code to display all the rows from the Cars table with their column
names.
import sqlite3 as lite
con = lite.connect('test.db')
with con:
cur = con.cursor()
cur.execute('SELECT * FROM Cars')
col_names = [cn[0] for cn in cur.XXXX]
rows =
cur.XXXXl()
print("%s %-10s %s" % (col_names[0], col_names[1], col_names[2]))
10
for row in rows:
print("%2s %-10s %s" % row)
Answer:
list = [1, 50, 60, 42, 30, 89, 45]
sum = 0
for i in list:
sum = sum + i
print('The sum of the list is = ', sum)
Similarly, for string data types, “+” operator is used to perform concatenation.
String1 = "Mengistu"
string2 = "Gurmu"
print(string1+" "+string2)
#As a result, the above program outputs Mengistu Gurmu
Here, we can see that a single operator “+” has been used to carry out different operations for
distinct data types. This is one of the most simple occurrences of polymorphism in Python.
There are some user defined and built-in functions in Python which are compatible to run with
multiple data types. One such built-in function is the len() function. It can run with many data types
in Python. Let's look at some example use cases of the function.
print(len("Programiz"))
print(len(["Python", "Java", "C"]))
print(len({"Name": "John", "Address": "Nepal"}))
Here, we can see that many data types such as string, list, tuple, set, and dictionary can work with the
len() function. However, we can see that it returns specific information about specific data types.
11
Polymorphism allows us to access these overridden methods and attributes that have the same name
as the parent class. Let's look at an example:
Here, we can see that the methods such as __str__(), which have not been overridden in the child
classes, are used from the parent class.
Due to polymorphism, the Python interpreter automatically recognizes that the fact() method for
object a(Square class) is overridden. So, it uses the one defined in the child class.
On the other hand, since the fact() method for object b isn't overridden, it is used from the Parent
Shape class.
Note: Method Overloading, a way to create multiple methods with the same name but different
arguments, is not possible in Python.
But by using Multiple Dispatch Decorator we can implement overloading. Multiple Dispatch
Decorator can be installed by: pip3 install multipledispatch
Example:
from multipledispatch import dispatch
# passing one parameter
@dispatch(int, int)
12
def product(first, second):
result = first*second
print(result)
# passing two parameters
@dispatch(int, int, int)
def product(first, second, third):
result = first * second * third
print(result)
# you can also pass data type of any value as per requirement
@dispatch(float, float, float)
def product(first, second, third):
result = first * second * third
print(result)
# calling product method with 2 arguments
product(2, 3) # this will give output of 6
# calling product method with 3 arguments but all int
product(2, 3, 2) # this will give output of 12
# calling product method with 3 arguments but all float
product(2.2, 3.4, 2.3) # this will give output of 17.985999999999997
Encapsulation is one of the key concepts of object-oriented languages like Python, Java, etc.
Encapsulation is used to restrict access to methods and variables. In encapsulation, code and data are
wrapped together within a single unit from being modified by accident.
Encapsulation is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as a single unit. In encapsulation, the variables of a class will be hidden from
other classes, and can be accessed only through the methods of their current class.
Example
class Students:
def __init__(self, name, rank, points):
self.name = name
self.rank = rank
self.points = points
# custom function
def demofunc(self):
print("I am "+self.name)
print("I got Rank ",+self.rank)
# create 4 objects
st1 = Students("Steve", 1, 100)
st2 = Students("Chris", 2, 90)
st3 = Students("Mark", 3, 76)
st4 = Students("Kate", 4, 60)
13
c. What is the lambda function in Python?
Lambda functions are similar to user-defined functions but without a name. They're commonly
referred to as anonymous functions.
Lambda functions are efficient whenever you want to create a function that will only contain simple
expressions – that is, expressions that are usually a single line of a statement. They're also useful
when you want to use the function once.
Example:
def mult(m):
return m * 2
mult(5)
#lambda function
lambda m: m * 2
The slice() function returns a slice object. A slice object is used to specify how to slice a sequence.
You can specify where to start the slicing, and where to end. You can also specify the step, which
allows you to e.g. slice only every other item.
Start: Optional. An integer number specifying at which position to start the slicing. Default is 0
End: An integer number specifying at which position to end the slicing
Step: Optional. An integer number specifying the step of the slicing. Default is 1
Example: Create a tuple and a slice object. Use the step parameter to return every third item:
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(0, 8, 3)
print(a[x])
Python also accepts function recursion, which means a defined function can call itself. Recursion is a
common mathematical and programming concept. It means that a function calls itself. This has the
benefit of meaning that you can loop through data to reach a result.
Answer:
14
def power(a, b):
# initialize result holder by 1
r = 1
# Multiply a for b times
for i in range(b):
r = r*a
return r
# Function call
num1=int(input("enter a number"))
num2=int(input("enter the exponent number"))
print(power(num1, num2))
b. Explain the differences between function, class, module, and package in python.
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result.
Classes in python act as a blueprint based on which objects are created. Objects are the very basis
for object-oriented programming. The objects are the real-world entities, and class acts as a template
that defines those objects.
Modules in Python are files with a .py extension using which we can reuse elements inside that file.
When we create a python program, the program may contain inside it functions, variables, and even
classes. Modules are python programs that can be imported into another python program. Importing
a module enables the usage of the module’s classes, functions and variables into another program.
To create large-scale-based real-world applications, we divide large code into smaller pieces to
perform different functionalities, resulting in many modules. To collaborate with all of the modules,
we create a Python package with an __init__.py file that informs the Python Interpreter that the
given folder is a Python Package.
Essentially, a class is a way of grouping functions (as methods) and data (as properties) into a logical
unit revolving around a certain kind of thing. If you don't need that grouping, there's no need to
make a class.
The main difference between a module and a package in Python is that a module is a simple Python
script with a .py extension file that contains collections of functions and global variables. In contrast,
a package is a directory that contains a collection of modules, and this directory also contains an
__init__.py file by which the interpreter interprets it as a package.
Modules are files present inside a package, whereas a class is used to encapsulate data and functions
together inside the same unit. Although modules and classes are very different, sometimes one may
get confused between their functionalities.
*args specifies the number of non-keyworded arguments that can be passed and the operations that
can be performed on the function in Python whereas **kwargs is a variable number of keyworded
arguments that can be passed to a function that can perform dictionary operations.
15
Let us assume that you are building a calculator which only performs addition. You can make a
simple function that can do this and that function will look like this-
def add(num1,num2):
return num1+num2
print("Addition:", add(2,3))
Output:
Addition:5
Now you want to add three numbers, so you have to make a new function.
def add(num1, num2, num3):
return num1+num2+num3
Output:
Addition: 6
We can already see the problem. If you keep going on like this, you will end up doing a lot of
functions. *args can save you the trouble here. We can use args to solve this problem in a simple and
flexible piece of code-
def add(*numbers):
sum=1
for n in numbers:
sum=sum+n
return sum
print("Addition: ",add(4,4,4,4,4,4))
Output:
Addition: 24
Now that our problem is solved let’s understand what is going on here. Python has *args, which
allows us to pass a variable number of non-keyword arguments to a function. Non-keyword here
means that the arguments should not be a dictionary (key-value pair), and they can be numbers or
strings. One thing to note here is that "args" is just an identifier. It can be named anything relevant.
When an asterisk(*) is passed before the variable name in a Python function, then Python
understands that here the number of arguments is not fixed.
Python will consider any variable name with two asterisks(**) before it as a keyword argument. For
example:
def makeSentence(**words):
sentence=''
for word in words.values():
sentence+=word
return sentence
is and is not are identity operators used to check if two values are located on the same part of the
memory. Two variables that are equal does not imply that they are identical. Example
x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]
print(x1 is not y1) # prints False
print(x2 is y2) # prints True
print(x3 is y3) # prints False
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical.
Same is the case with x2 and y2 (strings). But x3 and y3 are lists. They are equal but not identical. It
is because the interpreter locates them separately in memory although they are equal.
in and not in are the membership operators. They are used to test whether a value or variable is
found in a sequence (string, list, tuple, set and dictionary). In a dictionary we can only test for
presence of key, not the value. Example
x = 'Hello world'
y = {1:'a', 2:'b'}
# check if 'H' is present in x string
print('H' in x) # prints True
# check if 'hello' is present in x string
print('hello' not in x) # prints True
# check if '1' key is present in y
print(1 in y) # prints True
# check if 'a' key is present in y
print('a' in y) # prints False
10. a. Correct the below program so that the output should appear like this.
Solution:
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __str__(self):
return "x-value: " + str(self.x) + " y-value: " + str(self.y)
p1 = Point(3, 4)
p2 = Point(2, 3)
print(p1 + p2)
b. Explain the significant strengths and weaknesses of the python programming language.
Python is one of the most mention-worthy programming languages in today’s world. It ranks among
the fastest-growing programming language in the world. It is versatile, flexible, extremely effective,
easy to use and develop. It has a very active community as well. This means that the best minds in
the field will provide enough support to adopt this new language. It is used in numerous
organizations due to its multiple programming paradigm support and its performance of automatic
memory management.
Significant strengths
1. Easy to use and learn: For beginners, Python is straightforward to use. It is a high-level
programming language, and its syntax is like the English language. These reasons make the
language easy to learn and adapt to. Compared to Java and C, in Python, the same task can be
performed using fewer lines of code. As a result of its easy learning, the principles in Python
can be executed faster compared to other languages.
2. Increased productivity: Python is a very productive language. The simple nature of Python
helps the developers to concentrate on solving the issues in it. To understand the syntax and
behavior of the programming language, the users do not have to spend hours, so more work
is done.
3. Flexibility: This language is very flexible, and hence it allows the user to try new things. The
users can develop new sorts of the application using Python programming language. The
18
language does not restrict the user from trying something different. Other programming
languages do not provide this type of flexibility and freedom, and hence Python is more
preferred in these matters.
4. Extensive library: Python provides the user with a vast library. Python’s standard library is
massive, and just about every function one needs to perform is available in its library. This is
because it has a hugely supportive community and corporate sponsorship. External libraries
are not used by users while working with Python.
5. Supportive community: The Python language was created years ago, and hence it has a
mature community that can support every type of developer, starting from beginners’ level to
expert level. There are enough guides, tutorials, and documentation available on the Python
programming language, which helps the developers to understand the language faster and
better. Because of its supportive community, Python has rapid growth compared to other
languages.
Significant weaknesses
1. Speed: Compared to Java or C, the rate of Python is slower. Python is an interpreted language
that is dynamically typed. For the execution of a code, each line of the code needs to be
explicitly ordered since the language gets interpreted. This is time-consuming, and hence it
slows down the process of execution. The dynamic structure of Python also slows its speed
because while executing the code, the excess work also needs to be completed. Therefore, in
cases where fast acceleration is required, Python is not used there very commonly.
2. Memory consumption: Python has a very high memory consumption. This is because it is
flexible to the data types. It uses large amounts of memory. Python is not a good choice for
tasks where the user wants to optimize memory, i.e., a memory-intensive language.
3. Mobile development: Python is strong in server platforms and desktops, and hence it is a
fantastic server-side programming language. But it is not appropriate for mobile development.
For mobile development, Python is a fragile language. Since it is not memory efficient and has
a prolonged power for processing, due to these reasons, Python does not have many built-in
mobile applications. Carbonnelle is a built-in application present in Python.
4. Database access: Python provides easy programming. However, when it interacts with the
database, some issues arise. Compared to technologies like JDBC and ODBC, which are pretty
famous, the database access layer of the Python programming language is primitive and
underdeveloped. Large enterprises that usually need smooth interaction with complex legacy
data do not prefer the usage of Python.
5. Runtime errors: The users of Python mentioned various issues they faced with the language
design. Since the language of Python is dynamically typed, there can be changes in the data
type of a variable at any time. Therefore, it needs to be tested more often, and also, there are
errors in the language displayed during runtime.
6. Simplicity: Python is a straightforward and easy-to-use programming language which is also a
disadvantage of the language. The users of Python get so accustomed to its easy syntax and
extensive library feature that they face issues while learning other programming languages.
19
Some users also feel that the Java codes are unnecessary due to their complexity. Therefore,
Python has a very vulnerable nature, and the users start taking everything lightly.
We have a list : [1,1,2,3,2,2,4,5,6,2,1]. The list has many duplicates which we need to remove and
get back only the distinct elements. The list is given to the set() built-in function. Later the final list
is displayed using the list() built-in function, as shown in the example below. The output that we get
is distinct elements where all the duplicates elements are eliminated.
my_list = [1,1,2,3,2,2,4,5,6,2,1]
my_final_list = set(my_list)
print(list(my_final_list))
Output:
[1, 2, 3, 4, 5, 6]
The method unique() from Numpy module can help us remove duplicate from the list given. To
work with Numpy first import numpy module, you need to follow these steps:
Step 2) Use your list with duplicates inside unique method as shown below. The output is converted
back to a list format using tolist() method.
myFinalList = np.unique(my_list).tolist()
Output:
[1, 2, 3, 4, 5, 6]
d. How will you remove the last object from a list in Python?
The method pop() can be used to remove and return the last value from the list or the given index
value. If the index is not given, then the last element is popped out and removed.
The pop() method is another commonly used list object method. This method removes an item or an
element from the list, and returns it. The difference between this method and the remove() method is
20
that, we should specify the item to be removed in the remove() method. But, when using the pop(),
we specify the index of the item as the argument, and hence, it pops out the item to be returned at
the specified index. Consider the following examples:
L.pop()
print(L)
In this example, we are defining a list called ‘L’. we are using the pop( ) method, without argument,
which remove the last element. As you can see from the output, the pop( ) removes the element, and
returns ['Bran', 11, 22, 33, 'Stark', 22, 33].
21
Reference
1. https://www.geeksforgeeks.org/python-method-overloading/
2. https://www.programiz.com/python-programming/polymorphism
3. https://www.tutorialspoint.com/what-is-encapsulation-in-python
4. https://www.w3schools.com/python/ref_func_slice.asp
5. https://www.pythonpool.com/python-class-vs-module/
22