SlideShare a Scribd company logo
FEDERAL TVT INSTITUTE
Department of Information and Communication Technology
COURSE TITLE: - Advanced Web Technology
COURSE Code: - IT 503
TITLE: - Individual Assignment for advanced web Technology
NAME OF STUDENT IDNo
SIMENEH ANMUT TTMR/342/15
Submitted to: Dr.Ravindra Babu.B
Submission Date: Apr10 / 2023
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
name = input("Enter your name")
print('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
hrs=input("Enter Hour:")
rate=input("Eenter Rate per Hour:")
pay=float(hrs)*float(rate)
print("Pay:", pay)
C) What is __init__ in Python?
"__init__" is a reserved method in python classes. It is called as a constructor in object oriented terminology.
This method is called when an object is created from a class and it allows the class to initialize the attributes
of the class.
D) What are local variables and global variables in Python?
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.
A Global variable can be defined using the global Keyword, also we can make changes to the variable in the
local context.
1. A) Write a for loop that prints all elements of a list and their position in the list.
c = [4,7,3,2,5,9]
for i in c:
print("Element: " + str(i) + " Index: "+ str(c.index(i)))
B) Write a program to reverse/inverse key: value like below
dict1 = {'a': 1, 'b': 2}
result: dict1 = {1: 'a', 2: 'b'}
dict1
test_dict = {'gfg': 4, 'is': 2, 'best': 5}
# printing original dictionary
print ("The original dictionary: " + str(test_dict))
res = dict (reversed (list (test_dict. items ())))
# printing result
print ("The reversed order dictionary: " + str(res))
C) What does [: -1] do?
In Python, [: -1] means reversing a string, list, or any iterable with an ordering.
D) How can you generate random numbers in Python?
Python random module provides the randint() method that generates an integer number within a specific range.
Example - 1:
import random
n = random. randint(0,50)
print(n)
2. 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:
score = input("Enter Score: ")
s = float(score)
x = 'Error'
if s >= 0.9:
x = 'A'
elif s >=0.8:
x='B'
elif s >=0.7:
x='C'
elif s >= 0.6:
x='D'
elif s < .6:
x ='F'
else:
x ="Out of Range"
print (x)
B) Write a python function to calculate Greatest Common Divisor (GCD) of the number?
def hcf(a, b):
if b == 0:
return a
else:
return a
return hcf(b, a % b)
a = 60
b = 48
print("The gcd of 60 and 48 is : ", end="")
print(hcf(60, 48))
C) How does break, continue, and pass work?
break, pass, and continue statements are provided in Python to handle instances where you need to escape a loop
fully when an external condition is triggered or when you want to bypass a section of the loop and begin the
next iteration. These statements can also help you gain better control of your loop.
3. A) Below is the program to calculate the area of a box. Check how it is working. Correct the
program (if required).
class Box:
@property
def area(self):
return width * height
def __init__(self, width, height):
self.width = width
self.height = height
area=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.
import math
a=input("enter first coordinate : ")
p1 = a.split(",")
b=input("enter second coordinate : ")
p2 = b.split(",")
distance = math.sqrt( ((int(p1[0])-int(p2[0]))**2)+((int(p1[1])-int(p2[1]))**2) )
Print ("distance between ", a, "and", b, "is", distance)
C) Is multiple inheritances supported in Python?
The answer is yes
Python is one of the few modern programming languages that support multiple inheritances. Multiple
inheritances are the ability to derive a class from multiple base classes at the same time.
4. A) Explain with a suitable example the differences between list, set, tuple and dictionary
data types in python.
List: - List is a non-homogeneous data structure that stores the elements in single row and multiple rows
and columns
List can be represented by [ ]
Example: [1, 2, 3, 4, 5]
Tuple: - is also a non-homogeneous data structure that stores single row and multiple rows and columns
Tuple can be represented by ( )
Example: (1, 2, 3, 4, 5)
Set: - Set data structure is also non-homogeneous data structure but stores in single row
Set can be represented by { }
Example: {1, 2, 3, 4, 5}
Dictionary: - is also a non-homogeneous data structure which stores key value pairs
Dictionary can be represented by { }
Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”}
B) Explain different types of parameter passing techniques that are supported in python
functions.
There are 5 Arguments in Python to Know. These are
1. default arguments
2. keyword arguments
3. positional arguments
4. arbitrary positional arguments
5. arbitrary keyword arguments
Default Arguments in Python
• Default arguments are values that are provided while defining functions.
• The assignment operator = is used to assign a default value to the argument.
• Default arguments become optional during the function calls.
• If we provide a value to the default arguments during function calls, it overrides the default value.
• The function can have any number of default arguments.
• Default arguments should follow non-default arguments.
Keyword Arguments in Python
Functions can also be called using keyword arguments of the form kwarg=value.
During a function call, values passed through arguments don’t need to be in the order of parameters in the
function definition. This can be achieved by keyword arguments. But all the keyword arguments should match
the parameters in the function definition.
def add (a,b=5,c=10):
Return (a+b+c)
Calling the function add by giving keyword arguments
All parameters are given as keyword arguments, so there’s no need to maintain the same order.
Print(add(b=10, c=16, a=20))
#Output: 46
During the function call, only giving a mandatory argument as a keyword argument, Optional default arguments
are skipped.
Print (add(a=10))
#Output:25
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
Default vs Positional vs Keyword Arguments
C) What is the difference between range & xrange?
The range () and xrange() functions are Python built-in functions that are used to iterate over a sequence of
values. Both the range () and xrange () functions are used with the for() loops to iterate over certain number of
times. Both the range () and xrange() functions create a list of the specified range of values. So, if we provide (1,
10) as the parameter to both the functions then it will create a list in the memory having 9 elements (1 to 10
excluding the 10th number).
The range () and xrange() functions are used in Python3 and Python2 respectively. As we know Python3 does
not support backward compatibility, so the xrange() function (which was used in Python2) cannot be used in
Python3 but the range() function can be used with Python2. Now, if we want our code to work on both the
Python2 and Python3 interpreters then we should use the range () function.
Now, the difference between range and xrange in Python lies in their working speed and return values. The
range () function is comparatively faster than the range () function. The range () function supports list slicing on
the other hand, the xrange() function does not support list slicing. The range () function return a range a of
iterable type objects on the other hand the xrange() function return the generator object.
Range () Function
The range () function is a Python built-in function that is used to iterate over a sequence of values. Whenever
the range () function is invoked, a sequence of numbers is created by the function and returned. The range ()
function helps us to iterate over a specific block of code certain number of times. The returned sequence of
numbers starts with 0. By default the, numbers increments by 1 and the sequence ends before the specified
number.
Note: range () is a data type in Python programming language. We can verify the same by using type () method.
Syntax of range () Function
Range (start, stop, steps)
Parameters of the range () Function
The range () function takes three parameters in which two of them are optional and one is required. Let us
briefly discuss the parameters of the range () function:
• Start: It is an optional parameter. The start denotes the integer from where the iteration should start.
• End: It is a required parameter. The end denotes the integer where the iteration should stop. We should
remember that the end integer is not included.
• Steps: It is an optional parameter that denotes the number of increment(s) to be made in each iteration.
By default, the steps value is set to 1.
xrange() Function
The xrange() function is a Python built-in function that is used to iterate over a sequence of values. It was used
in Python2. Whenever the xrange() function is invoked, the generator object is created by the function and
returned. Now, this generated object can be further used to display the values using iteration. The xrange()
function helps us to iterate over a specific block of code certain number of times. The iteration starts at 0. By
default, the numbers increments by 1; and the sequence end before the specified number.
The xrange() function also only works with integers. So, all the parameters of the xrange() function accept
integers but all the three parameters of the xrange() function can be negative as well. The negative steps denote
the reverse order of iteration.
Syntax of xrange() Function
Xrange (start, stop, steps)
Parameters of the range () Function
The range () function takes three parameters in which two of them are optional and one is required. Let us
briefly discuss the parameters of the range () function:
• Start: It is an optional parameter. The start denotes the integer from where the iteration should start.
• End: It is a required parameter. The end denotes the integer where the iteration should stop. We should
remember that the end integer is not included.
• Steps: It is an optional parameter that denotes the number of increment(s) to be made in each iteration.
By default, the step's value is set to 1.
The xrange() function in Python is the ancestor of the range() function. It returns a generator object of the
xrange type. The generator object can be easily converted into any sequential data type like tuples, lists, sets,
etc.
The xrange() function has a major advantage over the range() function as the xrange() function is more memory
optimized.
5. a. Correct the below code so that it checks whether the database exists or not
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:
db_is_new = False
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")
col_names = [col[0] for col in cur.description]
print(col_names)
c. Write a program in Python to produce Star triangle?
Output:
*
***
*****
*******
*********
***********
*************
***************
*****************
def triangle(m):
k = m - 1
for i in range(0, m):
for j in range(0, k):
print(end=" ")
k -= 1
for j in range(0, i + 1):
print("* ", end='')
print("n")
m = int(input())
triangle(m)
6. A) Correct the below code, and it should update the values.
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("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.description]
rows = cur.fetchall()
print("%-10s %-10s %-10s" % (col_names[0], col_names[1], col_names[2]))
for row in rows:
print("%-10s %-10s %-10s" % row)
C. Write a Python program to calculate the sum of a list of numbers?
list1 = [29, 8, 3, 18, 12]
# creating sum_list function
from operator import*
list1 = [16, 30, 9, 2]
result = 0
for i in list1:
result = add(i, result)
# printing the result
print(result)
7. A) What is Polymorphism in Python?
The literal meaning of polymorphism is the condition of occurrence in different forms.
Polymorphism is a very important concept in programming. It refers to the use of a single type entity (method,
operator or object) to represent different types in different scenarios.
Example 1: Polymorphism in addition operator
num1 = 1
num2 = 2
print(num1+num2)
Function Polymorphism in Python
There are some functions in Python which are compatible to run with multiple data types.
One such 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.
Example 2: Polymorphic len() function
print(len("simeneh Anmut"))
print(len(["Python", "oracle", "C++"]))
print(len({"Name": "yonas", "Address": "Hawassa"}))
B. Define encapsulation in Python?
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.
Implement Encapsulation with a Class in Python
Another example of Encapsulation can be a class because a class combines data and methods into a single unit.
Here, the custom function demofunc() displays the records of students wherein we can access public data
member. Using the objects st1, st2, st3, st4, we have access ed the public methods of the class demofunc()
Example
class Teachers:
def __init__(self, name, Bank, points):
self.name = name
self.Bank = Bank
self.points = points
# custom function
def demofunc(self):
print("I am "+self.name)
print("I got Bank ",+self.Bank)
# create 4 objects
st1 = Teachers("Simeneh", 1, 100)
st2 = Teachers("Alem", 2, 90)
st3 = Teachers("abebe", 3, 76)
st4 = Teachers("Robel", 4, 60)
# call the functions using the objects created above
st1.demofunc()
st2.demofunc()
st3.demofunc()
st4.demofunc()
C. What is the lambda function in Python?
Lambda is a keyword in Python for defining the anonymous function. Argument is a placeholder that is a
variable that will be used to hold the value you want to pass into the function expression. A lambda function can
have multiple variables depending on what you want to achieve. 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.
We can define a lambda function like this:
Lambda argument(s): expression
1. Lambda is a keyword in Python for defining the anonymous function.
2. Argument(s) is a placeholder that is a variable that will be used to hold the value you want to pass into
the function expression. A lambda function can have multiple variables depending on what you want to
achieve.
3. Expression is the code you want to execute in the lambda function.
D. What is slicing in Python?
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.
Syntax
Slice (start, end, steps)
E. A) Write a recursive function to compute x raised to the power of n.
# Recursive function to find N^P.
def power(N, P):
if P == 0:
return 1
# Recurrence relation
return (N*power(N, P-1))
if __name__ == '__main__':
N = 9
P = 3
print(power(N, P))
Question 9
a. Write a recursive function to compute x raised to the power of n
def power(x, n):
if n == 0:
return 1
elif n % 2 == 0:
return power(x*x, n/2)
else:
return x * power(x*x, (n-1)/2)
# Test the power() function with some inputs
result = power(2, 3)
print(result)
b. Explain the differences between function, class, module, and package in python
A function is a block of reusable code that performs a specific task. Functions can take input arguments, process
them, and return output values. Functions are defined using the def keyword and can be called from other parts
of the code.
A class in Python is a blueprint for creating objects that share similar attributes and behaviors. A class contains
methods (functions) and properties (attributes) that define the behavior and state of its instances. Classes are
defined using the class keyword and can be instantiated to create objects.
A module in Python is simply a file that contains Python code, typically containing functions, classes, and
variables that can be imported and used from other modules or scripts. Modules allow you to reuse code across
multiple projects and keep your code organized.
A package in Python is a collection of modules that are grouped together in a directory hierarchy. Packages
provide an additional level of organization over modules, allowing you to break up your code into logical units
and avoid naming conflicts between different modules.
What does *args and **kwargs mean?
*args and **kwargs are special syntax used in function definitions to pass a variable number of arguments to a
function.
The *args syntax is used to pass a variable number of positional arguments to a function. It allows you to pass
any number of arguments to a function, which are then collected into a tuple.
The **kwargs syntax is used to pass a variable number of keyword arguments to a function. It allows you to
pass any number of keyword arguments to a function, which are then collected into a dictionary.
What is the purpose of is, not and in operators?
In Python, is, not, and in are operators that allow you to perform certain tests on variables or values.
The is operator is used to test whether two variables reference the same object in memory. It returns True if both
variables refer to the same object, and False otherwise. For example:
a = [1, 2, 3]
b = a
c = [1, 2, 3]
print(a is b)
print(a is c)
The not operator is used to negate a boolean expression. It returns True if the expression is false, and False if the
expression is true. For example:
a = 6
if not b == 10:
print("b is not equal to 10")
The in operator is used to test whether a value is contained within a sequence (like a string, list, or tuple). It
returns True if the value is found in the sequence, and False otherwise. For example:
my_list = [1, 2, 3, 4, 5]
if 5 in my_list:
print("5 is in the list")
Question 10
a. Correct the below program so that the output should appear like this.
class Point:
def __str__(self):
return "x-value: " + str(self.x) + " y-value: " + str(self.y)
def __add__(self, other):
# Create a new Point object with the sum of x and y values
p = Point()
p.x = self.x + other.x
p.y = self.y + other.y
return p
p1 = Point(3, 4)
p2 = Point(2, 3)
result = p1 + p2
print(result)
b. Explain the significant strengths and weaknesses of the python programming language.
Python is a popular high-level programming language that is known for its simplicity, readability, and ease of
use. It has several strengths as well as weaknesses, which are discussed below:
Strengths:
Simple and easy to learn: Python has a clear and concise syntax that makes it easy to read and write code. This
makes it an ideal choice for beginners who want to learn programming.
Large standard library: Python comes with a large standard library that provides support for many common
programming tasks such as working with databases, networking, and data analysis. This saves developers a lot
of time and effort when writing code.
Cross-platform compatibility: Python is supported on many platforms, including Windows, Linux, and
macOS. This makes it an ideal choice for developing cross-platform applications.
Strong community support: Python has a large and active community of developers who contribute to the
language by creating libraries, frameworks, and tools. This ensures that there is always a wealth of resources
available to help developers solve problems.
Interpreted language: Python is an interpreted language, which means that code can be executed immediately
without the need for compilation. This makes it easy to prototype and test code quickly.
Weaknesses:
Slow execution speed: Python is an interpreted language, which means that it can be slower than compiled
languages like C or Java. This makes it less suitable for performance-critical applications.
Global Interpreter Lock (GIL): The GIL is a mechanism in Python that prevents multiple threads from
executing Python bytecodes in parallel. This can limit the performance of multithreaded programs.
Weak type checking: Python is a dynamically-typed language, which means that variables are not required to
have explicit types. This can lead to errors at runtime if variables are not used correctly.
Not ideal for mobile development: Python is not a popular choice for mobile app development, since it does
not have native support for building mobile apps on iOS or Android.
Limited scalability: Python may not be the best choice for building large-scale applications because of its slow
execution speed and weak type checking.
Overall, Python is a versatile language that is great for prototyping, rapid application development, and scripting
tasks. However, its limitations in terms of performance and scalability mean that it may not be the best choice
for certain types of projects.
c. How will you remove duplicate elements from a list?
To remove duplicate elements from a list in Python, you can use several approaches. Here are some ways to
achieve this:
Using set() function: You can convert the list into a set to automatically remove duplicates, and then convert it
back to a list. However, this method does not preserve the original order of the list.
my_list = [1, 2, 3, 2, 1, 4, 5, 4]
new_list = list(set(my_list))
print(new_list) # Output: [1, 2, 3, 4, 5]
d. Using a loop and a new list: You can loop through the original list and add each element to a new list only if
it has not been added before. This method preserves the original order of the list.
my_list = [1, 2, 3, 2, 1, 4, 5, 4]
new_list = []
for item in my_list:
if item not in new_list:
new_list.append(item)
print(new_list) # Output: [1, 2, 3, 4, 5]
e. How will you remove the last object from a list in Python?
In Python, you can remove the last object from a list using the pop() method. The pop() method removes and
returns the last element in the list by default.
Here's an example:
my_list = [1, 2, 3, 4, 5]
last_element = my_list.pop()
print(last_element)
print(my_list)

More Related Content

DOCX
Functions.docx
PPTX
Python programming workshop
PDF
Functions_19_20.pdf
PPTX
Python Lecture 4
PPTX
Python_Functions_Unit1.pptx
PPTX
Unit2 input output
DOCX
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
Functions.docx
Python programming workshop
Functions_19_20.pdf
Python Lecture 4
Python_Functions_Unit1.pptx
Unit2 input output
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx

Similar to Advanced Web Technology ass.pdf (20)

PPTX
Functions
PPTX
functioninpython-1.pptx
PDF
Functionscs12 ppt.pdf
PDF
Functions.pdf
PPTX
MODULE. .pptx
PPT
Beginning with C++.ppt thus us beginnunv w
PDF
introduction to python programming course 2
PPTX
Chapter1 python introduction syntax general
PPTX
Lecture 08.pptx
PPTX
Function in c program
PDF
Functions_21_22.pdf
PDF
Python Manuel-R2021.pdf
PPTX
Fundamentals of functions in C program.pptx
PPTX
The Input Statement in Core Python .pptx
DOCX
PPTX
Input statement- output statement concept.pptx
PPT
An Overview Of Python With Functional Programming
PPTX
Computer programming 2 Lesson 10
PPTX
CHAPTER 01 FUNCTION in python class 12th.pptx
PDF
functions- best.pdf
Functions
functioninpython-1.pptx
Functionscs12 ppt.pdf
Functions.pdf
MODULE. .pptx
Beginning with C++.ppt thus us beginnunv w
introduction to python programming course 2
Chapter1 python introduction syntax general
Lecture 08.pptx
Function in c program
Functions_21_22.pdf
Python Manuel-R2021.pdf
Fundamentals of functions in C program.pptx
The Input Statement in Core Python .pptx
Input statement- output statement concept.pptx
An Overview Of Python With Functional Programming
Computer programming 2 Lesson 10
CHAPTER 01 FUNCTION in python class 12th.pptx
functions- best.pdf
Ad

Recently uploaded (20)

PPTX
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
PPT
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
PDF
Fluorescence-microscope_Botany_detailed content
PDF
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
PPT
Quality review (1)_presentation of this 21
PPTX
advance b rammar.pptxfdgdfgdfsgdfgsdgfdfgdfgsdfgdfgdfg
PDF
Mega Projects Data Mega Projects Data
PDF
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
PDF
Recruitment and Placement PPT.pdfbjfibjdfbjfobj
PPTX
Business Acumen Training GuidePresentation.pptx
PDF
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
PPTX
Introduction-to-Cloud-ComputingFinal.pptx
PPT
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
PPTX
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
PDF
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
PPTX
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
PPTX
IB Computer Science - Internal Assessment.pptx
PPTX
Major-Components-ofNKJNNKNKNKNKronment.pptx
PPTX
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
CEE 2 REPORT G7.pptxbdbshjdgsgjgsjfiuhsd
Chapter 3 METAL JOINING.pptnnnnnnnnnnnnn
Fluorescence-microscope_Botany_detailed content
22.Patil - Early prediction of Alzheimer’s disease using convolutional neural...
Quality review (1)_presentation of this 21
advance b rammar.pptxfdgdfgdfsgdfgsdgfdfgdfgsdfgdfgdfg
Mega Projects Data Mega Projects Data
168300704-gasification-ppt.pdfhghhhsjsjhsuxush
Recruitment and Placement PPT.pdfbjfibjdfbjfobj
Business Acumen Training GuidePresentation.pptx
TRAFFIC-MANAGEMENT-AND-ACCIDENT-INVESTIGATION-WITH-DRIVING-PDF-FILE.pdf
Introduction-to-Cloud-ComputingFinal.pptx
Chapter 2 METAL FORMINGhhhhhhhjjjjmmmmmmmmm
iec ppt-1 pptx icmr ppt on rehabilitation.pptx
“Getting Started with Data Analytics Using R – Concepts, Tools & Case Studies”
ALIMENTARY AND BILIARY CONDITIONS 3-1.pptx
IB Computer Science - Internal Assessment.pptx
Major-Components-ofNKJNNKNKNKNKronment.pptx
mbdjdhjjodule 5-1 rhfhhfjtjjhafbrhfnfbbfnb
Ad

Advanced Web Technology ass.pdf

  • 1. FEDERAL TVT INSTITUTE Department of Information and Communication Technology COURSE TITLE: - Advanced Web Technology COURSE Code: - IT 503 TITLE: - Individual Assignment for advanced web Technology NAME OF STUDENT IDNo SIMENEH ANMUT TTMR/342/15 Submitted to: Dr.Ravindra Babu.B Submission Date: Apr10 / 2023
  • 2. 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 name = input("Enter your name") print('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 hrs=input("Enter Hour:") rate=input("Eenter Rate per Hour:") pay=float(hrs)*float(rate) print("Pay:", pay) C) What is __init__ in Python? "__init__" is a reserved method in python classes. It is called as a constructor in object oriented terminology. This method is called when an object is created from a class and it allows the class to initialize the attributes of the class. D) What are local variables and global variables in Python? 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. A Global variable can be defined using the global Keyword, also we can make changes to the variable in the local context. 1. A) Write a for loop that prints all elements of a list and their position in the list. c = [4,7,3,2,5,9] for i in c: print("Element: " + str(i) + " Index: "+ str(c.index(i))) B) Write a program to reverse/inverse key: value like below dict1 = {'a': 1, 'b': 2} result: dict1 = {1: 'a', 2: 'b'} dict1 test_dict = {'gfg': 4, 'is': 2, 'best': 5} # printing original dictionary print ("The original dictionary: " + str(test_dict)) res = dict (reversed (list (test_dict. items ()))) # printing result print ("The reversed order dictionary: " + str(res)) C) What does [: -1] do? In Python, [: -1] means reversing a string, list, or any iterable with an ordering.
  • 3. D) How can you generate random numbers in Python? Python random module provides the randint() method that generates an integer number within a specific range. Example - 1: import random n = random. randint(0,50) print(n) 2. 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: score = input("Enter Score: ") s = float(score) x = 'Error' if s >= 0.9: x = 'A' elif s >=0.8: x='B' elif s >=0.7: x='C' elif s >= 0.6: x='D' elif s < .6: x ='F' else: x ="Out of Range" print (x) B) Write a python function to calculate Greatest Common Divisor (GCD) of the number? def hcf(a, b): if b == 0: return a else: return a return hcf(b, a % b) a = 60 b = 48 print("The gcd of 60 and 48 is : ", end="") print(hcf(60, 48)) C) How does break, continue, and pass work? break, pass, and continue statements are provided in Python to handle instances where you need to escape a loop fully when an external condition is triggered or when you want to bypass a section of the loop and begin the next iteration. These statements can also help you gain better control of your loop.
  • 4. 3. A) Below is the program to calculate the area of a box. Check how it is working. Correct the program (if required). class Box: @property def area(self): return width * height def __init__(self, width, height): self.width = width self.height = height area=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. import math a=input("enter first coordinate : ") p1 = a.split(",") b=input("enter second coordinate : ") p2 = b.split(",") distance = math.sqrt( ((int(p1[0])-int(p2[0]))**2)+((int(p1[1])-int(p2[1]))**2) ) Print ("distance between ", a, "and", b, "is", distance) C) Is multiple inheritances supported in Python? The answer is yes Python is one of the few modern programming languages that support multiple inheritances. Multiple inheritances are the ability to derive a class from multiple base classes at the same time. 4. A) Explain with a suitable example the differences between list, set, tuple and dictionary data types in python. List: - List is a non-homogeneous data structure that stores the elements in single row and multiple rows and columns List can be represented by [ ] Example: [1, 2, 3, 4, 5] Tuple: - is also a non-homogeneous data structure that stores single row and multiple rows and columns Tuple can be represented by ( ) Example: (1, 2, 3, 4, 5) Set: - Set data structure is also non-homogeneous data structure but stores in single row Set can be represented by { } Example: {1, 2, 3, 4, 5}
  • 5. Dictionary: - is also a non-homogeneous data structure which stores key value pairs Dictionary can be represented by { } Example: {1: “a”, 2: “b”, 3: “c”, 4: “d”, 5: “e”} B) Explain different types of parameter passing techniques that are supported in python functions. There are 5 Arguments in Python to Know. These are 1. default arguments 2. keyword arguments 3. positional arguments 4. arbitrary positional arguments 5. arbitrary keyword arguments Default Arguments in Python • Default arguments are values that are provided while defining functions. • The assignment operator = is used to assign a default value to the argument. • Default arguments become optional during the function calls. • If we provide a value to the default arguments during function calls, it overrides the default value. • The function can have any number of default arguments. • Default arguments should follow non-default arguments. Keyword Arguments in Python Functions can also be called using keyword arguments of the form kwarg=value. During a function call, values passed through arguments don’t need to be in the order of parameters in the function definition. This can be achieved by keyword arguments. But all the keyword arguments should match the parameters in the function definition. def add (a,b=5,c=10): Return (a+b+c) Calling the function add by giving keyword arguments
  • 6. All parameters are given as keyword arguments, so there’s no need to maintain the same order. Print(add(b=10, c=16, a=20)) #Output: 46 During the function call, only giving a mandatory argument as a keyword argument, Optional default arguments are skipped. Print (add(a=10)) #Output:25 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
  • 7. Default vs Positional vs Keyword Arguments C) What is the difference between range & xrange? The range () and xrange() functions are Python built-in functions that are used to iterate over a sequence of values. Both the range () and xrange () functions are used with the for() loops to iterate over certain number of times. Both the range () and xrange() functions create a list of the specified range of values. So, if we provide (1, 10) as the parameter to both the functions then it will create a list in the memory having 9 elements (1 to 10 excluding the 10th number). The range () and xrange() functions are used in Python3 and Python2 respectively. As we know Python3 does not support backward compatibility, so the xrange() function (which was used in Python2) cannot be used in Python3 but the range() function can be used with Python2. Now, if we want our code to work on both the Python2 and Python3 interpreters then we should use the range () function. Now, the difference between range and xrange in Python lies in their working speed and return values. The range () function is comparatively faster than the range () function. The range () function supports list slicing on the other hand, the xrange() function does not support list slicing. The range () function return a range a of iterable type objects on the other hand the xrange() function return the generator object. Range () Function The range () function is a Python built-in function that is used to iterate over a sequence of values. Whenever the range () function is invoked, a sequence of numbers is created by the function and returned. The range () function helps us to iterate over a specific block of code certain number of times. The returned sequence of numbers starts with 0. By default the, numbers increments by 1 and the sequence ends before the specified number. Note: range () is a data type in Python programming language. We can verify the same by using type () method.
  • 8. Syntax of range () Function Range (start, stop, steps) Parameters of the range () Function The range () function takes three parameters in which two of them are optional and one is required. Let us briefly discuss the parameters of the range () function: • Start: It is an optional parameter. The start denotes the integer from where the iteration should start. • End: It is a required parameter. The end denotes the integer where the iteration should stop. We should remember that the end integer is not included. • Steps: It is an optional parameter that denotes the number of increment(s) to be made in each iteration. By default, the steps value is set to 1. xrange() Function The xrange() function is a Python built-in function that is used to iterate over a sequence of values. It was used in Python2. Whenever the xrange() function is invoked, the generator object is created by the function and returned. Now, this generated object can be further used to display the values using iteration. The xrange() function helps us to iterate over a specific block of code certain number of times. The iteration starts at 0. By default, the numbers increments by 1; and the sequence end before the specified number. The xrange() function also only works with integers. So, all the parameters of the xrange() function accept integers but all the three parameters of the xrange() function can be negative as well. The negative steps denote the reverse order of iteration. Syntax of xrange() Function Xrange (start, stop, steps) Parameters of the range () Function The range () function takes three parameters in which two of them are optional and one is required. Let us briefly discuss the parameters of the range () function: • Start: It is an optional parameter. The start denotes the integer from where the iteration should start. • End: It is a required parameter. The end denotes the integer where the iteration should stop. We should remember that the end integer is not included.
  • 9. • Steps: It is an optional parameter that denotes the number of increment(s) to be made in each iteration. By default, the step's value is set to 1. The xrange() function in Python is the ancestor of the range() function. It returns a generator object of the xrange type. The generator object can be easily converted into any sequential data type like tuples, lists, sets, etc. The xrange() function has a major advantage over the range() function as the xrange() function is more memory optimized. 5. a. Correct the below code so that it checks whether the database exists or not 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: db_is_new = False 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") col_names = [col[0] for col in cur.description] print(col_names) c. Write a program in Python to produce Star triangle? Output: * *** ***** ******* ********* ***********
  • 10. ************* *************** ***************** def triangle(m): k = m - 1 for i in range(0, m): for j in range(0, k): print(end=" ") k -= 1 for j in range(0, i + 1): print("* ", end='') print("n") m = int(input()) triangle(m) 6. A) Correct the below code, and it should update the values. 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("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.description] rows = cur.fetchall() print("%-10s %-10s %-10s" % (col_names[0], col_names[1], col_names[2])) for row in rows: print("%-10s %-10s %-10s" % row) C. Write a Python program to calculate the sum of a list of numbers? list1 = [29, 8, 3, 18, 12] # creating sum_list function from operator import* list1 = [16, 30, 9, 2] result = 0 for i in list1: result = add(i, result) # printing the result print(result)
  • 11. 7. A) What is Polymorphism in Python? The literal meaning of polymorphism is the condition of occurrence in different forms. Polymorphism is a very important concept in programming. It refers to the use of a single type entity (method, operator or object) to represent different types in different scenarios. Example 1: Polymorphism in addition operator num1 = 1 num2 = 2 print(num1+num2) Function Polymorphism in Python There are some functions in Python which are compatible to run with multiple data types. One such 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. Example 2: Polymorphic len() function print(len("simeneh Anmut")) print(len(["Python", "oracle", "C++"])) print(len({"Name": "yonas", "Address": "Hawassa"})) B. Define encapsulation in Python? 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.
  • 12. Implement Encapsulation with a Class in Python Another example of Encapsulation can be a class because a class combines data and methods into a single unit. Here, the custom function demofunc() displays the records of students wherein we can access public data member. Using the objects st1, st2, st3, st4, we have access ed the public methods of the class demofunc() Example class Teachers: def __init__(self, name, Bank, points): self.name = name self.Bank = Bank self.points = points # custom function def demofunc(self): print("I am "+self.name) print("I got Bank ",+self.Bank) # create 4 objects st1 = Teachers("Simeneh", 1, 100) st2 = Teachers("Alem", 2, 90) st3 = Teachers("abebe", 3, 76) st4 = Teachers("Robel", 4, 60) # call the functions using the objects created above st1.demofunc() st2.demofunc() st3.demofunc() st4.demofunc() C. What is the lambda function in Python? Lambda is a keyword in Python for defining the anonymous function. Argument is a placeholder that is a variable that will be used to hold the value you want to pass into the function expression. A lambda function can have multiple variables depending on what you want to achieve. 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.
  • 13. We can define a lambda function like this: Lambda argument(s): expression 1. Lambda is a keyword in Python for defining the anonymous function. 2. Argument(s) is a placeholder that is a variable that will be used to hold the value you want to pass into the function expression. A lambda function can have multiple variables depending on what you want to achieve. 3. Expression is the code you want to execute in the lambda function. D. What is slicing in Python? 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. Syntax Slice (start, end, steps) E. A) Write a recursive function to compute x raised to the power of n. # Recursive function to find N^P. def power(N, P): if P == 0: return 1 # Recurrence relation return (N*power(N, P-1)) if __name__ == '__main__': N = 9 P = 3 print(power(N, P)) Question 9 a. Write a recursive function to compute x raised to the power of n def power(x, n): if n == 0: return 1 elif n % 2 == 0: return power(x*x, n/2) else: return x * power(x*x, (n-1)/2) # Test the power() function with some inputs result = power(2, 3) print(result) b. Explain the differences between function, class, module, and package in python
  • 14. A function is a block of reusable code that performs a specific task. Functions can take input arguments, process them, and return output values. Functions are defined using the def keyword and can be called from other parts of the code. A class in Python is a blueprint for creating objects that share similar attributes and behaviors. A class contains methods (functions) and properties (attributes) that define the behavior and state of its instances. Classes are defined using the class keyword and can be instantiated to create objects. A module in Python is simply a file that contains Python code, typically containing functions, classes, and variables that can be imported and used from other modules or scripts. Modules allow you to reuse code across multiple projects and keep your code organized. A package in Python is a collection of modules that are grouped together in a directory hierarchy. Packages provide an additional level of organization over modules, allowing you to break up your code into logical units and avoid naming conflicts between different modules. What does *args and **kwargs mean? *args and **kwargs are special syntax used in function definitions to pass a variable number of arguments to a function. The *args syntax is used to pass a variable number of positional arguments to a function. It allows you to pass any number of arguments to a function, which are then collected into a tuple. The **kwargs syntax is used to pass a variable number of keyword arguments to a function. It allows you to pass any number of keyword arguments to a function, which are then collected into a dictionary. What is the purpose of is, not and in operators? In Python, is, not, and in are operators that allow you to perform certain tests on variables or values. The is operator is used to test whether two variables reference the same object in memory. It returns True if both variables refer to the same object, and False otherwise. For example: a = [1, 2, 3] b = a c = [1, 2, 3] print(a is b) print(a is c) The not operator is used to negate a boolean expression. It returns True if the expression is false, and False if the expression is true. For example:
  • 15. a = 6 if not b == 10: print("b is not equal to 10") The in operator is used to test whether a value is contained within a sequence (like a string, list, or tuple). It returns True if the value is found in the sequence, and False otherwise. For example: my_list = [1, 2, 3, 4, 5] if 5 in my_list: print("5 is in the list") Question 10 a. Correct the below program so that the output should appear like this. class Point: def __str__(self): return "x-value: " + str(self.x) + " y-value: " + str(self.y) def __add__(self, other): # Create a new Point object with the sum of x and y values p = Point() p.x = self.x + other.x p.y = self.y + other.y return p p1 = Point(3, 4) p2 = Point(2, 3) result = p1 + p2 print(result) b. Explain the significant strengths and weaknesses of the python programming language. Python is a popular high-level programming language that is known for its simplicity, readability, and ease of use. It has several strengths as well as weaknesses, which are discussed below: Strengths: Simple and easy to learn: Python has a clear and concise syntax that makes it easy to read and write code. This makes it an ideal choice for beginners who want to learn programming. Large standard library: Python comes with a large standard library that provides support for many common programming tasks such as working with databases, networking, and data analysis. This saves developers a lot of time and effort when writing code. Cross-platform compatibility: Python is supported on many platforms, including Windows, Linux, and macOS. This makes it an ideal choice for developing cross-platform applications. Strong community support: Python has a large and active community of developers who contribute to the language by creating libraries, frameworks, and tools. This ensures that there is always a wealth of resources available to help developers solve problems. Interpreted language: Python is an interpreted language, which means that code can be executed immediately without the need for compilation. This makes it easy to prototype and test code quickly.
  • 16. Weaknesses: Slow execution speed: Python is an interpreted language, which means that it can be slower than compiled languages like C or Java. This makes it less suitable for performance-critical applications. Global Interpreter Lock (GIL): The GIL is a mechanism in Python that prevents multiple threads from executing Python bytecodes in parallel. This can limit the performance of multithreaded programs. Weak type checking: Python is a dynamically-typed language, which means that variables are not required to have explicit types. This can lead to errors at runtime if variables are not used correctly. Not ideal for mobile development: Python is not a popular choice for mobile app development, since it does not have native support for building mobile apps on iOS or Android. Limited scalability: Python may not be the best choice for building large-scale applications because of its slow execution speed and weak type checking. Overall, Python is a versatile language that is great for prototyping, rapid application development, and scripting tasks. However, its limitations in terms of performance and scalability mean that it may not be the best choice for certain types of projects. c. How will you remove duplicate elements from a list? To remove duplicate elements from a list in Python, you can use several approaches. Here are some ways to achieve this: Using set() function: You can convert the list into a set to automatically remove duplicates, and then convert it back to a list. However, this method does not preserve the original order of the list. my_list = [1, 2, 3, 2, 1, 4, 5, 4] new_list = list(set(my_list)) print(new_list) # Output: [1, 2, 3, 4, 5] d. Using a loop and a new list: You can loop through the original list and add each element to a new list only if it has not been added before. This method preserves the original order of the list. my_list = [1, 2, 3, 2, 1, 4, 5, 4] new_list = [] for item in my_list: if item not in new_list: new_list.append(item) print(new_list) # Output: [1, 2, 3, 4, 5] e. How will you remove the last object from a list in Python? In Python, you can remove the last object from a list using the pop() method. The pop() method removes and returns the last element in the list by default.
  • 17. Here's an example: my_list = [1, 2, 3, 4, 5] last_element = my_list.pop() print(last_element) print(my_list)