0% found this document useful (0 votes)
3 views

Python-SEM5

The document outlines various aspects of Python programming, including its advantages and disadvantages, differences between lists and tuples, and the concept of user-defined modules. It also covers key features such as exception handling, data types, and built-in functions, along with examples for clarity. Additionally, it discusses specific programming constructs like lambda functions, comments, and the use of selection statements.

Uploaded by

omkarbunny12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python-SEM5

The document outlines various aspects of Python programming, including its advantages and disadvantages, differences between lists and tuples, and the concept of user-defined modules. It also covers key features such as exception handling, data types, and built-in functions, along with examples for clarity. Additionally, it discusses specific programming constructs like lambda functions, comments, and the use of selection statements.

Uploaded by

omkarbunny12
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 31

(Python Sem-V)

a) What are the advantages and disadvantages of Python any five?

--> Advantages of Python:

Readability: Python's syntax is clean and easy to learn.

Versatility: It's used for various applications, from web development to data science.

Large Community: A strong community provides support and resources.

Cross-Platform Compatibility: Runs on different operating systems.

Standard Library: Offers a rich set of built-in modules.

Disadvantages of Python:

Speed: Python can be slower than compiled languages.

Global Interpreter Lock (GIL): Limits parallel processing capabilities.

Memory Consumption: Can be less memory-efficient compared to some languages.

Mobile Development Limitations: Less popular for mobile app development.

Dynamic Typing: While flexible, can lead to runtime errors if not used carefully.

b) List out main differences between lists & tuple.

-->

Criteria List Tuple

List is mutable which means its Tuple is immutable which


Type elements can be updated as per means we can't modify its
requirement. element once created.

List iteration is slower and is


Iteration Tuple iteration is faster.
time consuming.
Tuple is useful for read-only
Appropriate List is useful for insertion and
operations like accessing
for deletion operations.
elements.

Memory
Tuples consumes less
Consumptio List consumes more memory.
memory.
n

List provides many built-in Tuples have less built-in


Methods
methods. methods as compare to list.

List operations are more error


Error prone Tuples operations are safe.
prone.

c) Python is a scripting language. Comment.

--> While Python can be used for scripting, it's also a powerful general-purpose language
capable of building large-scale applications. Its interpreted nature and emphasis on
readability make it suitable for scripting tasks, but its versatility extends beyond that.

d) Demonstrate set with example.

--> A set is an unordered collection of unique elements. Elements in a set cannot be


duplicated. Sets are useful for performing operations like union, intersection, and
difference.

e) What is dictionary? Give example.

--> A dictionary is an unordered collection of key-value pairs. Each key is unique, and it's
used to access the corresponding value. Dictionaries are highly efficient for storing and
retrieving data.

f) What is regEx? give example.


--> Regular expressions (regex) are patterns used to match and manipulate text. They are
powerful tools for text processing and data extraction. The re module in Python provides
functions for working with regular expressions.

g) What is user defined Module? Give example.

-->

# my_module.py

def greet(name):

print("Hello, " + name + "!")

# main.py

import my_module

my_module.greet("Alice") # Output: Hello, Alice!

A user-defined module is a Python file containing functions, classes, and variables that can
be imported and used in other Python scripts. Modules help organize code and promote
reusability.

h) Python is case sensitive language. Comment.

--> Yes, Python is a case-sensitive language. This means that variables, function names,
and keywords must be written with consistent capitalization. For example, myVariable is
different from MyVariable.

j) What is lambda function? Give example.

--> A lambda function is a small, anonymous function defined using the lambda keyword.
It's often used for short, one-time operations. Lambda functions take input arguments,
perform a calculation, and return a result. They are useful for functional programming
paradigms.

EX:

double = lambda x: x * 2
result = double(5)

print(result) # Output: 10

a) How are comments written in Python?

--> Comments are used to explain code and improve readability. Single-line comments
start with #. Multi-line comments are enclosed within triple quotes (""").

# This is a single-line comment

print("Hello, world!")

"""

This is a multi-line comment

that spans multiple lines.(""")

b) Give the use of index() in string.

--> The index() method in Python strings is used to find the index of the first occurrence of a
substring within a string. It returns the index of the first character of the substring. If the
substring is not found, it raises a ValueError.

c) Explain the range() function and its parameters.

--> The range() function generates a sequence of numbers. It takes three optional
parameters: start, stop, and step.

start (default: 0): The starting number of the sequence.

stop (required): The number before which the sequence stops.

step (default: 1): The difference between each number in the sequence.

d) How to create a void function in Python?


--> Code Python,

def greet():

print("Hello, world!")

greet() # Output: Hello, world!

A void function, also known as a procedure, does not return any value. It's defined using the
def keyword followed by the function name and parentheses. The function body contains
the code to be executed when the function is called.

e) What is the difference between pop() and del in list.

-->

del remove() pop()

del is a keyword. It is a method. pop() is a method.

To delete value this This method also uses


To delete value it uses the index. method uses the value the index as a
as a parameter. parameter to delete.

The remove() method


The del keyword doesn’t return pop() returns deleted
doesn’t return any
any value. value.
value.

The del keyword can delete the


At a time it deletes only At a time it deletes only
single value from a list or delete
one value from the list. one value from the list.
the whole list at a time.
It throws value error in It throws index error in
It throws index error in case of
case of value doesn’t case of an index doesn’t
the index doesn’t exist in the list.
exist in the list. exist in the list.

g) What does the following functions return - clock() and gmtime().

--> clock() returns the processor time used by the Python script since it started. This can be
useful for measuring the performance of different parts of your code.

gmtime() returns a time tuple representing the current time in UTC (GMT). This tuple
contains information about the year, month, day, hour, minute, second, day of the week,
day of the year, and daylight saving time flag.

h) List the syntax for handling exception.

--> Syntax for handling exceptions in Python:

try: Encloses the code that might raise an exception.

except: Handles specific exceptions or general exceptions.

else: Executes if no exceptions occur within the try block.

finally: Always executes, regardless of exceptions or successful execution.

i) List any two functions in math module.

--> The math module provides various mathematical functions in Python. Here are two
common functions:

sqrt(x): Calculates the square root of a number x.

pow(x, y): Calculates x raised to the power of y.

j) Explain the function enumerate().


--> The enumerate() function adds a counter to an iterable (like a list or tuple). It returns an
enumerate object, which is an iterator of tuples, where each tuple contains the index and
the corresponding element from the iterable. This is useful for iterating over a sequence
and accessing both the index and the value of each element.

a) What is dry run in Python?

--> A dry run is a manual process of executing a program's logic step-by-step without
actually running it on a computer.It involves tracing the code line by line, simulating the
execution flow and keeping track of variable values. This technique helps in identifying
potential errors, understanding code behavior, and debugging issues before running the
program.

b) Give the purpose of selection statements in Python.

--> Selection statements, such as if, elif, and else, allow you to control the flow of execution
in your Python program based on certain conditions. They enable you to make decisions
and execute specific code blocks depending on whether a given condition is true or false.
This helps in creating dynamic and responsive programs.

c) List the types of type conversion in Python.

--> Python supports two types of type conversion:

Implicit Type Conversion: Python automatically converts data types to compatible ones,
like converting an integer to a float in arithmetic operations.

Explicit Type Conversion: You manually convert data types using built-in functions like int(),
float(), str(), etc. For example, converting a string to an integer: int("10").

d) What is the use of pass statement?

--> The pass statement is a placeholder that does nothing. It's often used to create empty
function bodies or code blocks that will be implemented later. It helps avoid syntax errors
and allows you to maintain the structure of your code.

f) Explain the extend method of list.

--> The extend() method adds all elements of one list to the end of another list. It modifies
the original list in-place. This is different from the append() method, which adds a single
element to the end of the list.
g) What are required arguments in function?

--> Required arguments are mandatory parameters that must be passed to a function when
it's called. The number of required arguments must match the number of parameters
defined in the function's definition. If you don't provide the required arguments, Python will
raise a TypeError.

h) Explain any 2 functions in time module.

--> The time module in Python provides functions for working with time and dates.

1. time.time(): Returns the current time in seconds since the Unix epoch (January 1,
1970, 00:00:00 UTC).

2. time.sleep(seconds): Pauses the execution of the program for the specified number
of seconds.

i) What are the types of file in Python?

--> Python primarily works with two types of files:

Text Files: Store data in human-readable text format.

Binary Files: Store data in binary format, not directly readable by humans.

j) Write the use of seek & tell function.

--> seek() and tell() functions are used to manipulate the file pointer's position within a
file.

seek(offset, from_where): Moves the file pointer to a specific position. from_where can be 0
(beginning), 1 (current position), or 2 (end of file).

tell(): Returns the current position of the file pointer.

These functions are useful for reading and writing specific parts of a file, especially
when dealing with large files.

b) Explain any 2 metacharacters used in regular expression.

--> 1) . (Dot): Matches any single character except a newline character.


Code Python,

pattern = r".at"

matches = re.findall(pattern, text) # Matches "cat", "hat", etc.

2) \d: Matches any digit character (0-9).

Code Python

pattern = r"\d{3}-\d{3}-\d{4}"

match = re.search(pattern, text) # Matches the phone number

c) Explain any 2 built-in list functions.

--> Here are two built-in list functions in Python:

1. append(element): Adds an element to the end of the list.

Python,

my_list.append(6) # my_list becomes [1, 2, 3, 4, 5, 6]

2.pop(index): Removes and returns an element at a specific index. If no index is provided, it


removes and returns the last element.

Python,

removed_element = my_list.pop(2) # Removes and returns 3, my_list becomes [1, 2, 4, 5, 6]

d) Explain backward indexing in strings.

--> Backward indexing allows you to access characters in a string from the end. The last
character has an index of -1, the second-to-last has -2, and so on. This is useful for
processing characters from the end without knowing the exact length.

e) Define identifiers.

--> Identifiers are names given to variables, functions, classes, and other objects in
Python. They must follow certain rules:

1.Start with a letter (a-z, A-Z) or an underscore (_).

2.Can contain letters, numbers, and underscores.


3.Case-sensitive.

4.Cannot be a reserved keyword.

Valid identifiers help make your code readable and maintainable.

a) Which methods are used to read from a file? Explain any two with example.

--> Two common methods to read from a file in Python are:

1.read(): Reads the entire content of the file as a single string.

2.readline(): Reads a single line from the file.

The with statement ensures proper file closure, even if an exception occurs.

b) What are the usage of dictionary copy(), gets(), items() and keys()

Methods?

--> copy(): Creates a new dictionary with the same key-value pairs.

get(): Retrieves a value associated with a key, with an optional default value.

items(): Returns a view of the dictionary's key-value pairs.

keys(): Returns a view of the dictionary's keys.

c) Explain union and intersection with example.

--> Union: Combines elements from both sets, removing duplicates.

Intersection: Returns a set containing elements present in both sets.

Code Python,

set1 = {1, 2, 3}

set2 = {2, 3, 4}

# Union

union_set = set1.union(set2)

print(union_set) # Output: {1, 2, 3, 4}

# Intersection
intersection_set = set1.intersection(set2)

print(intersection_set) # Output: {2, 3}

i) if

--> The if statement checks a condition. If the condition is True, the code inside the
indented block is executed.

b) if else

--> The if-else statement provides an alternative block of code to execute when the
condition is False.

c) break

--> The break statement immediately terminates the loop it's inside.

d) continue

--> The continue statement skips the rest of the current iteration and moves to the next
iteration of the loop.

e) List features of Python

--> Python offers simplicity, versatility, and a strong community. It's easy to learn, has a
clean syntax, and is used for web development, data science, machine learning, and more.
Its extensive libraries and cross-platform compatibility make it a powerful tool for various
applications.

a) Write a python program to calculate XY.

--> def calculate_xy(x, y):

"""Calculates the product of x and y."""

result = x * y

return result

# Get input values from the user


x = float(input("Enter the value of x: "))

y = float(input("Enter the value of y: "))

# Calculate the product

product = calculate_xy(x, y)

# Print the result

print("The product of", x, "and", y, "is:", product)

b) Write a python program to accept a number and check whether it is perfect number
or not.

-->

def is_perfect_number(number):

"""Checks if a number is perfect."""

sum_of_divisors = 0

for i in range(1, number):

if number % i == 0:

sum_of_divisors += i

return sum_of_divisors == number

# Get input from the user

number = int(input("Enter a number: "))

if is_perfect_number(number):

print(number, "is a perfect number.")

else:

print(number, "is not a perfect number.")


This program defines a function is_perfect_number to check if a number is perfect. It
calculates the sum of divisors and compares it to the number itself. If they are equal, the
number is perfect.

d) Demonstrate list slicing.

--> List slicing allows you to extract specific portions of a list using indexing and slicing
syntax. You can specify the start index, end index (exclusive), and optional step size to
create new lists from existing ones.

e) A tuple is ordered collection of items. Comment.

--> Yes, a tuple is indeed an ordered collection of items. This means that the elements
in a tuple are stored in a specific sequence, and their order is preserved. Unlike lists,
tuples are immutable, which means you cannot change their elements after creation.

a) Write a short note on datatypes in Python.

--> Python offers a variety of data types to store different kinds of information:

1.Numeric Types:

int: Represents integer numbers (e.g., 10, -5, 0)

float: Represents floating-point numbers (e.g., 3.14, -2.5)

complex: Represents complex numbers (e.g., 2+3j)

2.Boolean Type:

bool: Represents True or False values

3.Sequence Types:

str: Represents a sequence of characters (e.g., "Hello, world!")

list: Represents an ordered collection of items (e.g., [1, 2, 3, "apple"])

tuple: Represents an ordered, immutable collection of items (e.g., (1, 2, 3))

4.Set Type:

set: Represents an unordered collection of unique items (e.g., {1, 2, 3})

5.Mapping Type:
dict: Represents a collection of key-value pairs (e.g., {'name': 'Alice', 'age': 30})

Understanding these data types is crucial for effective Python programming.

b) Write a short note on exception handling.

--> Exception handling in Python is used to gracefully handle errors and unexpected events
that may occur during program execution. It helps prevent the program from crashing and
provides a way to recover or take appropriate actions.

The try block contains the code that might raise an exception. If an exception occurs, the
except block is executed. Multiple except blocks can be used to handle different types of
exceptions. The else block is optional and executes only if no exceptions occur within the
try block. The finally block is also optional and always executes, regardless of whether an
exception occurred or not.

c) What is a module?

--> A module is a Python file containing functions, classes, and variables. It's used to
organize code and promote reusability. You can import modules using the import
statement. In the example, my_module.py is a module, and main.py imports and uses
its greet function.

# my_module.py

def greet(name):

print("Hello, " + name + "!")

# main.py

import my_module

my_module.greet("Alice") # Output: Hello, Alice!

d)What is package? Explain with example

--> A package is a collection of Python modules organized into a directory hierarchy. It


helps in organizing and managing code, especially for larger projects. The __init__.py
file marks a directory as a Python package.
# my_package/module1.py

def greet():

print("Hello from module1!")

# my_package/__init__.py

# (Empty file to mark the directory as a package)

# main.py

import my_package.module1

my_package.module1.greet() # Output: Hello from module1!

a) Write a program to get a single string from two given strings, separated

by space and swap the first two characters of each string

Sample input: ‘abc’, ‘pqr’

Output: pqc abr

--> def swap_first_two_chars(str1, str2):

"""Swaps the first two characters of two strings and concatenates them."""

new_str1 = str2[:2] + str1[2:]

new_str2 = str1[:2] + str2[2:]

return new_str1 + " " + new_str2

# Get input strings from the user

str1 = input("Enter the first string: ")

str2 = input("Enter the second string: ")

# Swap and concatenate the strings

result = swap_first_two_chars(str1, str2)

# Print the result

print(result)
b) Write a program to display power of 2 upto a given number using

anonymous function

Example

N=2

2 raised to 0 is 1

2 raised to 1 is 2

2 raised to 2 is 4

--> N = int(input("Enter a number: "))

power = lambda x: 2**x

for i in range(N+1):

print(f"2 raised to {i} is {power(i)}")

c) Write a program to read an entire text file.

--> def read_file(filename):

"""Reads the entire content of a text file."""

with open(filename, 'r') as file:

content = file.read()

return content

# Get the filename from the user

filename = input("Enter the filename: ")

# Read the file and print its content

content = read_file(filename)

print(content)

a) Write a Python program to check if a given number is Armstrong.

--> def is_armstrong_number(number):


"""Checks if a number is an Armstrong number."""

num_str = str(number)

num_digits = len(num_str)

sum_of_digits = 0

for digit in num_str:

sum_of_digits += int(digit) ** num_digits

return sum_of_digits == number

# Get input from the user

number = int(input("Enter a number: "))

if is_armstrong_number(number):

print(number, "is an Armstrong number.")

else:

print(number, "is not an Armstrong number.")

b) Write a Python program to display power of 2 using anonymous

function.

--> N = int(input("Enter a number: "))

power = lambda x: 2**x

for i in range(N+1):

print(f"2 raised to {i} is {power(i)}")

c) Write a Python program to print even length words in a string.

--> def print_even_length_words(string):

"""Prints even-length words in a string."""

words = string.split()

for word in words:


if len(word) % 2 == 0:

print(word)

# Get input string from the user

string = input("Enter a string: ")

# Print even-length words

print_even_length_words(string)

a) Write a Python program to check for Zero Division Error Exception.

--> def divide_numbers(a, b):

"""Divides two numbers and handles ZeroDivisionError."""

try:

result = a / b

print("Result:", result)

except ZeroDivisionError:

print("Error: Division by zero is not allowed.")

# Get input numbers from the user

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

# Call the function to perform division

divide_numbers(num1, num2)

b) Write a Python program to find gcd of a number using recursion.

--> def gcd_recursive(a, b):

"""Calculates the greatest common divisor (GCD) of two numbers recursively."""

if b == 0:
return a

else:

return gcd_recursive(b, a % b)

# Get input numbers from the user

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

# Calculate the GCD using recursion

gcd = gcd_recursive(num1, num2)

print("The GCD of", num1, "and", num2, "is:", gcd)

c) Write a Python program to check if a given key already exists in a

dictionary.

--> def check_key_existence(dictionary, key):

"""Checks if a key exists in a dictionary."""

if key in dictionary:

print(f"The key '{key}' exists in the dictionary.")

else:

print(f"The key '{key}' does not exist in the dictionary.")

# Create a sample dictionary

my_dict = {'name': 'Alice', 'age': 30, 'city': 'New York'}

# Get input key from the user

key_to_check = input("Enter a key to check: ")

# Check for key existence

check_key_existence(my_dict, key_to_check)

a) Write a python program to Count Vowels and Consonants in a String.


--> def count_vowels_consonants(string):

vowels = "aeiouAEIOU"

vowel_count = 0

consonant_count = 0

for char in string:

if char in vowels:

vowel_count += 1

elif char.isalpha():

consonant_count += 1

return vowel_count, consonant_count

# Get input string from the user

string = input("Enter a string: ")

vowels, consonants = count_vowels_consonants(string)

print("Vowels:", vowels)

print("Consonants:", consonants)

b) Write a Python script to print a dictionary where the keys are numbers

between 1 and 15 (both included) and the values are the square of the

keys.

Sample Dictionary

{1: 1, 2:4, 3:9, 4: 16, 5:25, 6:36, 7:49, 8:64, 9:81, 10: 100, 11: 121, 12: 144,

13: 169, 14: 196, 15: 225}

--> square_dict = {}

for num in range(1, 16):


square_dict[num] = num ** 2

print(square_dict)

c) Write a Python function that accepts a string and counts the number of

upper and lower case letters.

--> def count_case_letters(input_string):

"""

Counts the number of uppercase and lowercase letters in a given string.

Args:

input_string (str): The string to analyze.

Returns:

dict: A dictionary with counts of uppercase and lowercase letters.

"""

upper_count = sum(1 for char in input_string if char.isupper())

lower_count = sum(1 for char in input_string if char.islower())

return {"Uppercase": upper_count, "Lowercase": lower_count}

# Example usage

string = "Hello World!"

result = count_case_letters(string)

print(f"Uppercase letters: {result['Uppercase']}")

print(f"Lowercase letters: {result['Lowercase']}")

a) Write a recursive function in Python to display addition of digits in

single digit.

--> def sum_to_single_digit(n):

"""
Recursively calculates the sum of digits of a number until it becomes a single digit.

Args:

n (int): The number to process.

Returns:

int: The single-digit sum of the digits.

"""

# Base case: if the number is a single digit, return it

if n < 10:

return n

else:

# Calculate the sum of the digits

digit_sum = sum(int(digit) for digit in str(n))

# Recursively call the function with the new sum

return sum_to_single_digit(digit_sum)

# Example usage

number = 9876

result = sum_to_single_digit(number)

print(f"The single-digit sum of {number} is: {result}")

b) Write a program in python to accept 'n' integers in a list, compute &

display addition of all squares of these integers.

--> def sum_of_squares():

"""

Accepts 'n' integers from the user, computes, and displays the sum of their squares.

"""
n = int(input("Enter the number of integers: "))

numbers = []

# Accept 'n' integers from the user

for _ in range(n):

number = int(input("Enter an integer: "))

numbers.append(number)

# Compute the sum of squares

squares_sum = sum(x**2 for x in numbers)

print(f"The sum of squares of the given integers is: {squares_sum}")

# Example usage

sum_of_squares()

c) Write a Python program to count all occurences of "India" and

"Country" in a text file "pledge.txt".

--> def count_words_in_file(filename):

"""

Counts the occurrences of the words "India" and "Country" in a text file.

Args:

filename (str): The name of the file to read.

Returns:

dict: A dictionary with counts of "India" and "Country".

"""

try:

with open(filename, 'r') as file:

content = file.read()
india_count = content.lower().count("india")

country_count = content.lower().count("country")

return {"India": india_count, "Country": country_count}

except FileNotFoundError:

print(f"Error: The file '{filename}' does not exist.")

return {}

# Example usage

filename = "pledge.txt"

result = count_words_in_file(filename)

if result:

print(f"'India' occurs {result['India']} times.")

print(f"'Country' occurs {result['Country']} times.")

a) What is the output of following code :

X=5

def f1( ) :

global X

X=4

def f2(a, b) :

global X

return a+b+X

f1( )

total = f2(1, 2)

print (total)
--> Execution:

1. X = 5: The global variable X is initialized to 5.


2. Function f1():
a. The global X statement allows modification of the global X.
b. Inside f1(), X is set to 4.
3. Call f1():
a. This changes the value of the global X to 4.
4. Function f2(a, b):
a. The global X statement allows access to the global X.
b. The function calculates a+b+Xa + b + Xa+b+X, where a=1a = 1a=1, b=2b =
2b=2, and X=4X = 4X=4 (modified by f1()).
c. The calculation is 1+2+4=71 + 2 + 4 = 71+2+4=7.
5. Assign and Print total:
a. total is assigned the value 7 (the result of f2(1, 2)).
b. print(total) outputs 7.

Output:

b) What is the output of following code :

def f(X) :

def f1(a, b) :

print ("hello")

if (b==0) :

print ("NO")

return

return f(a, b)

return f1

@f
def f(a, b) :

return a%b

f(4, 0)

--> Step-by-Step Execution:

1. Outer Function f(X):


a. This is a higher-order function that takes a parameter X (in this case, X is a
function due to the decorator @f).
b. Inside f(X), a nested function f1(a, b) is defined:
i. It prints "hello".
ii. If b == 0, it prints "NO" and exits with return.
iii. Otherwise, it calls f(a, b) and returns the result.
c. f(X) returns the nested function f1.
2. Decorator @f:
a. The @f decorator is applied to the function f(a, b).
b. This means the original f(a, b) function is passed as the argument X to the
outer function f(X).
c. The outer function f(X) returns f1, replacing the original f(a, b) with f1.
3. Calling f(4, 0):
a. After the decorator is applied, calling f(4, 0) actually calls the f1(a, b)
function inside f(X).
b. Inside f1(a=4, b=0):
i. "hello" is printed.
ii. Since b == 0, "NO" is printed, and the function exits with return.

Final Output:

hello
NO

a)

a = True
b = False

c = False

if not a or b:

print (1)

elif not a or not b and c:

print (2)

elif not a or b or not b and a:

print (3)

else:

print (4)

--> Step-by-Step Execution:

1. Variables:
a. a = True
b. b = False
c. c = False
2. First if Condition:

python
Copy code
if not a or b:

a. not a is not True, which evaluates to False.


b. b is False.
c. Therefore, not a or b is False or False, which evaluates to False.
d. This block is not executed.
3. First elif Condition:

python
Copy code
elif not a or not b and c:

a. not a is not True, which evaluates to False.


b. not b is not False, which evaluates to True.
c. not b and c is True and False, which evaluates to False.
d. not a or not b and c is False or False, which evaluates to False.
e. This block is not executed.
4. Second elif Condition:

python
Copy code
elif not a or b or not b and a:

a.not a is not True, which evaluates to False.


b.b is False.
c.not b is not False, which evaluates to True.
d.not b and a is True and True, which evaluates to True.
e.not a or b or not b and a is False or False or True, which
evaluates to True.
f. This block is executed, and print(3) is executed.
5. else Block:
a. The else block is not reached because the second elif condition is true.

Final Output:

b) def f1(x, 1=[ ]):

for i in range(x):

1.append(i*i)

print(1)

f1 (2)

f1 (3,[3,2,1])
f1 (3)

--> Step-by-Step Execution:

1. First Call: f1(2)


a. x = 2, and the default lst = [] (an empty list).
b. The loop runs for i = 0 and i = 1:
i. When i = 0, 0 * 0 = 0, so lst = [0].
ii. When i = 1, 1 * 1 = 1, so lst = [0, 1].
c. Prints: [0, 1].
2. Second Call: f1(3, [3, 2, 1])
a. x = 3, and lst = [3, 2, 1] (a custom list is passed).
b. The loop runs for i = 0, i = 1, and i = 2:
i. When i = 0, 0 * 0 = 0, so lst = [3, 2, 1, 0].
ii. When i = 1, 1 * 1 = 1, so lst = [3, 2, 1, 0, 1].
iii. When i = 2, 2 * 2 = 4, so lst = [3, 2, 1, 0, 1, 4].
c. Prints: [3, 2, 1, 0, 1, 4].
3. Third Call: f1(3)
a. x = 3, and the default lst = [] does not reset because default mutable
arguments (like lists) retain their state between function calls.
b. lst is now [0, 1] (from the first call).
c. The loop runs for i = 0, i = 1, and i = 2:
i. When i = 0, 0 * 0 = 0, so lst = [0, 1, 0].
ii. When i = 1, 1 * 1 = 1, so lst = [0, 1, 0, 1].
iii. When i = 2, 2 * 2 = 4, so lst = [0, 1, 0, 1, 4].
d. Prints: [0, 1, 0, 1, 4].

Final Output:

[0, 1]
[3, 2, 1, 0, 1, 4]
[0, 1, 0, 1, 4]

a) Trace the output of the following :

sum = 0
for i in range (12, 2, –2) :

sum + = i

print sum

--> Execution Step-by-Step:

1. range(12, 2, -2):
a. This generates numbers starting at 12, decreasing by 2, and stopping before
2.
b. The sequence is: [12, 10, 8, 6, 4].
2. Loop Iteration:
a. Iteration 1: i = 12, sum = 0 + 12 = 12.
b. Iteration 2: i = 10, sum = 12 + 10 = 22.
c. Iteration 3: i = 8, sum = 22 + 8 = 30.
d. Iteration 4: i = 6, sum = 30 + 6 = 36.
e. Iteration 5: i = 4, sum = 36 + 4 = 40.
3. Final Output: After the loop completes, sum = 40.

Output:

40

b) Trace the output of the following :

count = 1

def doThis ( ) :

global count

for i in (1, 2, 3) :

count + = 1

doThis( )
---> Execution:

1. Global count is initially 1.


2. Function doThis() is defined:
a. global count inside doThis() makes the variable count accessible
globally within the function's scope.
3. Loop inside doThis()
a. for i in (1, 2, 3):
b. count is incremented by 1 three times:
i. count = 1 + 1 = 2
ii. count = 2 + 1 = 3
iii. count = 3 + 1 = 4
4. After the loop is done, doThis() ends, and count in the global scope is 4
5. No other operations are performed in the main program.

Final Output:

The global `count` is `4`.

You might also like