Page 293 - CTS - CSA TP - Volume 2
P. 293
COMPUTER SOFTWARE APPLICATION - CITS
TASK 2: Write a program that takes a Python code snippet as input, compiles it using the compile
function, and executes it using exec
Code:
# Exercise 2: compile and exec
code = input(“Enter Python code snippet: “) # Prompt user for Python code
compiled_code = compile(code, ‘<string>’, ‘exec’) # Compile the code
exec(compiled_code) # Execute the compiled code
Explanation:
1 code = input(“Enter Python code snippet: “): This line prompts the user to enter a Python code snippet, and the
input is stored in the variable code.
2 compiled_code = compile(code, ‘<string>’, ‘exec’): The compile function is used to compile the entered code.
The first argument is the code itself, the second argument (‘<string>’) is a filename to represent the code (it
can be any string), and the third argument (‘exec’) specifies the compilation mode, which means the code will
be executed as a series of statements.
3 exec(compiled_code): The exec function is then used to execute the compiled code. This function is used to
dynamically execute Python code. The compiled code is passed as an argument to exec, and it is executed in
the current global and local scopes.
Output:
TASK 3: Write a program that uses the dir function to list all the attributes of a given object
# Exercise 3: dir
obj = [1, 2, 3] # Example object (list)
attributes = dir(obj) # Use dir to get attributes of the object
print(“Object attributes:”, attributes) # Print the result
Explanation:
1 obj = [1, 2, 3]: This line creates an example object, in this case, a list [1, 2, 3].
2 attributes = dir(obj): The dir function is then used to get the attributes of the object obj. The dir function returns
a list of names in the namespace of the object. In this case, it will return a list of attributes and methods
available for the list object.
3 print(“Object attributes:”, attributes): Finally, the program prints the obtained attributes of the object. This helps
in exploring the available attributes and methods for a given object.
Output:
278
CITS : IT & ITES - Computer Software Application - Exercise 132