Chapter 5+6+7
Chapter 5+6+7
Q4) Can you convert any for loop to a while loop? List the advantages of
using for loops.
Yes, any for loop can be converted into a while loop by managing the loop
variable manually.
Here are the advantages of using for loops in Python,
1. Simpler syntax – Less code for iteration.
2. Automatic iteration – Handles iterables (like lists, ranges) automatically.
3. Less error-prone – No need to manually update the loop variable.
4. Built-in functions – Works well with Python functions like range(),
enumerate().
5. Better readability – More readable and Pythonic.
6. Efficient with complex iterables – Easily loops over dictionaries, tuples,
etc.
for
The for loop is a count-controlled loop that executes a block of code repeatedly
for a fixed number of times. It consists of an initialization, a condition, and an
increment/decrement statement.
Often you know exactly how many times the loop body needs to be executed, so
a control variable can be used to count the executions. A loop of this type is
called a counter-controlled loop.
In general, the syntax of a for loop is:
for var in sequence:
# Loop body
a) for i in range(endValue):
#Loop body
b) for i in range(initialValue, endValue):
# Loop body
c) for i in range(initialValue, endValue,k):
#k=step value # Loop body
while
The while loop is a condition-controlled loop; it is controlled by a true/false
condition. It executes a block of code repeatedly as long as the specified
condition remains True
The syntax for the while loop is:
while loop-continuation-condition:
# Loop body Statement(s)
Q7) Can the following conversions be allowed? If so, find the converted
result.
i = int(True)
j = int(False)
b1 = bool(4)
b2 = bool(0)
Yes, the following conversions are allowed in Python. Here’s the result for each
one:
Result: i = 1
Result: j = 0
Result: b1 = True # Any non-zero number (like 4) is considered True
when cast to a boolean.
Result: b2 = False
print(random_number)
2) Generate a random float:
import random
random_float = random.random() # Generates a random float
between 0 and 1
print(random_float)
You can rewrite the given if statement using a Boolean expression like this:
newLine = (count % 10 == 0)
Chapter 6
Chapter 7
The function can be invoked by calling its name with arguments in parentheses.
Example:
greet("Alice")
def print_hello():
print("Hello")
# print_hello() is a statement
print_hello()
Q27) Can you have a return statement in a None function? Does the
return statement in the following function cause syntax errors?
def xFunction(x, y):
print(x + y)
return
Yes, you can have a return statement in a function that does not return any
value (i.e., a function that implicitly returns None). However, a return statement
without any value simply exits the function and returns None by default.
This function will not cause a syntax error because the return statement is
valid, even though it doesn't return any value. The function will:
1. Print the sum of x and y.
2. Return None (implicitly, since there's no value after return).
2. Parameter:
A parameter is a variable listed inside the parentheses in the function
header. It acts as a placeholder for the value that will be passed into the
function when it is called.
Example:
def greet(name): # 'name' is a parameter
3. Argument:
An argument is the actual value passed to the function when it is called. It
replaces the parameter during the function’s execution.
Example:
greet("Alice") # 'Alice' is the argument passed to the parameter
'name'
Default Arguments
Parameters can have default values. If no argument is passed, the default value
is used.
Example:
def greet(name, age=25): # Here, 'age' has a default value of
25
print(f"Hello {name}, you are {age} years old.")
greet("Alice") # Since no age is provided, it uses the default
value 25
Keyword Arguments
The values are assigned to parameters by explicitly naming the parameter in the
function call.
Example:
def greet(name, age):
print(f"Hello {name}, you are {age} years old.")
greet(name="Alice", age=30) # Using keyword arguments
num = 5
modify(num)
print(num) # Output: 5
Q32) Can the argument have the same name as its parameter?
Yes, an argument can have the same name as its parameter in a function call.
The argument value will be passed to the parameter, which will then use it within
the function. However, the names are only relevant within the function's scope.
Example:
def greet(name): # 'name' is the parameter
print(f"Hello, {name}!")
Q33) What happens if you define two functions in a module that have
the same name?
If you define two functions in a module with the same name, the second function
will overwrite the first one. This is because Python allows only one function
definition per name within a given scope. When you call the function, Python will
use the most recently defined version.
Example:
def greet():
print("Hello from the first greet function!")
def greet():
print("Hello from the second greet function!")
greet() # Output: Hello from the second greet function!
x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20
Local Variable: A local variable is declared within a function or block and can
only be accessed and modified within that function or block.
Example:
def my_function():
# Local variable
y = 20 # This is a local variable
print(f"Inside function: y = {y}")
# Trying to access the local variable outside the function (will result in an
error)
# print(y) # Error: NameError: name 'y' is not defined
def modify_global():
global x # Use global variable 'x' inside the function
x = 20 # Modify the global variable
modify_global()
print(x) # Output: 20
Python doesn’t have a local keyword, but variables created inside a function are
local to that function by default.
Formal Parameters
Purpose: They define the structure of the function and are used to accept
values when the function is invoked.
Example:
return a + b
Definition: Actual parameters are the real values or expressions passed to the
function when it is called. These values are assigned to the corresponding formal
parameters when the function is executed.
Purpose: They provide the actual data that is processed by the function.
Example:
Main Example:
Return x * y
Print(result)
1. Numbers
Integers (int)
Floats (float)
Complex numbers (complex)
Booleans (bool)
Examples:
x = 10
s = "hello"
t = (1, 2, 3)
Key Insight:
Example of mutable:
list
dict
set