if and Types of if statements
Conditional
Execution
We need the ability to check conditions and to change the behaviour/flow of the
program accordingly .
Conditional statements give us this ability.
IF CONDITION
The simplest is the ‘if’ statement
• The Boolean expression after the ‘if’ is called the condition.
• If the condition is true, the print statement is executed.
• If the condition is false, nothing happens
x = int(input("Enter the value of x:"))
if x > 0:
print('x is GREATER’)
Alternative
Execution
The second form of ‘if’ statement is alternative execution.
Here, there are two possibilities and the condition determines which one runs.
x = int(input("Enter the value of x:"))
if x > 0:
print('x is positive’)
else:
print('x is negative’)
• If the condition is true, the first print statement is executed.
• If the condition is false, the second print statement is executed.
• The alternatives are called branches, because there are branches in
the flow of execution.
Chained
Conditionals
Sometimes we need more than two possibilities and so more than two branches.
x = int(input("Enter x:"))
y = int(input("Enter y:"))
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal’)
print(‘exit’)
There is no limit on the number of ‘elif’ statements.
Each condition is checked in order. If the first is false, the next is checked and so
on. If one of them is true, the corresponding statement gets executed.
Nested
Conditionals
One conditional can also be nested within another. The previous
program can also be written as:
x = int(input("Enter x:"))
y = int(input("Enter y:"))
if x == y:
print('x and y are equal')
else:
if x < y:
print('x is less than y')
else:
print('x is greater than y')
Nested
Conditionals
The outer conditional contains two branches.
The first branch contains a single statement.
The second branch contains another if statement, which has two
branches on its own
Nested conditionals are difficult to read and is good to avoid.
For example,
if 0 < x:
if x < 10:
print('x is a positive single digit number')
can be rewritten as,
if 0 < x and x < 10:
print('x is a positive single digit number')
Regarding Loops – for, while
for -Loop
• A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
• To repeat a task until a particular condition is true.
The range()Function
• The range () is a built in function in python that is used to iterate over
a sequence of numbers.
Loops – while
Python While Loop is used to execute a block of statements
repeatedly until a given condition is satisfied.
To repeat one or more statements while particular condition is true.
And when the condition becomes false, the line immediately after
the loop in the program is executed.
The break Statement
• With the break statement we can stop the loop even if the while
condition is true:
The continue Statement
• With the continue statement we can stop the current iteration, and
continue with the next:
Nested loops
Using one loop inside another loop is called nested
loop. One is called the outer loop and the other is
called the inner loop.
A while loop can be inside another while loop
A for loop can be inside another for loop
A while loop can be inside a for loop and vice versa
Nested
loops
n = int(input("Enter n value:")) Output
for i in range(0,n):
for j in range(0,n): Enter n value:3
print("*",end=" ") * * *
print("\n")
* * *
* * *
Nested
loops
n = int(input("Enter n value:")) Output
m=n+1
for i in range(0,n): Enter n value:3
m=m-1 * * *
for j in range(0,m):
print("*",end=" ") * *
print("\n")
*
continue
statement
• The continue statement is used to
skip the rest of the code inside a
loop for the current iteration only
• Loop does not terminate but
continues on with the next
iteration
continue
statement
for val in "string":
if val == "i":
continue
print(val)
Output:
s
t
r
n
g
pass
statement
The pass statement is a null
statement Example 2:
Difference between pass and
comment is that comment is ignored
x = int(input("Enter
by the interpreter whereas pass is
not ignored
x:"))
Pass can be used as a placeholder if x == 0:
when code is to be added in future
pass
Example 1:
x = int(input("Enter x:"))
if x == 0:
Output
Getting the below error, since there
is no statement after if statement
Enter x:5
in the example above #No error since pass
IndentationError: expected an
indented block is used
pass
statement
Example 3: Example 4:
for i in range(4):
for i in range(4):
Getting the below error since pass
there is no statement associated
with for loop in the above
example #The above code does not throw
any error since the pass
File "pass_1.py", line 3
statement is used
for i in range(4):
^
IndentationError: expected an
indented block
Function
A function is a block of organized and reusable program code that performs a single, specific and
well-defined task
Syntax of a function Function header
def function_name(parameters): def func(): …………………
“””doc string “”” ………… …………………
statement(s) ……….. func()
Function body ………………..
return statement ………..
………… ………………..
…………………
The function name is used to identify the function
The function definition consists of a function header and a function body. The function
definition must be present before the function call. Otherwise, we will get an error.
The documentation string is optional. It describes what the function does.
The return statement is also optional.
Parameters through which we pass values to a function are optional
In the diagram, as soon as func() is called, the program control is passed to the first statement
in the function
All the statements in func() are executed and then the program control is passed to the
statement following the one that called the function
• Example (without • Example (with parameter):
parameter): def greet(name):
def greet(): """Greets a person"""
print("Hello, Good print("Hello " + name + ", Good
morning!") morning!")
greet('Paul’)
greet()
Output:
• Output: Hello Paul, Good morning!
Hello, Good morning!
Fruitful function – Function which return any value
Example(with return statement): Output:
def triangle_area(b, h): Enter base:10
a = (b * h)/2 Enter height:6
return a The area of the triangle is:
30.0
base = int(input("Enter base:"))
height = int(input("Enter height:"))
area = triangle_area(base,height)
print("The area of the triangle is:")
print(area)
Example (without return statement): Output:
def triangle_area(b, h): Enter base:10
area = (b * h)/2 Enter height:6
print("The area of the triangle is:") The area of the triangle is:
print(area) 30.0
base = int(input("Enter base:"))
height = int(input("Enter height:"))
triangle_area(base, height)
Advantages of using
functions
1.It helps to break a large program into many small parts.
As our program grows larger and larger, functions make
it more organized and manageable.
2.It avoids repetition and makes the code reusable.
3.We can also debug the program faster and better.
Local variable
A variable declared inside a function’s body Example:
is called as a local variable. It can be
accessed only inside the function def fn():
Part of the program where the variable is var = 5 * 2
accessible is called its scope print(“Inside fn(), var = :",var)
Example: fn()
def fn(): print(“Outside fn(), var = :",var)
var = 5 * 2
print(“Inside fn(), var = :",var) Output:
Inside fn(), var = : 10
fn() Traceback (most recent call last):
File “local.py", line 7, in <module>
Output: print(“Outside fn(), var = :",var)
Inside fn(), var = : 10 NameError: name 'var' is not defined
Global variable
A variable declared outside a function is Example:
called a global variable x = "awesome"
A global variable can be accessed inside
and outside a function
def myfunc():
Example:
x = "fantastic“ #local variable
x = "awesome"
print("Python is " + x)
def myfunc(): myfunc()
#using global variable
print("Python is " + x) print("Python is " + x) #global variable
Output:
myfunc()
Python is fantastic
Python is awesome
Output:
Python is awesome
Global variable
Example:
global keyword is used to modify a
global variable inside a function. x = "awesome"
def myfunc():
global x
x = "fantastic“ #global variable
print("Python is " + x)
myfunc()
print("Python is " + x) #global variable
Output:
Python is fantastic
Global variable
Example: Example:
var = 5 #Removing the global var statement from fn()
var = 5
def fn(): def fn():
global var var = 5 * 2
print("Inside fn(), var = :",var)
var = 5 * 2
print("Inside fn(), var = :",var)
fn()
print("Outside fn(),var = :",var)
fn()
print("Outside fn(),var = :",var) Output:
Inside fn(), var = : 10
Outside fn(),var = : 5
Output:
Inside fn(), var = : 10
Outside fn(),var = : 10
Function composition
We can call one function from within another
Function composition is a way of combining two or more functions in such a way that
the output of one function becomes the input of another function
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. The output of G(x) will be the input
for F(x) function.
F(G(x)),
Strings
String is a data type in python
A string is a sequence of characters
Strings are declared inside single or double or triple quotes
word = ‘banana’
x = ‘str1$’
y = “This1”
Here, word, x and y are objects of the class ‘str’
>>> type(word)
<class 'str'>
String slicing
A segment of a string is called a slice
The operator [n:m] returns the part of the string from the nth character to the mth character
• >>>fruit = 'banana’
• >>>print(fruit[3:])
• >>> ana
• >>>fruit=‘banana’
• >>>print(fruit[
len() function
len () function can be used to find the number of characters in a string
Concentanation
• + operator is used to concatenate two strings
str() function
• The str() function is used to convert values of any type to string type
* operator
• * operator is used to repeat a string n number of times
+= operator
+= operator is used to append a string
Strings are immutable
We cannot change the characters in a string
>>> name = "Rekha"
>>> name[0] = "L"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
We can only create a new string which is a variation of the original
>>> name = "Rekha"
>>> new_name = 'L' + name[1:]
>>> print(new_name)
Lekha
String formatting
• String formatting is the process of infusing things in the
string dynamically and presenting the string.
• String formatting can be done using the % operator also
called the string formatting operator
String formatting using the %
operator
>>> a = “Mary“
>>> print("%s How are you?"%a) Format symbol For
Mary How are you? %c character
>>> a = "Mary" %s string
>>> b = "Nisha“ %d Signed decimal integer
>>> print("%s and %s, How are you?" %(a,b)) %u Unsigned decimal integer
Mary and Nisha, How are you? %o Octal integer
%x Hexadecimal integer
>>> time = 10
%f Floating point number
>>> print("I will come there at %d o'clock" %time)
%e Scientific notation
I will come there at 10 o'clock
>>> a = 0x23f
>>> print("%x is the new number" %a)
23f is the new number
String functions
• Python provides a lot of built-in functions to manipulate strings.
Python String is immutable, so all these functions return a new
string and the original string remains unchanged.
len(str) - returns the length of the string
max(str) – returns the highest alphabetical character (having
highest ASCII value) in str
min(str) - returns the lowest alphabetical character (having
highest ASCII value) in str
enumerate(str) – lists the index and value of all the characters
in the string as pairs
>>> str = "Hello"
>>> print(list(enumerate(str)))
[(0, 'H'), (1, 'e'), (2, 'l'), (3, 'l'), (4, 'o')]
String methods
There are many built-in methods to manipulate strings
A method is invoked on a string object using the dot (.) operator
>>> flower = "rose"
>>> flower.upper()
'ROSE’
Here, flower is a string object
upper() is a method which is called on the flower object using the dot
operator.
upper() converts all the characters of the string object to capital letters
String Methods and
Functions
• strip() method removes spaces at the beginning and at the end of the
string
• Replace () method is used to remove the spaces between the words in
the string.
• Using split() and join() –remove the duplicate spaces
String module
Module in python
Modules are used to break down large programs into small and manageable
files
Modules provide reusability of code
Module refers to a file containing python statements and definitions
A file containing python code for example, math.py is called a module and its
module name would be math
We can import a module in a python program using the import keyword
and access the definitions inside it using the dot(.) operator
>>> import math
>>> print(math.pi)
3.141592653589793
String constants in the string
module
whitespace -- a string containing all ASCII whitespace
ascii_lowercase -- a string containing all ASCII lowercase letters
ascii_uppercase -- a string containing all ASCII uppercase letters
ascii_letters -- a string containing all ASCII letters
digits -- a string containing all ASCII decimal digits
hexdigits -- a string containing all ASCII hexadecimal digits
octdigits -- a string containing all
String constants in the string
module
String module contains a number of string constants, classes and
functions
string capwords() function
• In Python, string capwords() method is used to
capitalize one or more letters in the string using
split() method.
• Split the argument into words using split, capitalize the
required letters using capitalize, and then join the
words using join.
• If the optional second argument sep (separator) is
absent or None,
capwords function in the
string module
Lists as arrays
An array is an ordered collection of elements of the same data type. The elements are stored in
contiguous memory locations.
A list containing a sequence of elements of the same data type can be used as an array
Each element in the array can be accessed using its index
The index value of the first element in the array is 0, the index value of the second element is 1, the
index value of the third element is 2 and so on
The differences between the array and list is list can store elements of multiple data types whereas
array store only of the same datatype.
Element:Each item stored in an array
Index:Location
Example : An array containing 10 elements
2 34 6 50 65 78 92 11 13 45
0 1 2 3 4 5 6 7 8 9
index
Basic operations
• Traverse-Print all the array elements one by one.
• Insertion-Adds an element in the array at specified index.
• Deletion-Delete an element in an array
• Search-Search the array to check if the specified value is present or
not.
• Update-Updates/changes the value of an element present at the
specified index in an array
Creating an array
• The array is declared in python as,
Import array as arr
Arrayname=array(typecode,[Initializers])
Where Typecode specifies the type of value(s)that will be stored in the
array.
• i-integer of size 2 bytes
• F-floating point of size of 4 bytes
• c-character of size 1 byte
Lists as arrays-Program to sum the elements in
an array
Output:
Illustrative Program:Linear
search
Linear search
It searches the list sequentially (starting from index 0) until ‘val’ is found or
until the entire list is searched
• list=[10,5,13,25,67]
• Am searching the value 25
• Search element “25 “is present in the list or not in sequencial order
Using list:
Lists as arrays –
Linear search
#Program to find an element using linear search
array = []
n = int(input("Enter the number of elements:"))
for i in range(n):
ele = int(input("Enter element to be inserted))
array.append(ele)
val = int(input("Enter the element to find:”))
flag = 0
for i in range(n):
if(val == array[i]):
print(val, “found at position",i))
flag = 1
break #for loop ends here
Lists as arrays –
Linear search
if(flag == 0):
print(val, “ is not available in the array")
Output
******
Enter the number of elements:5
Enter element 0:22
Enter element 1:44
Enter element 2:11
Enter element 3:26
Enter element 4:49
Enter the element to find:11
11 found at position 2
Lists as arrays – Binary search
Let val be the element to find in a If the val is same as the element in mid,
list/array. Binary search it returns mid
If val is not in mid, then it splits the list
This method is used, if the list is
into two parts - one part before the mid
already in sorted order element and the other part after the mid
This method is more efficient element and searches again only in one
than linear search part as follows:
if( val < array[mid]), search the
Let’s say in a list, start is index 0,
element in the part of the list before
end is index n-1 and mid is the the mid element by setting end as,
middle index. This method first end = mid -1
compares ‘val’ to the element in If(val > array[mid]), search the
mid. element in the part of the list after
the mid element by setting start as
start = mid + 1
Repeat the above step until the element
is found or until start <= end
Lists as arrays –
Binary search
Program to find an element using binary search
#Used when all the elements in the list are in the sorted order
n = int(input("Enter the number of elements:"))
array = []
for i in range(n):
ele = int(input("Enter element %d:"%i))
array.append(ele)
val = int(input("Enter the element to find:"))
start = 0
end = n-1
flag = 0
Lists as arrays –
Binary search
while(start <= end):
mid = int((start+end)/2)
if(val == array[mid]):
print(val,“ found at position“, mid)
flag = 1
break
elif(val < array[mid]):
end = mid -1
elif(val > array[mid]):
start = mid + 1
Lists as arrays –
Binary search
if flag == 0:
print(val, “ is not available in the array")
Output
******
Enter the number of elements:3
Enter element 0:1
Enter element 1:2
Enter element 2:3
Enter the element to find:4
4 is not available in the array
Lists as arrays –
Binary search
n=6 50 > array[mid] => 50 > 30 => yes
array start = mid+1 = 3
index value
0 10 mid = (start + end)/2 = (3 + 5)/2 = 4
1 20 50 == array[mid] => 50 == 50 => yes
2 30
3 40
4 50
5 60
val = 50
start = 0, end = 5, mid = (start + end)/2 = (0 + 5)/2 = 2
50 == array[mid] => 50 == 30 => No
50 < array[mid] => 50 < 30 => No
Lists as arrays –
Binary search
n=6 70 > array[mid] => 70 > 30 => yes
array start = mid+1 = 3
index value
0 10 mid = (start + end)/2 = (3 + 5)/2 = 4
1 20 70 == array[mid] => 70 == 50 => no
2 30 70 < 50 => no
3 40 70 > 50 => yes
start = mid +1 = 4 +1 = 5
4 50
mid = (start + end)/2 = (5 + 5)/2 = 5
5 60
70 == array[mid] => 70 == 60 => no
70 < 60 => no
val= 70
70 > 60 => yes
start = 0, end = 5, mid = (start + end)/2 = (0 + 5)/2 = 2
start = mid + 1 = 5 + 1 = 6
70 == array[mid] => 70 == 30 => No
start > end ( 6 > 5) => stop
70 < array[mid] => 70 < 30 => No
Recursion
• Recursion is a programming technique to solving a problem, that has a
recursive function call itself again and again until the condition is reached.
factorial(n)
Step 1:Start Step 1:Set f=1
Step 2:Input the number as n Step 2:IF n==1 then return 1
Step 3:Call factorial(n) ELSE
Step 4:End Set f=n*factorial(n-1)
Step 3:Print f
• FORMULA-- n!=n*(n-1)!
• Ex: n=3
• Factorial of 3 is 6
• Advantages of using recursion
• 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 render the code look simple and effective.
• Disadvantages of using recursion
• A lot of memory and time is taken through recursive calls which makes it
expensive for use.
• Recursive functions are challenging to debug.
• The reasoning behind recursion can sometimes be tough to think through.
Greatest common Divisor
• The greatest common divisor of two numbers is the largest integer
that divides both the numbers,
• By using Euclid’s algorithm that states:
• GCD(a,b)= b, if b divides a
• GCD(b, a%b) otherwise
Assume that a>b
If a<b, then interchange a and b in the above formula
GCD(17,2)
GCD(2, 17%2)
GCD(2,1)=1
Working
• Assume a =62 and b=8
GCD(62,8)
remainder=62%8=6
GCD(8,6)
remainder=8%6=2
GCD(6,2)
Remainder=6%2=0
return 2
return 2
return 2
Squareroot:
Exponentiation
• We can find the solution to find exponent of a number using
recursion.
• To find x (pow )y
• base case- when y=0, the value will be “0”
• Recursive case- to find x (pow) y.
• EXP(x,y)= 1, if Y==0
• x*EXP(x (pow)y-1) otherwise