Unit 3
Unit 3
PART-A
The len() function in Python is used to determine the number of items in an object.
It can be applied to various data types such as strings, lists, tuples, dictionaries, and more.
Example:
string = "Hello, World!"
print(len(string))
Output: 13
Syntax of If Statement:
if condition:
# Statements to execute if
# condition is true
Example:
if 10 > 5:
print("10 greater than 5")
print("Program ended")
Output:
10 greater than 5
Program ended
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false
Example:
x=3
if x == 4:
print("Yes")
else:
print("No")
Output
No
Example
letter = "A"
if letter == "B":
print("letter is B")
else:
print("letter isn't A, B or C")
Output
letter is A
Nested if statements:
You can nest if statements within another if or else block to create complex decision trees.
Syntax:
if (condition1):
# executes when condition is True
if (condition2):
# executes when condition is True
Example:
i = -15;
if i != 0:
if i > 0:
print("Positive")
if i < 0:
print("Negative")
Output:
Negative
State
A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
>>> x = 5
>>> x
5
>>> x = 7
>>> x
7
The first time we display x, its value is 5; the second time, its value is 7. Python uses the equal
sign (=) for assignment. First, equality is a symmetric relationship and assignment is not.
For example, in mathematics, if a = 7 then 7 = a. But in Python, the statement a = 7 is legal
and 7 = a is not. Also, in mathematics, a proposition of equality is either true or false for all
time. If a =b now, then a will always equal b. In Python, an assignment statement can make
two variables equal.
>>> a = 5
>>> b = a # a and b are now equal
>>> a = 3 # a and b are no longer equal
>>> b
5
The third line changes the value of ―a but does not change the value of ―b , so they are no
longer equal. A common kind of reassignment is an update, where the new value of the
variable depends on the old.
>>> x = x + 1
This means ―get the current value of x, add one, and then update x with the new value. If we
try to update a variable that doesn‘t exist, you get an error, because Python evaluates the right
side before it assigns a value to x:
>>> x = x + 1
NameError: name ‘x’ is not defined, Before you can update a variable, you have to initialize
it, usually with a simple assignment:
>>>x = 0
>>>x = x + 1
Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.
While loop
Repeats a statement or block of statements while a given condition is TRUE.
Tests the condition before executing the body of loop.
The body of the loop should change the value of one or more variables so that the
condition becomes false eventually and the loop terminates. Otherwise the loop will repeat
forever, which is called an infinite loop. In the case of countdown, we can prove that the loop
terminates: if n is zero or negative, the loop never runs. Otherwise, n gets smaller each time
through the loop, so eventually we have to get to 0. For some other loops, it is not so easy to
tell
Program
sum = 0
i=1
while i <= n:
sum = sum + i
i = i+1 # update counter
print(“The sum is”, sum) # print the sum
Output:
The sum is 55
In the above program, the test condition will be True as long as our counter
variable i is less than or equal to n. We need to increase the value of counter variable in the
body of the loop. This is very important (and mostly forgotten). Failing to do so will result in
an infinite loop (never ending loop). Finally the result is displayed.
For Loop
The for loop in Python is used to iterate over a sequence (list, tuple, string) or other
iterable objects. Iterating over a sequence is called traversal. The for loops are used to construct
definite loops.
Syntax of FOR LOOP:
for val in sequence:
Body of for
Here, val is the variable that takes the value of the item inside the sequence on each iteration.
Loop continues until we reach the last item in the sequence. The body of for loop is separated
from the rest of the code using indentation.
Example 1:
for k in [4, 2 ,3, 1]:
print (k)
Output:
4
2
3
1
Break
Break statement is used to break the loop. For example, suppose you want to take input
from the user until they type done
Break statements can alter the flow of a loop. It terminates the current 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
Example
for i in "welcome":
if(i=="c"):
break l
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.
Syntax:
pass
Example
for i in "welcome":
if(i=="c"):
pass
print(i)
Output
w
e
l
c
o
m
e
3. Explain in detail about the fruitful function with examples.
A function that returns a value is called fruitful function.
Example:Root=sqrt (25)
Example: def add():
a=10
b=20
c=a+b
return c
c=add()
print(c)
Void Function
A function that perform action but don’t return any value.
Example:
print(“Hello”)
Example:
def add():
a=10
b=20
c=a+b
print(c)
add()
Return values:
The built-in functions we have used, such as abs, pow, and max, have produced
results.
Calling each of these functions generates a value, which we usually assign to a variable or use
as part of an expression.
But so far, none of the functions we have written has returned a value. In this
chapter, we are going to write functions that return values, which we will call fruitful
functions, for want of a
better name. The first example is area, which returns the area of a circle with the given radius:
Example:
def area(radius):
temp = 3.14159 * radius**2
return temp
We have seen the return statement before, but in a fruitful function the return
statement includes a return value. This statement means: Return immediately from this
function and use the following expression as a return value. The expression provided can be
arbitrarily complicated, so we could have written this function more concisely:
Example:
def area(radius):
return 3.14159 * radius**2
On the other hand, temporary variables like temp often make debugging easier.
Sometimes it is useful to have multiple return statements, one in each branch of a conditional.
We have already seen the built-in abs, now we see how to write our own:
Example:
def absolute_value(x):
if x < 0:
return -x
else:
return x
return keywords are used to return the values from the function.
example:
return a – return 1 variable
return a,b– return 2 variables
return a+b– return expression
return 8– return value
String slices
A segment of a string is called a slice. Selecting a slice is similar to selecting a character:
Example
>>> s = ‘Monty Python’
>>> s[0:5]
‘Monty’
The operator [n:m] returns the part of the string from the ―n-eth character to the ―m-eth
character, including the first but excluding the last. This behavior is counter intuitive, butit might
help to imagine the indices pointing between the characters. If you omit the first index (before the
colon), the slice starts at the beginning of the string.
If you omit the second index, the slice goes to the end of the string:
>>> fruit = ‘banana’
>>> fruit[:3]
‘ban’
>>> fruit[3:]
‘ana’
If the first index is greater than or equal to the second the result is an empty string,
represented by two quotation marks:
>>> fruit = ‘banana’
>>> fruit[3:3]
‘’
An empty string contains no characters and has length 0, but other than that, it is the same
as any other string.
Immutability
It is tempting to use the [] operator on the left side of an assignment, with the intention of
changing a character in a string.
For example:
>>> greeting = ‘Hello, world!’
>>> greeting[0] = ‘J’
TypeError: ‘str’ object does not support item assignment
The ―object in this case is the string and the ―item is the character you tried to assign. The
reason for the error is that strings are immutable, which means you can‘t change an existing string.
The best you can do is create a new string that is a variation on the original:
>>> greeting = ‘Hello, world!’
>>> new_greeting = ‘J’ + greeting[1:]
>>> new_greeting
‘Jello, world!’
This example concatenates a new first letter onto a slice of greeting. It has no effect on the
original string.
Length
The len function, when applied to a string, returns the number of characters in a string:
>>> fruit = “banana”
>>> len(fruit)
6
The index starts counting form zero. In the above string, the index value in from 0 to 5.
To get the last character, we have to subtract 1 from the length of fruit:
size = len(fruit)
last = fruit[size-1]
Alternatively, we can use negative indices, which count backward from the end of the string.
The expression fruit[-1] yields the last letter, fruit[-2] yields the second to last, and so on.
Syntax to access the method
Stringname.method()
5. Explain in detail about recursion with proper syntax and program in python.
Recursion
Recursion is a technique of solving a problem by breaking it down into smaller and
smaller sub problems until you get to a small enough problem that it can be easily solved.
Usually, recursion involves a function calling itself until a specified a specified condition is
met/ A function calling itself till it reaches the base value - stop point of function call.
Factorial(n)
Step 1 : Set f=1
Step 2: IF n==1 then return 1
ELSE
Set f=n*factorial(n-1)
Step 3 : print f
Factorial of n
def fact(n):
if(n==1):
return 1
else:
return n*fact(n-1)
n=eval(input("enter no. to find fact:"))
fact=fact(n)
print("Fact is",fact)
Output
enter no. to find fact:5
Fact is 120