Python Unit 3 QB
Python Unit 3 QB
(Autono mous)
B.E./B.Tech.(Full Time)
Depart ment of Inf ormat ion Techno log y
20CS201 PROBLEM SOLVING USING PYTHON
Regu lations 2020
UNIT III
Prepared by: K.Ashokkumar, AP/IT
PART A 2Marks
The statement itself says if a given condition is true then execute the statements present inside
the “if block” and if the condition is false then execute the “else” block.
num = 5
if(num > 10):
print(“number is greater than 10”)
else:
print(“number is less than 10”)
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? ")
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:
i.break statement.
Break statements can alter the flow of a loop. It terminatesthe current Loop and executes
the remaining statement outside the loop. If the loop has else statement, that will also get
terminatedand come out of the loop completely.
ii.continue statement.
It terminatesthe current iterationand transfer the control to the next iterationin 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
8. Write a syntax (i) nested for loop, (ii) nested while loop.
(i) nested for loop
for condition1:
#statement()
for condition 2
# inside statement()
(ii)Syntax nested for loop
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop
10. Define function and state the necessary syntax for it.
A function is a block of code which only runs when it is called. You 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
def functionName():
# What to make the function do
11. Compare built in function & user defined function with necessary examples.
Functions that we define ourselves to do certain specific task are 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
def add_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.
12. What are the arguments in python with examples?
An argument is a value that is passed to a function when it is called. It might be a variable,
value or object passed to a function or 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-lengtharguments)
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.
The object does not need to exist at compile time, but does need to exist at runtime.
Syntax: Example:
def fun():
def cube(x):
statements
r=x**3
………
return r
return [expression]
16.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
Global variables are the types of variables that are declared outside of every function of
the program. The global variable, is accessible by all functions in a program.
Yes can a variable be both local &global
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 function and so on.
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
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 multipliesit by 2 and the output is 14
19. 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.
range (start, stop, step )
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
x = lambda a : a + 10
print(x(5))
PART B 16Marks
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.
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.
1.Conditional (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.
2. Program to provide bonus mark if the category is sports.
1. Program to provide flat rs 500, if the purchase amount is greater than 2000.
Program: Output:
purchase=eval(input(“enter your enter your purchase
purchase amount”)) amount
if(purchase>=2000): 2500
purchase=purchase-500 amount to pay
print(“amount to pay”,purchase) 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
2. Positive or negative number
3. Leap year or not
4. Greatest of two numbers
5. Eligibility for voting
Output
enter a number 8
positivenumber
3.Leap year or not
Program
y=eval(input("entera yaer"))
if(y%4==0):
print("leap year")
else:
print("not leap year")
Output
enter a yaer2000
leap year
4. Greatest of two numbers
Program
a=eval(input("enter a value:")) Output
b=eval(input("enterb value:"))
enter a value:4
if(a>b):
enter b value:7
print("greatest:",a)
greatest: 7
else:
print("greatest:",b)
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.
Example:
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 statement1get executed otherwise statement2get execute.
if the condition is false statement3gets executed
Syntax:
If(condition):
If(condition 1):
Statement 1
else:
statement
else:
statement
Flowchart:
Exampe:
1. greatest of three numbers
2. positive negative or zero
Output
enter the value of a 9
enter the value of a 1
enter the value of a 8
thegreatestnois
9
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, python inspects
each elif conditional in sequential order until one of them evaluates to true.it 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:
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:
Program
n=eval(input("entern"))
i=1
sum=0 sum=sum+i
while(i<=n): i=i+1
print(sum) enter n
10
Output 55
Factorial of a numbers:
Program
n=eval(input("entern"))
i=1
fact=1
while(i<=n): Output
fact=fact*i enter n
i=i+1print(fact) 5
120
Program
n=eval(input("entera number"))
sum=0
while(n>0):
a=n%10
sum=sum+a Output
n=n//10 Enter a number
print(sum) 123
6
n=eval(input("entera number"))
sum=0
while(n>0):
a=n%10 Output
sum=sum*10+a
enter a number
n=n//10
123
print(sum)
321
n=eval(input("entera number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum+a*a*a
n=n//10
if(sum==org):
print("The given number is Armstrong Output
number")
enter a number153
else:
print("The given number is not The given number is Armstrong number
Armstrong number")
Palindrome or not
Program
n=eval(input("entera number"))
org=n
sum=0
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome") Output
else: enter a number121
print("The given no is not palindrome") The given no is palindrome
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
Flowchar t:
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)
Examples:
1. print nos divisible by 5 not by 10:
2 Program to print fibonacci series.
Program
n=eval(input("entera"))
for i in range(1,n,1):
output
enter a:30 25
5
15
Fibonacci series
Program
a=0 Output
b=1 Enter the number of terms: 6
n=eval(input("Enterthe number of terms: ")) Fibonacci Series:
print("Fibonacci Series: ") 01
print(a,b) 1
for i in range(1,n,1): 2
c=a+b 3
print(c) 5
a=b 8
b=c
Output
find factors of a number
enter a number:10
Program 1
2
n=eval(input("entera number:"))
5
for i in range(1,n+1,1):
10
if(n%i==0):
print(i)
n=eval(input("entera number"))
for i in range(2,n):
if(n%i==0):
print("The num is not a prime") Output
break enter a no:7
else: The num is a prime number.
print("The num is a prime number.")
Program
OUTPUT
enter a lower range50
enter a upper range100
53
59
61
67
71
73
79
83 89
97
3.Summarize various loop control statement in detail. Explain it with necessary example.
BREAK
Syntax:
Break
Ou tpu t
CONTINUE
Example
w
It terminatesthe current iterationand transfer the control to the next iterationin the loop.
for
Syntax: e i in "welcome":
Continueif(i=="c"):
l
break
print(i)
Flowchart
Flowchart
Output
Example: w
for i in "welcome":
e
if(i=="c"):
continue l
print(i)
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 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 functions. based on our requirements These functions are
known as user defined functions .
User Defined Functions
User-defined functions help to decompose a large program into small segments which
makes program easy to understand, maintainand 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 declarationbegins 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:
def function_name(argument1,argument2,…):
Statement_1
Statement_2
………..
…………
return
Here,
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).
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.
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')
Ou tput:
Hello, Ayushi
2. Python Keyword Arguments
With keyword argumentsin 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
You may not always know how many arguments you’ll get. In that case, you use an
asterisk(*) before an argument name.
Example:
def sayhello(*names):
for name in names:
print(f"Hello, {name}")
Output:
Hello, Ayushi
Hello, Leo
Hello, Megha
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
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 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))