Chandigarh University
ADD-ON PYTHON
PROGRAMMING
MAY 21, 2024
Firoz Khan | BCA
Bachelors in Computer Application
Question 1 : Write a Python program that will accept the base and height of a triangle and
compute the area.
Answer 1:
Python program to calculate the area of a triangle based on the given base and height:
def triangle_area(base, height):
"""
Calculate the area of a triangle given its base and height.
Args:
- base (float): The base length of the triangle.
- height (float): The height of the triangle.
Returns:
- float: The area of the triangle.
"""
area = 0.5 * base * height
return area
def main():
# Get user input for base and height
base = float(input("Enter the base length of the triangle: "))
height = float(input("Enter the height of the triangle: "))
# Calculate the area
area = triangle_area(base, height)
# Print the result
print("The area of the triangle with base", base, "and height", height, "is:", area)
if __name__ == "__main__":
main()
Question 2: Write a Python program to sum of two given integers. However, if the sum is between
15 to 20 it will return 20.
Answer 2:
Below is a Python program that takes two integers as input, sums them, and returns 20 if the sum falls between 15
and 20 (inclusive), otherwise it returns the actual sum:
def sum_or_twenty(num1, num2):
"""
Calculate the sum of two given integers. If the sum is between 15 and 20, return 20.
Args:
- num1 (int): First integer.
- num2 (int): Second integer.
Returns:
- int: Sum of the two integers, or 20 if the sum is between 15 and 20.
"""
sum_result = num1 + num2
if 15 <= sum_result <= 20:
return 20
else:
return sum_result
def main():
# Get user input for two integers
num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
# Calculate the sum or return 20 if it's between 15 and 20
result = sum_or_twenty(num1, num2)
# Print the result
print("The sum is:", result)
if __name__ == "__main__":
main()
Run this program by saving it in a Python file (e.g., ‘sum_or_twenty .py’) and executing it. It will ask you to input two
integers, and then it will print the sum or 20 if the sum is between 15 and 20.
Question 3: Write a Python program to calculate the length of a string
Answer 3:
Simple Python program that calculates the length of a string:
def calculate_string_length(string):
"""
Calculate the length of a given string.
Args:
- string (str): The input string.
Returns:
- int: The length of the string.
"""
length = len(string)
return length
def main():
# Get user input for a string
input_string = input("Enter a string: ")
# Calculate the length of the string
length = calculate_string_length(input_string)
# Print the result
print("The length of the string is:", length)
if __name__ == "__main__":
main()
Python file (e.g., calculate_string_length .py) and run it. It will prompt you to enter a string, and then it will calculate
and display the length of the string.