(X) Unit 4 Programming in Python

Python मा जम्मा ५ वटा Exercise पेज 151,163,185,202,225

Unit 4: Python (Page: 151)

1. Choose the correct answer.

i. Which statement is used to display output in Python? a) input ( ) b) print ( ) c) display ( ) d) output ( ) ii. Which of the following is NOT a valid Python data type mentioned in the text? a) int b) float c) character d) bool iii. What type of values does the Boolean data type hold? a) Whole numbers b) Decimal numbers c) Text d) True or False iv. Which of the following is an example of a relational operator? a) + b) * c) == d) and v. Which logical operator returns True if both conditions are true? a) or b) not c) and d) != vi. What is the purpose of the if statement in Python? a) To repeat a block of code. b) To define a function. c) To execute a block of code only if a condition is true. d) To store multiple items in a single variable. vii. Which conditional statement allows you to check multiple conditions in sequence? a) if b) if-else c) nested if d) if-elif-else viii. What is the term for repeating a block of code multiple times? a) Selection b) Iteration c) Condition d) Assignment ix. Which type of loop is used when you know the number of times you want to repeat a block of code? a) while loop c) if loop b) for loop d) nested loop x. Which data structure is used to store multiple items in a single variable in Python, as shown in the example ["Computer", "Science", 20, True]? a) String b) Tuple c) List d) Dictionary 2. Write short answers to these questions. a) What is the primary function of the input() function in Python? Ans: The input() function is used to take input from the user through the keyboard. b) Provide an example of a string literal in Python. Answer: "Hello, World!" or 'Python' are examples of string literals. c) What is an identifier in the context of Python programming? Ans: An identifier is the name used to identify variables, functions, classes, or other objects in a Python program. d) Explain the difference between the division operator (/) and the floor division operator (//) in Python. Ans: The / operator returns the division result as a decimal (float), while the // operator returns the quotient without the decimal part (integer). Example: 10 / 3 = 3.3333 10 // 3 = 3 e) Define the concept of data types in Python. Ans: Data types specify the type of value a variable can store, such as integers, floats, strings, and Boolean values. f) What is the purpose of relational operators in Python? Give one example. Ans: Relational operators are used to compare two values and return either True or False. Example: 10 > 5 returns True. g) Describe the functionality of the else block in an if-else statement. Ans: The else block executes when the condition in the if statement is False. h) What is a nested if statement? Ans: A nested if statement is an if statement placed inside another if or else block to check additional conditions. i) When would you typically use a for loop instead of a while loop? Ans: A for loop is used when the number of iterations is known in advance or when looping through a sequence like a list or string. j) What is the role of the range() function often used with for loops? Answer: The range() function generates a sequence of numbers, which is commonly used to control the number of repetitions in a for loop. k) Define a Python list and provide a simple example. Ans: A Python list is an ordered collection of multiple items stored in a single variable. Example: fruits = ["Apple", "Banana", "Mango"] l) Discuss the concept of iteration in programming. Ans: Iteration is the process of repeating a block of code multiple times until a condition is met or all items in a sequence have been processed.

3. Write long answers to these questions.

a) Explain the different categories of operators available in Python (arithmetic, relational, and logical) with examples of each.

Arithmetic Operators

Arithmetic operators perform standard mathematical calculations on numerical values. 1. Addition (+): Adds two operands. Example: 5 + 3 results in 8. 2. Subtraction (-): Subtracts the right operand from the left operand. Example: 10 - 4 results in 6. 3. Multiplication (*): Multiplies two operands. Example: 3 * 4 results in 12. 4. Division (/): Divides the left operand by the right operand. It always returns a float (decimal value). Example: 7 / 2 results in 3.5. 5. Floor Division (//): Divides the operands and rounds the result down to the nearest whole integer. Example: 7 // 2 results in 3. 6. Modulus (%): Returns the remainder of a division operation. Example: 7 % 2 results in 1 (since 2 goes into 7 three times, with 1 left over). 7. Exponentiation (**): Raises the first operand to the power of the second operand. Example: 2 ** 3 results in 8 (23).

Relational (Comparison) Operators:

Relational operators compare two values and evaluate to a Boolean value: either True or False. 1. Equal to (==): Returns True if both sides are equal. Example: 5 == 5 is True. 2. Not equal to (!=): Returns True if the operands are not equal. Example: 5 != 3 is True. 3. Greater than (>): Returns True if the left operand is larger than the right. Example: 10 > 7 is True. 4. Less than (<): Returns True if the left operand is smaller than the right. Example: 4 < 2 is False. 5. Greater than or equal to (>=): Returns True if the left operand is greater than or equal to the right. Example: 5 >= 5 is True. 6. Less than or equal to (<=): Returns True if the left operand is less than or equal to the right. Example: 3 <= 8 is True.

Logical Operators

Logical operators combine conditional statements and evaluate expressions based on Boolean logic. 1. and Operator: Returns True only if both conditions are true. If either condition is false, it returns False. Example: (5 > 3) and (10 > 2) evaluates to True because both individual expressions are true. 2. or Operator: Returns True if at least one of the conditions is true. It only returns False if both conditions are false. Example: (5 < 3) or (10 > 2) evaluates to True because 10 > 2 is true. 3. not Operator: Reverses the Boolean state of the expression. It turns True into False, and False into True. Example: not(5 > 3) evaluates to False because 5 > 3 is true.
b) Describe the three main types of conditional statements in Python (if, if-else, and if-elif-else).

Three Main Types of Conditional Statements in Python

Conditional statements control the flow of a program based on whether certain conditions evaluate to True or False.

1. if Statement

The simplest form of control structure. It executes a block of code if, and only if, a specified condition is true. If the condition is false, the block is skipped. Example: age = 20 if age >= 18: print("You are an adult.")

2. if-else Statement

Provides an alternative path of execution. If the condition is true, the if block runs; if it is false, the else block runs. Example: age = 16 if age >= 18: print("You can vote.") else: print("You are too young to vote.")

3. if-elif-else Statement

Used to check multiple exclusive conditions sequentially. elif stands for "else if". Python evaluates them from top to bottom; the first true condition executes its block. If none are true, the optional final else block runs.Example: score = 85 if score >= 90: print("Grade: A") elif score >= 80: print("Grade: B") else: print("Grade: C")
c) Explain the two types of loops available in Python (for and while) with their respective syntaxes and provide a practical example demonstrating the use of each loop.

Two Types of Loops in Python

Loops allow you to execute a block of code repeatedly.

1. for Loop

Syntax: for item in iterable: # Code block to execute Practical Example: Used when you want to iterate over a known sequence (like a list, string, or a range of numbers).
 # Prints numbers from 1 to 5
for i in range(1, 6):
    print( i )

2. while Loop

Syntax: while condition: # Code block to execute Practical Example: Used when the number of iterations is not known in advance, and the loop depends on a condition remaining true.
# Countdown from 3 to 1
count = 3
while count > 0:
    print(count)
    count -= 1  # Updates condition variable
d) Describe the four basic data types covered in the text (integer, float, string, and boolean), providing an example of each. Why is it important to understand data types when writing Python programs?

Basic Data Types in Python

1. Description and Examples

1. Integer (int): Represents whole numbers without fractional parts (positive, negative, or zero). Example: x = -5 2. Float (float): Represents real numbers containing one or more decimals. Example: pi = 3.14159 3. String (str): A sequence of characters enclosed inside single, double, or triple quotes. Example: name = "Python" 4. Boolean (bool): Represents one of two logical values. Example: is_active = True

2. Importance of Understanding Data Types

Understanding data types is crucial because it defines:Memory Allocation: The system allocates resources efficiently based on what type of data is stored.Valid Operations: Python prevents illegal operations (e.g., you cannot add a string to an integer like "hello" + 5). Knowing your data types prevents runtime exceptions.Logic Design: Functions and methods perform differently depending on the input type (e.g., using + on numbers performs arithmetic addition, but on strings, it performs concatenation).
e) Imagine you need to write a Python program that takes an integer input from the user and performs the following actions: i. Prints "Positive" if the number is greater than 0. ii. Prints "Negative" if the number is less than 0. iii. Prints "Zero" if the number is equal to 0. iv. If the number is positive, it then checks if it's even or odd and prints the result.
num = int(input("Enter an integer: ")) if num > 0: print("Positive") if num % 2 == 0: print("Even") else: print("Odd") elif num < 0: print("Negative") else: print("Zero")
f) Write the Python code for this program, demonstrating your understanding of input/output, conditional statements (including nested if), and basic arithmetic operators.
# 1. Input/Output: Take score input from the user and convert to integer score = int(input("Enter test score (0-100): ")) # 2. Conditional Statements: Primary check for passing, failing, or perfect score if score >= 50: print("Pass") # Nested IF: Check for distinction using comparison operator (>=) if score >= 80: print("Distinction") else: print("Standard Pass") elif score >= 0: print("Fail") # Nested IF: Check how close they were using subtraction (-) points_needed = 50 - score print("Points needed to pass: ", points_needed) else: print("Invalid Score (Negative number)")

Unit 4: Python Functions (Page: 163)

1. Choose the correct answer.

i. Which keyword is used to define a user-defined function in Python? a) function b) define c) def d) func ii. What are the values passed to a function when it is called known as? a) Parameters b) Arguments c) Return values d) Scope iii. The part of the program where a function can be accessed is called its: a) Parameter b) Argument c) Return type d) Scope iv. Variables declared inside a function have: a) Global scope b) Local scope c) Unlimited scope d) No scope v. What does the return statement do in a Python function? a) Prints output to the console. b) Takes input from the user. c) Sends a value back to the caller of the function. d) Defines the function. vi. What are the values specified in the function header within the parentheses called? a) Arguments b) Parameters c) Return values d) Local variables vii. What type of argument allows you to call a function by specifying the parameter names? a) Positional arguments b) Default arguments c) Keyword arguments d) Required arguments viii. A function that performs an action but does not explicitly return a value is sometimes referred to as a: a) Non-void function b) Void function c) Recursive function d) Anonymous function ix. Can a Python function return multiple values? a) No b) Yes, as a list c) Yes, as a tuple d) Yes, directly separated by commas

2. Write short answers to these questions.

a) What is the main benefit of using user-defined functions in programming? Ans: User-defined functions promote code reusability and modularity, allowing you to write logic once and execute it multiple times, which reduces redundancy and makes code easier to maintain and debug. b) Name the two types of Python functions. Ans: Two types of Python functions 1. Built-in functions: Pre-defined functions provided by Python (e.g., print(), len()). 2. User-defined functions: Custom functions created by programmers using the def keyword. c) Explain the difference between a parameter and an argument in the context of Python functions Ans: Parameter: A variable listed inside the parentheses in the function's definition. Argument: The actual value or data passed into the function when it is called. d) What is local scope in Python functions? Provide a brief example. Ans: Local scope refers to variables declared inside a function, which are accessible only within that function and are destroyed once the function finishes executing.
def my_function(): x = 10 # 'x' has local scope print(x) my_function() # Accessing 'x' outside the function here will cause a NameError
e) What is global scope in Python? How does it differ from local scope? Ans: Variables created in the main body of the script have global scope and can be accessed from anywhere in the program, including inside functions. In contrast, local variables are created inside a function and can only be accessed within that specific function block. f) What is the purpose of the return keyword in a Python function? Ans: The return keyword exits a function and sends a calculated value or object back to the caller. g) Explain what positional arguments are and how they are passed to a function. Ans: Positional arguments are values passed to a function that are matched to parameters based on their order or position. The first argument maps to the first parameter, the second to the second, and so on. h) Describe the use case for default arguments in Python functions. Ans:Default arguments allow you to specify a fallback value for a parameter in the function signature. They are used when a parameter typically uses a standard value, making the function call simpler while still leaving the flexibility to override it when needed. i) What are keyword arguments, and what advantage do they offer when calling a function? Ans: Keyword arguments are passed to a function using the name=value format (e.g., func(age=25, name="Alice")). Their primary advantage is that order does not matter, which improves code clarity and readability. j) What happens if a void function has a return statement without any value? Ans: If a function executes a return statement with no specified value, it immediately terminates execution of the function and implicitly returns None.

3. Write long answer to these questions.

a. Explain the concept of function scope in Python, differentiating between local and global scope.

Scope defines the region of a Python program where a specific variable is visible and accessible. Python uses namespaces to track variables and follows the LEGB rule (Local, Enclosing, Global, Built-in) to resolve variable names in order.

Local Scope

A variable defined inside a function belongs to the local scope of that function. It is created when the function executes and is completely destroyed when the function finishes execution. Local variables cannot be accessed outside the function.

def calculate_area():
    radius = 5  # Local variable
    print("Inside function radius:", radius)

calculate_area()
# Accessing 'radius' here raises a NameError

Global Scope

A variable declared at the top level of a Python file (outside all functions) belongs to the global scope. Global variables are accessible throughout the entire script after their declaration, including inside functions.

pi = 3.14159  # Global variable

def print_pi():
    print("Global pi inside function:", pi)

print_pi()
print("Global pi outside function:", pi)

Key Differences

Feature Local Scope Global Scope
Declaration Place Inside a function body Outside all functions
Lifetime Created at function call, destroyed on return Exists for the lifetime of the program run
Accessibility Accessible only within the defining function Accessible anywhere within the module
Modification Can be updated directly inside the function Requires the global keyword to modify inside a function

Modifying Global Variables (global keyword)

To modify a global variable inside a local scope, declare it using the global keyword:

counter = 0

def increment():
    global counter  # Declares intention to modify the global variable
    counter += 1

increment()
print(counter)  # Output: 1
b.Describe the concept of return values in Python functions. Differentiate between functions that return a value (non-void) and those that do not (void). Provide examples of both types and explain how the return value can be used in the calling part of the program.

A return value is the data that a function sends back to the location where it was invoked. The return statement terminates function execution immediately and passes control and output back to the caller.

Non-Void Functions (Functions Returning a Value)

Non-void functions compute a value and explicitly send it back using the return statement. The caller can store this returned value in a variable, pass it into another function, or evaluate it in expressions.

def add_numbers(a, b):
    return a + b  # Explicit return statement

# Storing the return value in a variable
total = add_numbers(10, 20)
print("Total:", total)

# Using the return value directly in an expression
doubled_total = add_numbers(10, 20) * 2
print("Doubled Total:", doubled_total)

Void Functions (Functions without Return Values)

Void functions perform an action without returning a value. In Python, if a function lacks a return statement, it implicitly returns None Python's built-in constant representing the absence of a value.

def greet_user(name):
    print(f"Hello, {name}!")  # Performs an I/O action, no return statement

result = greet_user("Alice")
print("Returned value:", result)  # Output: Returned value: None
Feature Non-Void Functions Void Functions
Return Mechanism Explicit return expression No return statement (or bare return)
Evaluated Result Evaluates to the specified expression/object Always evaluates to None
Primary Use Case Calculations, data processing, transformations Displaying output, updating state, file I/O
c. Python allows functions to return multiple values. Explain how this is achieved and provide an example demonstrating a function that returns multiple values and how these values can be accessed by the caller.

Python allows functions to return multiple values seamlessly by automatically packing them into a single tuple.

How It Works

When multiple comma-separated expressions follow a return statement, Python implicitly creates a tuple containing those values. The caller can either receive the entire tuple as a single object or use tuple unpacking to extract the values into separate individual variables.

Demonstration Example

def calculate_stats(numbers):
    total = sum(numbers)
    count = len(numbers)
    average = total / count if count > 0 else 0
    return total, average, count  # Automatically packs as a tuple: (total, average, count)

sample_data = [10, 20, 30, 40, 50]

# Access Method 1: Tuple Unpacking into separate variables
sum_val, avg_val, count_val = calculate_stats(sample_data)
print(f"Sum: {sum_val}, Average: {avg_val}, Count: {count_val}")

# Access Method 2: Receiving as a single tuple object
result_tuple = calculate_stats(sample_data)
print("Returned Tuple:", result_tuple)
print("Accessing by index (Average):", result_tuple[1])
d. Design a Python program that includes at least two user-defined functions: 1. One function that takes two numbers as arguments and returns their product. 2. Another function that takes a list of numbers as an argument and prints each number.

Below is the complete implementation meeting the required user-defined functions:

# i. Function that takes two numbers and returns their product
def multiply(num1, num2):
    """Takes two numbers as arguments and returns their product."""
    return num1 * num2

# ii. Function that takes a list of numbers and prints each number
def print_list_elements(numbers):
    """Takes a list of numbers as an argument and prints each number."""
    print("--- List Items ---")
    for item in numbers:
        print(item)

# Main Execution Block
if __name__ == "__main__":
    # Demonstrating Function i (Non-void function)
    a, b = 6, 7
    product_result = multiply(a, b)
    print(f"The product of {a} and {b} is: {product_result}\n")

    # Demonstrating Function ii (Void function)
    my_numbers = [10, 25, 42, 78, 100]
    print_list_elements(my_numbers)

Expected Output

The product of 6 and 7 is: 42
--- List Items ---
10
25
42
78
100

Unit 4: Python (Page: 185)

Unit 4: Python (Page: 202)

Unit 4: Python (Page: 225)

Back