Page 294 - CTS - CSA TP - Volume 2
P. 294
COMPUTER SOFTWARE APPLICATION - CITS
TASK 4: Write a program that takes a mathematical expression as input from the user, evaluates it
using the eval function, and prints the result
Code:
# Exercise 4: eval and input
expression = input(“Enter a mathematical expression: “) # Prompt user for expression
result = eval(expression) # Evaluate the expression using eval
print(“Result:”, result) # Print the result
Explanation:
1 expression = input(“Enter a mathematical expression: “): This line prompts the user to enter a mathematical
expression. The entered expression is stored in the variable expression.
2 result = eval(expression): The eval function is then used to evaluate the mathematical expression stored in the
variable expression. eval interprets the expression as a Python expression and returns the result.
3 print(“Result:”, result): Finally, the program prints the result of the evaluated expression.
So, this program demonstrates the use of the eval built-in function to dynamically evaluate a user-input
mathematical expression. Users can input any valid Python expression, and the program will output the result
of the evaluation.
Output :
TASK 5: Write a program that uses the filter function to extract even numbers from a list
Code:
# Exercise 5: filter
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # Example list
print(“Numbers: “,numbers)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) # Use filter to get even numbers
print(“Even numbers:”, even_numbers) # Print the result
Explanation:
1 numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: This line creates a list named numbers containing integer values from
1 to 10.
2 even_numbers = list(filter(lambda x: x % 2 == 0, numbers)): The filter function is used here to filter out even
numbers from the numbers list. The lambda function lambda x: x % 2 == 0 checks if a number is even (x % 2
== 0). The filter function returns an iterator containing only the elements from the numbers list for which the
lambda function returns True. list() is used to convert the iterator to a list.
3 print(“Even numbers:”, even_numbers): Finally, the program prints the list of even numbers extracted using the
filter function.
So, this program demonstrates the use of the filter built-in function to selectively extract elements from a list
based on a specified condition.
279
CITS : IT & ITES - Computer Software Application - Exercise 132