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

Python Uint III QB

Uploaded by

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

Python Uint III QB

Uploaded by

sakthivelv.eec
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

EXCEL ENGINEERING COLLEGE

(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Accredited by NBA, NAAC with “A+” and Recognised by UGC (2f &12B)
KOMARAPALAYAM – 637303
Department of Electronics and Communication Engineering
23CS102 - Problem solving using Python
Regulation 2023
UNIT – 3 (Conditional Statements and Functions)

1. Define Conditional statement.


 The statement used for decision making is called as conditional statement.
 This is also known as conditional constructs or conditional expression.

2. List the types of conditional statements.


 if statement
 if…else statement
 if…elif..else statement

3. Quote the rules for conditional statements.


 The colon is required [:] at the end of statement
 Four spaces required for indentation

4. Draw the flowchart for if condition.

Test True
Condition

True condition
statements
False

5. Give the syntax for chained if statement.


Syntax:
if condition1:
True statement block
elif:
True statement block
else:
True statement block
5. List out the looping statements.
 while
 for
 nested loop

6. What are the loop control statements?


 Break
 Continue
 Pass

7. Write a program for “break” statement.

for letter in “mech_class”:


if letter==’_’:
break
print(“currentletter:”,letter)
Output:
currentletter: m
currentletter: e
currentletter: c
currentletter: h

8. Tell about pass statement.


 It is used to pass control to the next statement
 It is a null operation.

9. Define function.
 Functions are group of related statements that perform specific task.
 Function avoids repetition and makes code reusability.

10. State the syntax for function.


def function_name(parameters):
set of statements
return statement

11. Illustrate an example program for if elif.


num= 3
if num>0:
print(“num is positive”)
elif num=0:
print(“num is zero”)
else:
print(“num is negative”)
Output:
num is positive

12. Illustrate an example for iteration statement


fruits = ["apple", "banana", "cherry"]for x in fruits:
print(x)
Output:
apple
banana
cherry
13. List different types of function.
 Built-in function
 User defined function

14. Define user-defined functions.


 A function is a block of code which defined by the user.
 Parameters can be passed to a function .A function can return value.

15. Identify some of the built-in functions.

 print( ) function.
 min( ) function.
 max( ) function.
 count( ) function.

16. List out types of argument to a function.


 Required
 Keyword
 Default
 Variable length

17. Tell about variable length argument.


 Arbitrary number of arguments
 By placing * as a prefix to the argument of function definition

18. Infer about recursion.


 Function calling itself
 Function iterates until condition is satisfied

19. Define lambda function.


o A lambda function is a small anonymous function.
o A lambda function can take any number of arguments, but can only have oneexpression.

20. Illustrate program for passing parameters to afunction.


def sum(x, y):
print("sum= ", x+y)
sum(10,20)
output:
sum=30

PART – B

1(a). Discuss conditional alternative statements in detail.


(if and if-else)
Conditional statements:
 The statements used for decision making are called as ‘Conditional statements,’ they also know as the
conditional expressions or conditional construct.
Types of Conditional checking statements:
 Python programming language provides the following types of conditional checking statements.
if statements
if-else statements
if statement:
 In “ if ” statements, the test expression is evaluate first, if the test expression is “ True”, the statements
which are indented and below ‘if’ structure are executed.
 If the test expression is “False”, the control will flow to the next statement after the ‘if’ statement.
Syntax
if test_expression:
statement(s)

Example Program
num=3
if num>0;
print(num, “is a positive no”)
print(“This is always printed”)
num = -1
if num>0;
print(num, “ is a positive no”)
print(“This is also always printed”)
Output:
3 is a positive no
This is always printed
This is also always printed
if else statement:
 The if_else statement evaluates test condition and executes the true statement
block only when test condition is True.
 If the condition is False, false statement block or else part is executed.
 Indentation is used to separate the blocks.

Syntax
if test expression:
body of if
else:
body of else

Example Program
#pgm checks if the no is + or –
#displays an appropriate msg

num=3
if num>=o;
print (“The number is positive”)
else:
print (“The number is negative”)

Output
n=3
The number is positive
1(b). Discuss the chained conditional in detail. (if-elif-else and nested if)
if-elif-else Statement
Explanation:
 The elif is short form of else if
 It is used to check multiple conditions
 If the condition 1 is false, it checks condition 2 of the next elif block and so on.
Syntax
if condition 1:
True statement Block for condition 1
elif condition 2:
True statement Block for condition 2
elif condition 3:
True statement Block for condition 3
else
False statement Block

Example Program

num=3
if num>0:
print(“positive num”)
elif num==0:
print(“Zero”)
else:
print(“Negative num”)
Output
Positive number

Nested if statement
 A conditional statement can be written in another conditional statement is called nested condition.
 Any number of conditional statements can be nested with in another conditional statement
Syntax
if condition 1:
if condition 2:
True statement Block for condition 2
else3:
else statement
if condition3:
True statement Block for condition 3
Example
A=3,b=4,c=5
If(a>b):
If(a>c):
Print “ A is greater”
Else:
Print : C is greater”
Elif(b>c):
Print “ B is greater”
Else:
Print “ C is greater”
Output
C is greater

2(a). Explain in detail about iterations. Write a Python program to find sum of n numbers using while
Looping statement
1. while loop statement
2. for loop statement
While loop statement:
 The while loop in python iterates over a block of statements as long as the test condition
is true.
 The statement body is entered only when the test condition is true.
 After 1’st iteration, the test condition checked again
 The process continues until the test condition evaluate false.
Syntax
while condition :
statement_1
……
statement_n
example
i=1
while i<=3:
print “Hello world”
i=i+1
output
Hello world
Hello world
Hello world
for loop statement:
 The for loop in python is used to iterate over a sequence of value.(list, tuple, string)
 Iterating over a sequence of item is called traversal.
Syntax
For value in sequence:
Body of for loop
For value in range();
Body of for loop
example

fruits =[“apple”,”banana”,”cherry”]
for x in fruits:
print(x)
output
apple
banana
cherry
sum of n numbers
num = int(input("Enter a number: "))
if num < 0:
print("Enter a positive number")
else:
sum = 0
while(num > 0):
sum += num
num -= 1
print("The sum is",sum)

2(b). Summarize various looping controlling statement in detail. Explain it with example (break, cont and
pass)
Break statement:
 The break statement in python terminates the current loop before it has looped through all the items.
Syntax
break
Example
fruits =[“apple”,”banana”,”cherry”]
for x in fruits:
if x==”banana”:
break
print(x)
output
apple

Continue statement:
 The continue statement stop current iteration of loop and continue with the next.
 The continue statement rejects all the remaining statements in the current iteration of
the loop.
 And moves the control back to the top of the loop.
Syntax
continue
Example
fruits =[“apple”,”banana”,”cherry”]
for x in fruits:
if x==”banana”:
continue
print(x)
output
apple
cherry

Pass statement:
 For empty loop pass statement is used to avoid error
 The pass statement is a null operation, it just passes the control.
Syntax
pass
Example
for x in [0,1,2]:
pass
output
No output

3(a). Brief the types of function. Explain user define function with example.
Types of function
Built-in functions:
 Built-in functions are the functions that are already written or defined in python.
 Python interpreter has number of function that are always available for use.
 Example
len() It returns the length of an object/value.
list() It returns a list.
max() It is used to return maximum value from a sequence (list,sets) etc.
User define function:
 The user-defined functions are those define by the user to perform the specific task.
 Parameters are the names used when defining a function or a method, and into which arguments will be
mapped.
Creating a Function
 Python provides the def keyword to define the function
 The function block is started with the colon (:), and block statements must be at the same indentation.
 A function accepts the parameter (argument), and they can be optional.
Syntax of a User Defined Function:
def my_function(parameters):
function_block
return expression
Function call
 After the function is created, we can call it from another function
Syntax
my_function(parameters):
Example
Sum of two numbers using function
def add(a,b):
sum=a+b;
return sum;
x=int(input("input the number one: "))
y=int(input("input the number one :"))
print("The sum is",add(x,y))
output
input the number one: 3
input the number one: 4
The sum is 7

3(b). Explain in detail about function and parameter passing in function with suitable example.
Function
 A function is a group of related statements that performs a specific task.
 Functions help to break large program into smaller programs are called subprograms.
 Each sub programs are called as function.
Parameter passing
 Required Arguments ------> No of Arguments should be same in both F. call & F.def order
position should be followed.
eg: def display (a, b) :------> Function Definition(2)
Print(a, b) --------->10, 20
20, 10
display (20, 10) ----------> Function call (2)
 Key word Arguments -------> Order /position is not required
Initialization will be done based on keyword(name)
eg: def display (a, b):
print(a, b) -------> 10, 20
display (b=20, a=10)
 Default Arguments ----->No of arguments need not be match with both F. call &F.def
Some of arguments will be consider as default arguments
eg: def display(name, course=”B. tech”):
Print (name)
Print(course)
display (name=”abc”, course=”M. Tech”)
display (name=”PQR”)

Output:
abc
M.tech
PQR
B.Tech
 Variable length Arguments -----> Arbitrary no of Arguments by placing as *prefix
to the argument of F.Definition
eg: def display (*courses):
for i in courses
Print (i)
display (“B. Tech”, “M. Tech”,”MCA”,”MBA”)

4(a). Describe in detail about Recursion and write a Python program to find the factorial of the given
number
 A process in which a function calls itself directly or indirectly.
 Also, a recursive function needs to have a condition to stop calling itself
Advantage
 A complicated function can be split down into smaller sub-problems utilizing recursion.
 Sequence creation is simpler through recursion than utilizing any nested iteration.
 Recursive functions make the code look simple and effective.

Factorial of the given Number

def factorial(n):

if (n==1 or n==0):

return 1

else:

return (n * factorial(n - 1))


num = 5;
print("Enter a number : ",num)
print("Factorial : ",factorial(num))

Output
Enetr a Number : 5
Factorial : 120
4(b). Explain lambda function with example. Write a Python program to find greatest of three numbers
lambda function
 Lambda functions is also known as anonymous function.
 An anonymous function is a function that is defined without a name.
 While normal functions are defined using the def keyword in Python, anonymous
functions are defined using the lambda keyword.
Syntax
lambda arguments: expression
Example
x = lambda a : a + 10
print(x(5))
output
15
Greatest of three numbers
def maximum(a, b, c):
if (a >= b) and (a >= c):
largest = a
elif (b >= a) and (b >= c):
largest = b
else:
largest = c
return largest

a = 10
b = 14
c = 12
print(maximum(a, b, c))
Output:
14

5(a). Discuss the python program to implement square root of a number and same program with math
function. Explain about math function.
Math:
 It is a built in function in python.
 The math module has a set of methods and constants.
 Math methods:
-math.ceil()
-math.floor()
-math.cos()
-math.exp()
-math.sqrt()
-math.factorial() ,etc..
 Eg:1 x=4.6
math.ceil(x)
output:
5
 Eg:2 x=4.3
Math.floor(x)
Output:
4
To find the square root of a number

Program:
number = float(input("enter a number: "))
sqrt = number ** 0.5
print("square root:", sqrt)

Output:
enter a number: 676
square root: 26.0

Using Math Function:


import math
print(math.sqrt(1024))

Output:
32.0

5(b). Write a Python program to generate first ‗N‘ Fibonacci series numbers. (Note: Fibonacci numbers
are 0, 1, 1, 2, 3, 5, 8… where each number is the sum of the preceding two)
Algorithm

Step 1:Input the 'n' value until which the Fibonacci series has to be generated

Step 2:Initialize sum = 0, a = 0, b = 1 and count = 1

Step 3:while (count <= n)

Step 4:print sum

Step 5:Increment the count variable

Step 6:swap a and b

Step 7:sum = a + b

Step 8:while (count > n)

Step 9:End the algorithm

Step 10:Else

Step 11:Repeat from steps 4 to 7


Program
#Python program to generate Fibonacci series until 'n' value
n = int(input("Enter the value of 'n': "))
a=0
b=1
sum = 0
count = 1
print("Fibonacci Series: ", end = " ")
while(count <= n):
print(sum, end = " ")
count += 1
a=b
b = sum
sum = a + b

Input:

Enter the value of 'n': 5

Output:

Fibonacci Series: 0 1 1 2 3
d is Not Found in the Array '%(e))

You might also like