Objective:
- Functions in Python
Activity 1:
Write a Python program that will ask the user to enter the width and length of a rectangle and then display the rectangle’s area. The program calls the following functions, which have not been written:
- getLength: This function should ask the user to enter the rectangle’s length and then return that value as a float.
- getWidth: This function should ask the user to enter the rectangle’s width and then return that value as a float.
- getArea: This function should accept the rectangle’s length and width as arguments and return the rectangle’s area. The area is calculated by multiplying the length by the width.
- displayData: This function should accept the rectangle’s length, width, and area as arguments and display them in an appropriate message on the screen.
Solution:
def getLength():
return float(input("Enter Length of Rectangle: "))
def getWidth():
return float(input("Enter Width of Rectangle: "))
def getArea(l, w):
return l * w
def displayData(area):
print("Area of Rectangle is:", area)
def main():
length = getLength()
width = getWidth()
area = getArea(length, width)
displayData(area)
main()
Activity 2:
Write a
function called displayShape that
accepts size and shapetype as parameters and displays a square or a triangle of
the required size.
So e.g. if
the function is called with the following parameters:
displayShape(‘S’, 5); a square of
size 5 is displayed as given
1 |
2 |
3 |
4 |
5 |
2 |
4 |
6 |
8 |
10 |
3 |
6 |
9 |
12 |
15 |
4 |
8 |
12 |
16 |
20 |
5 |
10 |
15 |
20 |
25 |
displayShape(‘T’, 6); a triangle
of size 6 is displayed as given
1
1
1
1
2 1
1
3 3 1
1
4 6 4 1
1
5 10
10 5 1
Solution:
def print_square(size):
for i in range(1, size+1):
for j in range(1, size+1):
print(i*j, end="\t")
print()
def print_triangle(size):
for i in range(size):
for _ in range(size - i - 1):
print(end=" ")
coef = 1
for j in range(i+1):
print(coef, end=" ")
if j < i:
coef = coef * (i - j) // (j + 1)
print()
def displayShape(shape_type, size):
if shape_type == 'S':
print_square(size)
elif shape_type == 'T':
print_triangle(size)
else:
print("Invalid shape type.")
def main():
while True:
shape_type = input("Enter 'S' for Square or 'T' for Triangle (or 'Q' to quit): ").upper()
if shape_type == 'Q':
break
size = int(input("Enter size of shape: "))
displayShape(shape_type, size)
main()