0% found this document useful (0 votes)
40 views25 pages

Python Control Statements & Functions Guide

This document is a question bank for the course 'Problem Solving Using Python' at Excel Engineering College, focusing on control statements and functions. It includes various questions related to conditional statements, iteration techniques, looping statements, function definitions, and recursion in Python. Each question is categorized by marks, course outcomes, and Bloom's levels, providing a structured approach to understanding Python programming concepts.

Uploaded by

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

Python Control Statements & Functions Guide

This document is a question bank for the course 'Problem Solving Using Python' at Excel Engineering College, focusing on control statements and functions. It includes various questions related to conditional statements, iteration techniques, looping statements, function definitions, and recursion in Python. Each question is categorized by marks, course outcomes, and Bloom's levels, providing a structured approach to understanding Python programming concepts.

Uploaded by

chithira84
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXCEL ENGINEERING COLLEGE

(Autonomous)
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
I Semester
23CS102 –problem solving using python

Regulations 2023
Question Bank
UNIT – IIICONTROL STATEMENT
AND FUNCTIONS
PART- A
[Link]. Questions Mar CO BL
ks
Define conditional statement and its types.

Conditional statements help you to make a decision based on


1 certain conditions. These conditions are specified by a set of conditional 2 CO3 R
statements having Boolean expressions which are evaluated to a Boolean
value of true or false.
Types.
 Conditional if or Simple if
 Alternative if… else
 Chained if…elif…else
 Nested if….else

Quote the rules for a conditional statement and define indentation.

Rules for a conditional statement


A conditional statement is a statement that can be written in the form “If
P then Q,” where P and Q are sentences. For this conditional statement, P is
2 called the hypothesis and Q is called the conclusion. Intuitively, “If P then Q” 2 CO3 R
means that Q must be true whenever P is true.
Indentation
 Python uses four spaces as default indentation spaces. However,
the number of spaces can be anything; it is up to the user. But a
minimum of one space is needed to indent a statement. The first
line of python code cannot have an indentation
Differentiate alternate IF statement and chained IF statement with examples.
3 2 CO3 U

Chained IF statement
Chained conditionals are simply a "chain" or a combination
or multiple conditions. We can combine conditions using the
following three key words:
and, or, not
food=input("What is your favorite food? ")
drink=input("What is your favorite drink? ")

iffood=="pizza"anddrink=="juice":
print("Those are my favorite as well!")
else:
print("One of those is not my favorite")

Label chained IF and nested IF, with necessary examples.

4 Chained IF
2 CO3 U
Chained conditionals are simply a "chain" or a combination or
multiple conditions. We can combine conditions using the
following three key words:
and, or, not
Example:
food=input("What is your favorite food? ")
drink=input("What is your favorite drink? ")
iffood=="pizza"anddrink=="juice":
print("Those are my favorite as well!")
else:
print("One of those is not my favorite")

Nested “if-else
 Nested “if-else” statements mean that an “if” statement or “if-else”
statement is present inside another if or if-else block. Python provides this
feature as well, this in turn will help us to check multiple conditions in a
given program.
 An “if” statement is present inside another “if” statement which is present
inside another “if” statements and so

Example:
answer=input ("What is your age? ")
ifint(answer)>=18:
answer=input("What country do you live in? ")
ifanswer=="canada":
print("Me as well!")
else:
print("Oh, I do not live there.")

What is an Iteration technique and spell about block of statements?

5 Iteration technique 2 CO3 R


 In Python, the iterative statements are also known as looping
statements or repetitive statements.
 The iterative statements are used to execute a part of the program
repeatedly as long as a given condition is true.
Block of statements
A block is a piece of Python program text that is executed as a unit.
The following are blocks: a module, a function body, and a class
definition. Each command typed interactively is a block.
List out the Looping statements.
The three types of looping statements are:
 while
6  for 2 CO3 R
 nested loop

State the Loop control statements.


i. break statement.
7 Break statements can alter the flow of a loop. It terminates the 2 CO3 R
currentLoop and executes the remaining statement outside the loop. If the
loop has else statement, that will also get terminated and come out of the
loop completely.
ii. continue statement.
It terminates the current iteration and transfer the control to the next
iteration in the loop.
iii. pass statement.
It is used when a statement is required syntactically but you don’t
want any code to execute. It is a null statement, nothing happens when it
is executed

Write a syntax (i) nested for loop, (ii) nested while loop.

8 (i) nested for loop 2 CO3 R


for condition1:
#statement()
for condition 2
# inside statement()
(ii)Syntax nested while loop
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop

Infer about Pass statement in Python.


9 2 CO3 R
 It is used when a statement is required syntactically but you don’t
want
any code to execute.
 It is a null statement, nothing happens when it is executed.

Define function and state the necessary syntax for it.


10  A function is a block of code which only runs when it is called. You 2 CO3 R
can pass data, known as parameters, into a function.
 In Python, you define a function with the def keyword, then write the
function identifier (name) followed by parentheses and a colon.
 The next thing you have to do is make sure you indent with a tab or 4
spaces, and then specify what you want the function to do for you.

Syntax
deffunctionName():
# What to make the function do
Compare built in function & user defined function with necessary examples.

 Functions that we define ourselves to do certain specific task are


11 2 CO3 U
referred as user-defined functions
 Functions that readily come with Python are called built-in functions.
If we use functions written by others in the form of library, it can be
termed as library functions.
Example
defadd_numbers(x,y):
sum=x+y
return sum
num=5
num=6
Print(“the sum is”,add_numbers(num1,num2))
 In above example Here, we have defined the
function my_addition() which adds two numbers and returns the
result. This is our user-defined function.
In above example print() is a built-in function in Python.
What are the arguments in python with examples?
 An argument is a value that is passed to a function when it is called.
12 It might be a variable, value or object passed to a function or 2 CO3 R
method as input.
 They are written when we are calling the function.
In Python, we have the following 4 types of function arguments.
 Default argument.
 Keyword arguments (named arguments)
 Positional arguments.
 Arbitrary arguments (variable-length arguments)

Does Python need function prototyping? Justify.


 Python does not have prototyping because you do not need it.
 Python looks up globals at runtime; this means that when you use
write Hello the object is looked up there and then.
13 2 CO3 AP
 The object does not need to exist at compile time, but does need to
exist at runtime.
What are the parameter passing mechanisms in Python?
 function with no argument and return value
 Function with no argument and with return value
 python function with argument and no return value
14  function with argument and return value 2 CO R
3

How do you return a value from a function in Python?


 return statement is used to end the execution of the function call and
“returns” the result (value of the expression following the return keyword)
to the caller.
 The statements after the return statements are not executed. If the return
15 statement is without any expression, then the special value none is CO AP
returned. 2 3
 A return statement is overall used to invoke a function so that the passed
statements can be executed.
Syntax: example
def fun(): defcube(x)
statements r=x**3
……… return r
return [expression]
Does a global variable supersede local variable? Can a variable be both local &
global?
 LOCAL variables are only accessible in the function itself., so
the GLOBAL variable would supersede the LOCAL variable
16.  Global variables are the types of variables that are declared outside of every 2 CO3 AP
function of the program. The global variable, is accessible by all functions
in a program.
 Yes can a variable be both local &global

What is recursion in Python and write the limitation?


 The function calls itself infinitely called recursion.
17.  The Python interpreter limits the depths of recursion to help avoid infinite 2 CO3 R
recursions, resulting in stack overflows. By default, the maximum depth of
recursion is 1000 .

Write syntax for function composition with necessary examples.


 Function composition is the way of combining two or more functions in
such a way that the output of one function becomes the input of the second
18. function and so on. 2 CO3 U
 For example, let there be two functions “F” and “G” and their composition
can be represented as F(G(x)) where “x” is the argument and output of
G(x) function will become the input of F() function.

Example:
def add(x):
return x + 2

def multiply(x):
return x * 2

print("Adding 2 to 5 and multiplying the result with 2: ",


multiply(add(5)))

Output:
Adding 2 to 5 and multiplying the result with 2: 1
Explanation
First the add() function is called on input 5. The add() adds 2 to the input
and the
output which is 7, is given as the input to multiply() which multiplies it by 2 and
the output is 14
Define range() function.
The range() function returns a sequence of numbers, starting from 0 by
default, and increments by 1 (by default), and stops before a specified number.
19. range (start, stop, step) 2 CO3 R
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
Output:3 4 5
Define Lambda function in Python. 2 CO3 R
 A lambda function is a small anonymous function.
20.  A lambda function can take any number of arguments, but can only have
one expression.
 lambda arguments : expression

x = lambda a : a + 10
print(x(5))

PART B

Q. Questions Ma CO BL
No. rk
s
1 a) Discuss conditional statement with necessary details.(08)

 A conditional statement is used to determine whether a certain condition


exists before code is executed.
 Conditional statements can help improve the efficiency of your code by
providing you with the ability to control the flow of your code, such as
when or how code is executed. 8 CO3 U
 This can be very useful for checking whether a certain condition exists
before the code begins to execute, as you may want to only execute
certain code lines when certain conditions are met.
 For example, conditional statements can be used to check that a certain
variable or file exists before code is executed, or to execute more code if
some criteria is met, such as a calculation resulting in a specific value.

Types of Conditional Statements


1. Conditional if
2. Alternative if… else
3. Chained if…elif…else
4. Nested if….else

[Link] (if):
Conditional (if) is used to test a condition, if the condition is true the
statements inside if will be executed.
Syntax:
if(condition 1):
Statement 1
Flowchart:

Example
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
Program to provide flat rs 500, if the purchase amount is greater than 2000.
Program:
purchase=eval(input(“enter your purchase amount”))
if(purchase>=2000):
purchase=purchase-500
print(“amount to pay”,purchase)
Output:
enter your purchase
amount
2500
amount to pay
2000

2. Alternative (if-else)

 In the alternative the condition must be true or false. In this else statement
can be combined with if statement.
 The else statement contains the block of code that executes when the
condition is false.
 If the condition is true statements inside the if get executed otherwise else
part gets executed. The alternatives are called branches, because they are
branches in the flow of execution.

Syntax:
if(condition 1):
Statement 1
else:
statement 2
Flowchart:

Examples:
1. Odd or even number
Program
n=eval(input("enter a number"))
if(n%2==0):
print("even number")
else:
print("odd number")
Output
enter a number4
even number

Chained conditionals(if-elif-else)

 The elif is short for else if.


 This is used to check more than one condition.
 If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions
are False, then the else part is executed
 Among the several if...elif...else part, only one part is executed according to
the condition.
 The if block can have only one else block. But it can have multiple elif
blocks.
 The way to express a computation like that is a chained conditional.
Syntax:
if(Condition):
statement 1
elif(condition):
statement 2
elif(condition 3):
statement 3
else:
default statement
Flowchart:

Example:

Compare two numbers


Program
x=eval(input("enter x value:"))
y=eval(input("enter y value:"))
if(x == y):
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Output
enter x value:5
enter y value:7
x is less than y
Nested conditionals
 One conditional can also be nested within another. Any number of condition
can be nested inside one another. In this, if the condition is true it checks
another if condition1.
 If both the conditions are true statement1 get executed otherwise statement2
get execute.
 if the condition is false statement3 gets executed

Syntax:

If(condition):
If(condition 1):
Statement 1
else:
statement
else:
statement

Flowchart:

Exampe:
1. greatest of three numbers
Program
a=eval(input(“enter the value of a”))
b=eval(input(“enter the value of b”))
c=eval(input(“enter the value of c”))
if(a>b):
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
Output
enter the value of a 9
enter the value of a 1
enter the value of a 8

b) Discuss chained conditional statement in detail.(08)

 The Python elif statement stands for “else if”. It used to evaluate multiple
expression and choose from one of several different code paths. It is always
used in conjunction with the if statement ,and is sometimes referred to as a
chained condition
 The python first evaluates the if conditional. If the if conditional is false, 8 CO3 U
python inspects each elif conditional in sequential order until one of them
evaluates to [Link] then runs the corresponding elif code
 block if all the elif conditionals are false python does not run any of the elif
code blocks
 A sequence of elif statements can be followed bye followed by optional else
directive, which terminates the chain. the else code block is only executed
when the if conditional and all elif conditions are false. there is no limit to
the number of elif expressions that can be used, but only one code block can
be executed
 The python if elif statement follows this template. the final else directive
and code block are optional

Syntax
If Boolean expression 1:
Statement 1
elif Boolean expression 2:
statement 2
elif Boolean expression 3:
statement 3
Example
x=50
y=75
If x< y:
Print(“x is less than y”)
Elif x>y:
Print(“x is greater than y”)
else:
Print(“x and y must be equal”)

2 Explain in detail about iterations. Write a suitable Python program using


Looping statement.

While loop:
16 CO3 AP
 While loop statement in Python is used to repeatedly executes set of
statement as long as a given Condition is true.
 In while loop, test expression is checked first. The body of the loop is
entered only if the test expression is True. After one iteration, the test
expression is checked again. This process continues until the test
expression evaluates to False.
 In Python, the body of the while loop is determined through indentation.
 The statements inside the while start with indentation and the first
unindented line marks the end.
Syntax:
initial value
while (Condition):
body of While loop
increment
Flowchart

Examples:
Sum of n numbers:
n=eval(input("enter n"))
i=1
sum=0
while(i<=n):
sum=sum+i
i=i+1
print(sum)

output
enter n
10
55
For loop:
for in range:
 We can generate a sequence of numbers using range() function. range(10) will
generate numbers from 0 to 9 (10 numbers).
 In range function have to define the start, stop and step size as
range(start,stop,step size). step size defaults to 1 if not provided.

Syntax:
for i in range(start,stop,steps):
body of for loop
Flowchart:

For in sequence
 The for loop in Python is used to iterate over a sequence (list, tuple, string).
 Iterating over a sequence is called traversal. Loop continues until we reach the
last element in the sequence.

The body of for loop is separated from the rest of the code using indentation.
for i in sequence:
print(i)

Sequence can be a list, strings or tuples

Examples
Print nos divisible by 5 not by 10
n=eval(input("enter a"))
for i in range(1,n,1):
if(i%5==0 and i%10!=0):
print(i)
output
enter a:30
5
15
25
3. Summarize various loop control statement in detail. Explain it with necessary
example.

 BREAK
 Break statements can alter the flow of a loop.
 It terminates the current 16 CO3 AP
 loop and executes the remaining statement outside the loop.
 If the loop has else statement, that will also gets terminated and come out of the
loop completely.

Syntax:
Break

Flowchart
Example
for i in "welcome":
if(i=="c"):
break
print(i)
output
w
e
l

CONTINUE
It terminates the current iteration and transfer the control to the next iteration in the
loop.
Syntax:
Continue
Example:
for i in "welcome":
if(i=="c"):
continue
print(i)

Output
w
e
l
o
m
e

PASS
 It is used when a statement is required syntactically but you don’t want any
code to execute.
 It is a null statement, nothing happens when it is executed.
Example
for i in “welcome”:
if (i == “c”):
pass
print(i)
Output
w
e
l
c
o
m
e
Difference between break and continue

4 Brief the types of function. Explain user define function with an example.

Function
 A function is a set of statements that take inputs, do some specific
computation task and produce output.
 The idea is to put some commonly or repeatedly done tasks together 16 CO3 AP
and make a function so that instead of writing the same code again and
again for different inputs, we can call the function.
Types of function
1. Build in functions or Standard libray functions
Functions that readily come with Python are called built-in functions.
Python provides
built-in functions like print(), etc
2. User defined functions
But we can also create your own [Link] on our requirements These
functions are known as user definedfunctions.

User Defined Functions

Advantages of user-defined functions


 User-defined functions help to decompose a large program into small
segments which makes program easy to understand, maintain and
debug.
 If repeated code occurs in a program. Function can be used to include
those codes and execute when needed by calling that function.
 Programmers working on large project can divide the workload by
making different functions.
Function have two parts
 Function declaration
 Function call
Function Declaration
 In Python, a user-defined function's declaration begins with the keyword
def and followed by the function name.
 The function may take arguments(s) as input within the opening and
closing parentheses, just after the function name followed by a colon.
 After defining the function name and arguments(s) a block of program
statement(s) start at the next line and these statement(s) must be
indented
Syntax:

deffunction_name(argument1,argument2,…):

Statement_1

Statement_2

………..

…………

return

Here,

 def - keyword used to declare a function


 function_name - any name given to the function
 arguments - any value passed to function
 return (optional) - returns value from a function

Let's see an example,


def greet():
Print(‘Hello world’)

 Here, we have created a function named greet(). It simply prints the


text Hello World!.
 This function doesn't have any arguments and doesn't return any values.
Function call

Calling a function in Python is similar to other programming languages,

using the function name, parenthesis (opening and closing) and


parameter(s).

See the syntax, followed by an example.

Syntax:
function _name (arg1,arg2)

 In the above example, we have declared a function


named greet().Now, to use this function, we need to call it.
 Here's how we can call the greet() function
#call the function
greet()

Example
def greet():
Print(‘Hello world’)
# call the function
greet()
Print(‘outside function’)
Output
Hello world
Outside function
 In the above example, we have created a function named greet().
Here's how the program works:

 Here,

 When the function is called, the control of the program goes to the
function definition.
 All codes inside the function are executed.
 The control of the program jumps to the next statement after the function
call.

5 a) Discuss function arguments in Python.(08) 8 CO3 AP

Types of Python Function Arguments


1. Default Argument in Python:
 Python Program arguments can have default values. We assign a default
value to an argument using the assignment operator in python(=).
 When we call a function without a value for an argument, its default
value (as mentioned) is used.

Example:
def greeting(name='User'):
print(f"Hello, {name}")
greeting('Ayushi')
Output:
Hello, Ayushi
2. Python Keyword Arguments
 With keyword arguments in python, we can change the order of passing
the arguments without any consequences.
 Let’s take a function to divide two numbers, and return the quotient.

Example:
def divide(a,b):
return a/b
divide(3,2)
output:
1.5
3. Python Arbitrary Arguments:
 You may not always know how many arguments you’ll get. In that case,
you use an asterisk(*) before an argument name.
Example:
defsayhello(*names):
for name in names:
print(f"Hello, {name}")

sayhello('Ayushi','Leo','Megha')

Output:
Hello, Ayushi
Hello, Leo
Hello, Megha
5 b) Explain the parameter passing in function with suitable examples.(08)
 The terms parameter and argument can be used for the same
thing: information that are passed into a function.
 A parameter is the variable listed inside the parentheses in the function
definition. An argument is the value that are sent to the function when it
is called. 8 CO3 U
Types of parameter passing in user defined function
1. Function with no argument and with return value
2. Functionwith argument and no return value
3. Function with no argument and no return value
4. Functionwith argument and return value

1. Function with no argument and with return value


Example
def add():
a=20
b=30
sum=a+b
print(“after calling function:”sum)
add()
Output
After calling function:50

2. Functionwith argument and no return value


def add(a,b):
sum=a+b
print(“result:”sum)
add(20,30)
Output
result:50
The result is print within the function

3. Function with no argument and return value


def add():
a=20
b=30
sum=a+b
return sum
z=add(10,30)
print(“result:”z)
Output
result:50

Here we are not passing any value to the parameters to the function instead
values are assigned with in the function ,but result is return to the calling
function

4. Functionwith argumentand return value


def add(a,b):
sum=a+b
return sum
z=add(20,30)
print(“result:”z)
Output
result:50
Here we passing two values to the parameter a,b to the function.
function is calculating
Sum of these values and return to the calling statement which is stored in
the variable z

6. Describe in detail about Recursion and Write a Python program to find the
factorial of
the given number.
Recursion
 Python, we know that a function can call other functions.
 It is even possible for the function to call itself. These types of construct
are termed as recursive functions.
 The following image shows the working of a recursive function 16 CO3 AP
called recurse.
 A function calling itself till it reaches the base value - stop point of
function call

Example: factorial of a given number using recursion


x=factorial (3)
def factorial(x):
if x == 1:
return 1
else:
return (x * factorial(x-1))
print("The factorial of", num, "is", factorial(x))

Working of a recursive factorial function


Our recursion ends when the number reducess to 1. This is called the base
condition.

(Note:*Blooms Level (R – Remember, U – Understand, AP – Apply, AZ – Analyze, E – Evaluate, C


– Create)
PART A- Blooms Level : Remember, Understand, Apply
PART B- Blooms Level: Understand, Apply, Analyze, Evaluate(if possible)
Marks: 16 Marks, 8+8 Marks, 10+6 Marks)

Subject Incharge Course Coordinator HOD


IQAC (Name & Signature) (Name & Signature)

You might also like