0% found this document useful (0 votes)
13 views19 pages

Chapter 5+6+7

Uploaded by

mua347175
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

Chapter 5+6+7

Uploaded by

mua347175
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

Chapter 5

Q1) What is ord function use for?


The ord() function in Python is used to get the Unicode code point (integer
representation) of a character.
The ord() function takes a single character (a string of length 1) as an
argument and returns its Unicode code point (an integer)
Example:
char = 'A'
unicode_value = ord(char)
print(unicode_value) # Output: 65

Q2) What is ASCII?


ASCII is a character encoding standard that represents text in computers using
numbers. Each character (letters, digits, punctuation) is assigned a unique
number between 0 and 127.
You can use the ord() function to get the ASCII value of a character:
Example:
char = 'A'
ascii_value = ord(char)
print(ascii_value) # Output: 65
Using chr():
To convert an ASCII value back to a character, you can use the chr() function.
Example:
ascii_value = 65
character = chr(ascii_value)
print(character) # Output: 'A'

In the ASCII character set:


 Lowercase letters: a to z are assigned values from 97 to 122.
 Uppercase letters: A to Z are assigned values from 65 to 90.
 Digits: 0 to 9 are assigned values from 48 to 57.
Q3) What does eval function do?
The eval() function in Python takes a string of Python code, evaluates or
executes it, and returns the result of the expression (if any).
Example:
result = eval("3 + 4") # Evaluates "3 + 4" and returns 7
eval("print('Hello!')") # Executes the print statement,
output: Hello!

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.

Q5) List the advantages of using while loops.


Here are the advantages of a while loop in very short terms:
1. Flexible: Runs as long as the condition is true.
2. User-Controlled: Stops based on user input or changing conditions.
3. Stops Early: Exits as soon as the condition is false.
4. Simple: Easy for tasks with unknown iterations.
5. Infinite Loops: Useful for continuous tasks.
6. Dynamic: Condition can change during the loop.

Q6) What is Loop, Type of Loop Statements in Python.


A loop in Python is a way to repeat a block of code multiple times. It’s useful
when you want to perform the same action several times without writing the
same code over and over.
There are two types of loop statements in Python language. They are,

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

Q8) How can we generate a random number?


You can generate random numbers using the random module.
1) Generate a random integer:
import random
random_number = random.randint(1, 10) # Generates a random integer
between 1 and 10

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)

Q9) What is wrong in the following code?

if score >= 60.0:


grade = 'D'
elif score >= 70.0:
grade = 'C'
elif score >= 80.0:
grade = 'B'
elif score >= 90.0:
grade = 'A'
else:
grade = 'F'
The conditions in the elif blocks should check for higher values first, so the
conditions must be reordered, but in this code, they check for lower scores after
the first condition.
if score >= 90.0:
grade = 'A'
elif score >= 80.0:
grade = 'B'
elif score >= 70.0:
grade = 'C'
elif score >= 60.0:
grade = 'D'
else:
grade = 'F'

Q10) Rewrite the following statement using a Boolean expression:


if count % 10 == 0:
newLine = True
else:
newLine = False

You can rewrite the given if statement using a Boolean expression like this:
newLine = (count % 10 == 0)

Q11) Are the following two statements equivalent?

if income <= 10000: if income <= 10000:


tax = income * 0.1 tax = income * 0.1
elif income <= 20000: elif income > 10000 and
tax = 1000 + \ income <= 20000:
(income - 10000) * tax = 1000 + \
0.15 (income - 10000) *
0.15
ANS: YES, its correct ANS: No, in line 3 you must
place \ or write the full
condition in one line

Q12) What is wrong in the following code?


income = 232323
if income <= 10000:
tax = income * 0.1
elif income > 10000 and income <= 20000:
tax = 1000 + (income - 10000) * 0.15
print(tax)

In line no 4 use or instead of and.

Q13) Write a Boolean expression that evaluates to True if variable num


is between 1 and 100.
num=101
x= 1<= num <= 100
print(x)

Q14) Write a Boolean expression that evaluates to True if variable num


is between 1 and 100 or the number is negative.
num=0
x= 1<= num <= 100 or num<0
print(x)

Q15) Are the following expressions equivalent?


(a) (x >= 1) and (x < 10)
(b) (1 <= x < 10)

Yes, both are correct because.


Explanation:
 In expression (a):
o (x >= 1) checks if x is greater than or equal to 1.

o (x < 10) checks if x is less than 10.

o And operator ensures both conditions must be true for the


entire expression to be true.
 In expression (b):
o (1 <= x < 10) is a shorthand form in Python that checks
if x is between 1 (inclusive) and 10 (exclusive).
o It implicitly combines both conditions: x >= 1 and x <
10.
Q16) Assuming x 4 and y 5, show the result of the following Boolean
expressions:
x >= y >= 0
x <= y >= 0
x != y == 5
(x != 0) or (x == 0)

1) False 2)True 3)True 4) True

Q17) What is meant by control structure? (EXTRA)


A control structure is a block of programming that analyzes variables and
chooses a direction in which to go based on given parameters. The term is often
used in reference to functions, loops, if statements, and other programming
structures that determine the flow of a program based on conditions or variables.

MORE PROGRAMMING EXPRESIONS AND QUESTION ON PAGE NO 133,


136 AND 138

Chapter 6

PROGRAMMING EXPRESIONS AND QUESTION ON PAGE NO 162, 163, 146,


169, 173

Q18) What does break and continue keywords do?


The break and continue keywords are used to control the flow of loops. Here's
what each one does:
break: Exits the loop completely, stopping it before it finishes all iterations. In
nested Loops, if break statement is inside an inner loop, it will terminate the
inner most loop. If it’s inside an outer loop, it will terminate both inner and outer
loop.
Example:
for i in range(1, 6):
if i == 3:
break # Stops the loop when i is 3
print(i)
Output:
1
2
continue: Skips the rest of the current loop iteration and moves to the next one.
Loop does not terminate but continues on with the next iteration.
Example:
for i in range(1, 6):
if i == 3:
continue # Skips printing 3
print(i)
Output:
1
2
4
5

Q19) What is sentinel loop?


A sentinel loop is a loop that continues executing until it encounters a special
value (called a sentinel value) that signals the end of the loop. The sentinel value
is used to terminate the loop.
Example:
while True:
user_input = input("Enter something (or type 'quit' to stop): ")
if user_input == "quit":
break # Exits the loop when 'quit' is entered
print("You entered:", user_input)

Chapter 7

PROGRAMMING EXPRESIONS AND QUESTION ON PAGE NO 179, 180, 183,


188, 189, 190, 192
Q20) What is a function?
A function is a block of code that performs a specific task and can be called by
name from other parts of the program. Functions provide modularity, making the
code easier to manage and reuse. A function consists of, Function name,
Parameters (optional), Body, and Return (optional).
Syntax:
def function_name(parameters):
# Function body
# Code to execute
return value # Optional return statement
Example:
def greet(name):
print(f"Hello, {name}!")

greet("Alice") # Calling the function with the argument


"Alice"

Q21) What are parameters?


Parameters are variables defined inside the parentheses in a function definition.
They allow you to pass values (called arguments) into the function when it is
called, so the function can use those values to perform its task.
Example:
def greet(name): # 'name' is the parameter
print(f"Hello, {name}!")

greet("Alice") # "Alice" is the argument passed to the parameter


'name'

Q22) What are the benefits of using a function?


Modularity: Breaks code into smaller, manageable parts.
Reusability: Allows code to be used multiple times.
Abstraction: Hides complex details behind a simple name.
Easier Debugging: Makes it easier to find and fix errors.
Improved Readability: Makes code clearer and more organized.
Separation of Concerns: Organizes different tasks in the program.

Q23) How do you define a function? How do you invoke a function?


In Python, you define a function using the def keyword, followed by the function
name, parentheses (which may include parameters), and a colon. The code
inside the function is indented.
Example:
def greet(name): # 'name' is a parameter
print(f"Hello, {name}!") # Function body

The function can be invoked by calling its name with arguments in parentheses.
Example:
greet("Alice")

Q24) What are Default Arguments?


Default arguments in Python are values that are assigned to function parameters
if no argument is provided when the function is called. These default values are
specified in the function definition
Example:
def greet(name="Guest"):
print(f"Hello, {name}!")

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


greet() # Output: Hello, Guest!

Q25) What is Function Abstraction?


Function Abstraction hides the implementation details of a function and only
shows its behavior. It allows the user to focus on what the function does, not how
it does it.
Example:
def add(a, b):
return a + b
result = add(5, 3) # Only know it adds numbers, not how

Q26) True or false? A call to a None function is always a statement


itself, but a call to a value-returning function is always a component of
an expression.
True.
 A call to a None-returning function (a function that doesn't return
anything, or explicitly returns None) is treated as a statement. For
example, calling a function that performs an action like printing something
is a statement.
 A call to a value-returning function (a function that returns a value) is
considered part of an expression. The returned value can be used in
further calculations or assignments.
Example:

def print_hello():
print("Hello")

def add(a, b):


return a + b

# print_hello() is a statement
print_hello()

# add(3, 4) is part of an expression


result = add(3, 4)

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).

Q28) Define the term’s function header, parameter, and argument.


1. Function Header:
 The function header is the first line of a function definition, which defines
the function’s name and its parameters (if any). It includes the def
keyword, followed by the function name, parentheses, and a colon.
Example:
def greet(name): # 'def greet(name):' is the function header

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'

Q29) How many ways we can pass arguments in a function?


You can pass arguments to a function in the following ways:
Positional Arguments
The values are assigned to parameters based on their position in the function
call.
Example:
def greet(name, age): #this function expects two arguments: name
and age
print(f"Hello {name}, you are {age} years old.")
greet("Alice", 30)# Here, "Alice" is assigned to 'name' and 30 is assigned to
'age'

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

Q30) Compare positional arguments and keyword arguments.

Feature Positional Keyword


Arguments Arguments
Passing Based on the position of Based on the parameter
Method the arguments. names.
Must match the order of
Order Order doesn't
parameters in the
Requirement matter.
function definition.
More readable, as it specifies
Readabilit Can be less clear if many
which value goes to which
y arguments are passed.
parameter.
Flexibilit Less flexible when calling More flexible, especially with
y the function. many parameters.

Q31) What is pass-by-value?


Pass-by-value means passing a copy of the original value to the function.
Changes made to the parameter inside the function do not affect the original
variable outside the function.
In Python, this applies to immutable types (e.g., integers, strings), where
changes inside the function don't modify the original value.
Example:
def modify(x):
x = 10 # x is reassigned, but this doesn't affect the original
variable.

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}!")

name = "Alice" # 'name' is the argument


greet(name) # 'name' is passed as an argument

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!

Q34) Can a function return multiple values?


Yes, a function in Python can return multiple values. You can achieve this by
returning a tuple, list, or any other collection type that holds multiple values.
Example:
def get_coordinates():
x = 10
y = 20
return x, y # Returning multiple values as a tuple
coords = get_coordinates()
print(coords) # Output: (10, 20)
You can also unpack the returned values:

x, y = get_coordinates()
print(x) # Output: 10
print(y) # Output: 20

Q35) Define None Value.


None is a special value in Python that represents the absence of a value or
"nothing." It is the default return value for functions that don't explicitly return
anything.
OR
A function that does not return a value is called a void function or a
procedure. In Python, such functions implicitly return None if there is no explicit
return statement
Example:
def sum(number1, number2):
total = number1 + number2 print(sum(1, 2)) # Output:
None

Q36) Scope of Variables, Differentiate between Global Variables and


Local Variables.
The scope of a variable refers to the part of the program where the variable can
be accessed or modified.
Global Variable: A global variable is declared outside of any function and can
be accessed and modified by any part of the program.
Example:
x = 10 # This is a global variable
def display_global(): # Accessing global variable inside a
function
print(f"Inside function: x = {x}") # Calling the
function
display_global()
print(f"Outside function: x = {x}") # Output: Outside function: x
= 10

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}")

# Calling the function


my_function() # Output: Inside function: y = 20

# Trying to access the local variable outside the function (will result in an
error)
# print(y) # Error: NameError: name 'y' is not defined

Q37) What is global keyword?


The global keyword is used inside a function to refer to a global variable.
It allows a function to modify a global variable, rather than creating a local
variable with the same name.
Without global, a variable inside a function would be considered local, and you’d
need to initialize it within the function to modify it.
Example:
x = 10 # Global variable

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.

Q38) What are formal and actual parameter?

Formal Parameters

Definition: Formal parameters are the variables defined in the function


signature (or declaration). They are essentially placeholders that specify what
kind of data the function expects to receive when it is called.

Purpose: They define the structure of the function and are used to accept
values when the function is invoked.

Example:

def add(a, b): # 'a' and 'b' are formal parameters

return a + b

Actual Parameters (or Arguments)

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:

Result = add(5, 3) # ‘5’ and ‘3’ are actual parameters (arguments)

Main Example:

Def multiply(x, y): # ‘x’ and ‘y’ are formal parameters

Return x * y

Result = multiply(4, 6) # ‘4’ and ‘6’ are actual parameters


(arguments)

Print(result)

Q39) Immutable object.

In Python, an immutable object is one whose state cannot be modified after it is


created. Any changes result in the creation of a new object rather than
modification of the original one. Here are some common immutable types in
Python:

1. Numbers

 Integers (int)
 Floats (float)
 Complex numbers (complex)
 Booleans (bool)

Examples:

x = 10

x += 1 # Creates a new int object; the original `10` remains unchanged.

s = "hello"

s += " world" # Creates a new string object; the original "hello" is


unchanged.

t = (1, 2, 3)

t[0] = 0 # Error: tuples are immutable.


t = (1, [2, 3]) # The list inside can still be modified.

t[1][0] = 10 # This works.

Key Insight:

 The object 10 was never changed. Instead:


 A new object (11) was created.
 The variable x was updated to refer to the new object

Example of mutable:

 list
 dict
 set

You might also like