Functions and Data Structures

359 viewsG13-09 AL ICT Python Programming
0

  1. What is the difference between a built-in and a user-defined function in Python?

  2. Explain the concept of variable scope in Python functions.

  3. Write a Python function to calculate the factorial of a number.

  4. What is the difference between a list and a tuple in Python?

  5. Write a Python program to create a dictionary and print its keys and values.

Ruwan Suraweera Changed status to publish
0

Answers and Descriptions:

  1. Answer: Built-in functions (e.g., print()) are predefined in Python; user-defined functions are created by the programmer.
    Description: Built-in functions are ready-to-use, while user-defined functions (e.g., def my_func():) allow custom logic tailored to specific needs.

  2. Answer: Variable scope determines where a variable is accessible; local variables are within a function, global variables are outside.
    Description: A local variable in a function isn’t accessible outside it, while a global variable can be accessed anywhere unless shadowed.

  3. Answer:

    def factorial(n):
        if n == 0:
            return 1
        return n * factorial(n - 1)
    num = int(input("Enter a number: "))
    print("Factorial is:", factorial(num))

    Description: The recursive function calculates factorial (e.g., 5! = 5 * 4 * 3 * 2 * 1). It returns 1 for 0 and multiplies n by factorial(n-1) otherwise.

  4. Answer: Lists are mutable (can be changed); tuples are immutable (cannot be changed).
    Description: Lists (e.g., [1, 2, 3]) allow modifications like append(), while tuples (e.g., (1, 2, 3)) are fixed, useful for constant data.

  5. Answer:

    my_dict = {"name": "Alice", "age": 17, "grade": 13}
    print("Keys:", my_dict.keys())
    print("Values:", my_dict.values())

    Description: The dictionary stores key-value pairs. The keys() method returns keys (e.g., name, age), and values() returns values (e.g., Alice, 17).

Ruwan Suraweera Changed status to publish
🔴 Lesson List
SIDE BUTTON ON
Sign In Register
×

👋 Welcome Back!

🚀
Ready to Learn?Pick up where you left off.
🔑
Forgot Password?Click the link below to reset.
📢
New FeaturesCheck out the new AI Voice tool.

Sign In

👤
🔒
or continue with
Google Facebook

Already have an account? Register Now