GE8151 Unit III
GE8151 Unit III
GE8151 Unit III
Conditionals: Boolean values and operators, conditional (if), alternative (if-else), chained
conditional (if-elif-else); Iteration: state, while, for, break, continue, pass; Fruitful functions:
return values, parameters, local and global scope, function composition, recursion; Strings: string
slices, immutability, string functions and methods, string module; Lists as arrays. Illustrative
programs: square root, gcd, exponentiation, sum an array of numbers, linear search, binary
search.
3.1 CONDITIONALS:
3.1.1 BOOLEAN VALUES AND OPERATORS
A Boolean expression is an expression that is either true or false. It is used to compare two
values.
The following examples use the operator ==, which compares two operands and produces True if
they are equal and false otherwise.
>>>5==5
True
>>>5==6
False
True and False are special values that belong to the type bool; They are not strings.
>>> type(True)
<class 'bool'>
>>> type(False)
<class 'bool'>
Remember that = is an assignment operator and == is the relational operator.
Program:
x=12
y=15
print(―is x == y ? =‖ ,x == y )
print(―is x != y ? =‖ ,x != y )
print(―is x <= y ? =‖ ,x <= y )
print(―is x >= y ? =‖ ,x >= y )
print(―is x > y ? =‖ ,x > y )
print(―is x < y ? =‖ ,x < y )
Output:
is x == y ? = False
is x != y ? =True
is x <= y ? =True
is x >= y ? =False
is x > y ? =False
is x < y ? =True
Eg:
x = True
y = False
print('x and y is', x and y)
print('x or y is', x or y)
print('not x is', not x)
Output:
x and y is False
x or y is True
not x is False
The boolean expression after if is called the condition. If it is true, the indented statement runs.
If not, nothing happens.
if statements have the same structure as function definitions: a header followed by an indented
body. Statements like this are called compound statements.
Flowchart:
There is no limit on the number of statements that can appear in the body, but there has to be at
least one. Occasionally, it is useful to have a body with no statements. In that case, you can use
the pass statement, which does nothing.
Ex:
x=7
if x < 0:
pass # TODO: need to handle negative values!
Example:
If the remainder when x is divided by 2 is 0, then we know that x is even, and the program
displays a message to that effect. If the condition is false, the second set of statements is
executed. Since the condition must be true or false, exactly one of the alternatives will run. The
alternatives are called branches, because they are branches in the flow of execution.
Example:
Odd or even number Output
n=eval(input("enter a number")) enter a number4
if(n%2==0): even number
print("even number")
else:
print("odd number")
positive or negative number Output
n=eval(input("enter a number")) enter a number8
if(n>=0): positive number
print("positive number")
else:
print("negative number")
leap year or not Output
Sometimes there are more than two possibilities and we need more than two branches. One way
to express this type of computation is a chained conditional:
The syntax looks like this:
if (condition1):
statement(s)
elif(condition2):
statement(s)
elif(condition3):
statement(s)
else:
statement(s)
elif is an abbreviation of ―else if.‖ Again, exactly one branch will be executed. There is no limit
on the number of elif statements. If there is an else clause, it has to be at the end, but there
doesn‘t have to be one.
Eg:
# Check positive or negative
num = int(input("enter a num"))
if num > 0:
print("Positive number")
elif num == 0:
print("Zero")
else:
print("Negative number")
if choice == 'a':
draw_a()
elif choice == 'b':
draw_b()
elif choice == 'c':
draw_c()
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 branch executes, and the statement ends. Even if more
than one condition is true, only the first true branch executes.
Example:
student mark system Output
mark= eval(input("enter ur mark:")) enter ur mark:78
if(mark>=90): grade:B
print("grade:S")
elif(mark>=80):
print("grade:A")
elif(mark>=70):
print("grade:B")
elif(mark>=50):
print("grade:C")
else:
print("fail")
traffic light system Output
colour=input("enter colour of light:") enter colour of light:green
if(colour=="green"): GO
print("GO")
elif(colour=="yellow"):
print("GET READY")
else:
print("STOP")
compare two numbers Output
x=eval(input("enter x value:")) enter x value:5
y=eval(input("enter y value:")) enter y value:7
if(x == y): x is less than y
print("x and y are equal")
elif(x < y):
print("x is less than y")
else:
print("x is greater than y")
Roots of quadratic equation output
8
NESTED CONDITIONALS
One conditional can also be nested within another.
#Check positive or negative
num = float(input("enter a num"))
if num>= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
The outer conditional contains two branches. The first branch contains a simple
statement. The second branch contains another if statement, which has two branches of its own.
Those two branches are both simple statements, although they could have been conditional
statements as well.
Although the indentation of the statements makes the structure apparent, nested
conditionals become difficult to read very quickly.
Logical operators often provide a way to simplify nested conditional statements. For
example, we can rewrite the following code using a single conditional:
x=5
if 0 < x:
if x < 10:
Output:
x is a positive single-digit number.
The print statement is executed only if we make it past both conditionals, so we can get
the same effect with the ‗and‘ operator:
9
x=5
if 0 < x and x < 10:
print('x is a positive single-digit number.')
Output:
x is a positive single-digit number.
Output:
x is a positive single-digit number.
Reassignment
It is legal to make more than one assignment to the same variable. 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.
Figure, shows what reassignment looks like in a state diagram.
(1) 5
x
(2) 7
State: Transition from one process to another process under specified condition with in a
time is called state
In python an assignment statement can make two variables equal. But they don‘t have to stay
that way:
>>>a=5
>>>a=b #a and b are now equal
>>>a=3 #a and b are no longer equal
10
>>>b
5
The third line changes the value of a but does not change the value of b, so they are no longer
equal.
Reassigning variables is often useful, but it has to be used with caution. If the values of the
variables change frequently, it can make the code difficult to read and debug.
Updating Variables
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, we 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 we can update a variable, we 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.
3.2 ITERATION:
Iteration is an ability to run a block of statements repeatedly. Python allows a block of
statements to be repeated as many times as long as the processor could support. This is generally
called looping, also called as repetition structure or iteration.
A looping statement also influences the flow of control because it causes one or more statements
or a block to be executed repeatedly.
The keyword while followed by a test expression (which can be any valid expression),
and a colon. Following the header is an indented body. The test expression is evaluated. If it
evaluates to True, then the body of the loop is executed. After executing the body, the test
expression is evaluated again. While test expression evaluates to True, the body of the loop is
executed. When the test expression evaluates to False, the loop is terminated and execution
continues with the statement following the body.
Syntax:
while (condition):
body of the loop
Example program:
i=0
n=5
while i<=n:
print (i)
i+=1
Output:
0
1
2
3
4
5
12
Example:
while(n>0):
a=n%10
sum=sum*10+a
n=n//10
if(sum==org):
print("The given no is palindrome")
else:
print("The given no is palindrome")
Python‘s for statement iterates over the items of any sequence (a list or a string), in the
order that they appear in the sequence. A for statement is also called a loop because the flow of
execution runs through the body and then loops back to the top.
Syntax:
for iterating_var in sequence:
statement(s)
If we do need to iterate over a sequence of numbers, the built-in function range() comes
in handy. It generates arithmetic progressions:
Eg:
This function does not store all the values in memory, it would be inefficient. So it
remembers the start, stop, step size and generates the next number on the go.
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
3. for i in (2,3,1): 2
For loop in tuple print(i) 3
1
o
Output:
The sum is 48
Nested Loops
Python programming language allows to use one loop inside another loop. Following section
shows few examples to illustrate the concept.
Syntax:
The syntax for a nested while loop statement in Python programming language is as follows
while expression:
while expression:
statement(s)
statement(s)
16
The break statement terminates the loop containing it. Control of the program flows to
the statement immediately after the body of the loop.
If break statement is inside a nested loop (loop inside another loop), break will terminate
the innermost loop.
The working of break statement in for loop and while loopis shown below.
Eg:
Example Output
for i in "welcome": if(i=="c"): w
break e
print(i) l
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.
The working of continue statement in for and while loop is shown in figure.
17
Eg:
Example Output
for i in ―welcome‖: w
if (i == ―c‖): e
continue l
print(i) o
m
e
Eg:
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
This is commonly used for creating minimal classes:
>>> class MyEmptyClass:
... pass
18
Example Output
for i in ―welcome‖: w
if (i == ―c‖): e
pass l
print(i) c
o
m
e
Example:
for i in range(1,6):
print(i)
else:
print("the number greater than 6")
Output
1
2
3
4
5
the number greater than 6
Example:
i=1
while(i<=5):
print(i)
i=i+1
else:
print("the number greater than 5")
Output:
1
2
3
4
5
the number greater than 5
Consider the example function area, which returns the area of a circle with the given
radius:
20
def area(radius):
temp = 3.14159 * radius**2
return temp
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.
def area(radius):
return 3.14159 * radius**2
Code that appears after a return statement, or any other place the flow of execution can
never reach, is called dead code.
3.3.2 PARAMETERS/ARGUMENTS
Parameters are the variables which used in the function definition.
Parameters are inputs to functions. Parameter receives the input from
the function call.
It is possible to define more than one parameter in the function definition.
Types of parameters/Arguments:
1. Required/Positional parameters
2. Keyword parameters
3. Default parameters
4. Variable length parameters
Example Output:
def student( name, roll ): George 98
print(name,roll)
student(―George‖,98)
Keyword parameter:
When we call a function with some values, these values get assigned to the
parameter according to their position. When we call functions in keyword parameter, the
order of the arguments can be changed.
Example Output:
def student(name,roll,mark): 90 102 bala
print(name,roll,mark)
student(90,102,"bala")
21
Default parameter:
Python allows function parameter to have default values; if the function is called without
the argument, the argument gets its default value in function definition.
Example Output:
def student( name, age=17): Kumar 17
print (name, age)
Ajay 17
student( ―kumar‖)
student( ―ajay‖)
Python allows us to handle this kind of situation through function calls with number of
arguments.
In the function definition we use an asterisk (*) before the parameter name to denote this
is variable length of parameter.
Example Output:
def student( name,*mark): bala ( 102 ,90)
print(name,mark)
student (―bala‖,102,90)
Local Scope
A variable with local scope can be used only within the function. Parameters and
variables defined inside a function is not visible from outside. Hence, they have a local scope.
Example:
a=50 --------------------------------------------------Global variable
def add():
b=20--------------------------------------------Local variable
c=a+b
print c
def sub():
b=30--------------------------------------------Local variable
c=a-b;
print c
print a
add()
sub()
Output:
50
70
20
Example:
math.sqrt(math.log(10))
23
Example: Output:
def add(a,b): 900
c=a+b
return c
def mul(c,d):
e=c*d
return e
c=add(10,20)
e=mul(c,30)
print(e)
find sum and average using function output
Composition
def sum(a,b): enter a:4
sum=a+b enter b:8
return sum the avg is 6.0
def avg(sum):
avg=sum/2
return avg
a=eval(input("enter a:"))
b=eval(input("enter b:"))
s=sum(a,b)
a=avg(s)
print("the avg is",a)
def area(radius):
return 3.14159 * radius**2
def
area2(xc, yc, xp, yp):
return area(distance(xc, yc, xp, yp)) #function Composition
3.3.5 RECURSION:
Recursion is the process of defining something in terms of itself.
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.
A function calling itself till it reaches the base value - stop point of function call.
Example: factorial of a given number using recursion
Factorial of n Output
def fact(n): enter no. to find fact:5
if(n==1): Fact is 120
return 1
else:
return n*fact(n-1)
n=input(―enter no.to find fact:‖)
fact=fact(n)
print("Fact is",fact)
Filtering
The filter() function in Python takes in a function and a list as arguments. The function is
called with all the items in the list and a new list is returned which contains items for which the
function evaluates to true.
The function filter(function, list) offers an way to filter out all the elements of a list, for
which function returns True.
3.4 STRINGS
String is defined as sequence of characters represented in quotation marks(either single quotes
( ‗ ) or double quotes ( ― ) or (―‖‖ ―‖‖‖)
An individual character in a string is accessed using an index.
The index should always be an integer (positive or negative).
A index starts from 0 to n-1.
Strings are immutable i.e. the contents of the string cannot be changed after it is
created.
Python will get the input at run time by default as a string.
Python does not support character data type. A string of size 1 can be treated as
characters.
String A H E L L O
Positive Index 0 1 2 3 4
Negative Index -5 -4 -3 -2 -1
26
Summary of operations:
Searching
Example: Program to find the letter in a word
def find(word, letter):
index = 0
while index < len(word):
if word[index] == letter:
return index
index = index + 1
return -1
If the character is not found, the function returns -1. If word[index] == letter, the function breaks
out of the loop and returns immediately. If the character doesn‘t appear in the string, the program
exits the loop normally and re-turns -1. This pattern of computation—traversing a sequence and
returning when we find what we are looking for—is called a search.
27
substring = original_string[first_pos:last_pos]
Example:
>>> s = 'Monty Python'
>>> s[0:5]
'Monty'
>>> s[6:12]
'Python'
If the first index is greater than or equals to the second the result is an empty string, represented
by two quotation marks:
>>> fruit = 'banana'
>>> fruit[3:3]
''
3.4.2 IMMUTABILITY
In Python, Strings are immutable. This means that elements of a string cannot be changed once it
has been assigned. Therefore [ ] operator cannot be used on the left side of an assignment.
>>>mystring = 'programiz‗
>>>mystring[5] = ‗b'
TypeError: 'str' object does not support item assignment.
We cannot delete or remove characters from a string. But deleting the string entirely is possible
using the keyword del.
28
>>>del mystring.
Stringname.method()
a=‖happy birthday‖
here, a is the string name.
'HAPPY BIRTHDAY‘
3 a.lower() >>> a.lower() change string to lower case
Boolean Methods
str.isalnum() - String consists of only alphanumeric characters (no symbols)
str.isalpha() - String consists of only alphabetic characters (no symbols)
str.islower() - String‘s alphabetic characters are all lower case
str.isnumeric() - String consists of only numeric characters
str.isspace() -String consists of only whitespace characters
str.istitle() - String is in title case
str.isupper() - String‘s alphabetic characters are all upper case
Example
>>>number = "5"
>>>letters = "abcdef"
>>>print(number.isnumeric())
True
>>>print(letters.isnumeric())
False
3.4.4 String Modules:
A module is a file containing Python definitions, functions, statements. Standard
library of Python is extended as modules. To use these modules in a program, programmer
needs to import the module. Once we import a module, we can reference or use to any of its
functions or variables in our code. There is large number of standard modules also available
in python. Standard modules can be imported in the same way as we import our user-defined
modules.
Syntax:
import module_name
Example output
import string
print(string.punctuation) !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
print(string.digits) 0123456789
print(string.printable) 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJ
KLMNOPQRSTUVWXYZ!"#$%&'()*+,-, ./:;<=>?@[\]^_`{|}~
print(string.capwords("happ Happy Birthday
y birthday"))
print(string.hexdigits) 0123456789abcdefABCDEF
print(string.octdigits) 01234567
31
Example:
a=array.array(‘i’,[1,2,3,4])
a - array name
array - module name
i - integer datatype
Example
Program to find sum of array elements Output
import array 10
sum=0
a=array.array('i',[1,2,3,4])
for i in a:
sum=sum+i
print(sum)
32
Syntax:
arrayname.fromlist(list_name)
Example
Program to convert list Output into array
import array
sum=0
l=[6,7,8,9,5]
a=array.array('i',[])
a.fromlist
(l)
for i in a:
sum=sum+i
print(sum)
Methods in array
Example: a=[2,3,4,5]
Exponentiation
def power(base,exp):
if(exp==1):
return(base)
if(exp!=1):
return(base*power(base,exp-1))
base=int(input("Enter base: "))
exp=int(input("Enter exponential value: "))
print("Result:",power(base,exp))
return found
a=[]
n=int(input("enter upper limit"))
for i in range(0,n):
e=int(input("enter the elements"))
a.append(e)
x=int(input("enter element to search"))
search(a,x)
Binary search
def binary_search(item_list,item):
first = 0
last = len(item_list)-1
found = False
while( first<=last and not found):
mid = (first + last)//2
if item_list[mid] == item :
found = True
36
else:
if item <item_list[mid]:
last = mid - 1
else:
first = mid + 1
return found
list_val=list(input(―Enter the values of the list‖)) #enter values one by one separated by ,
search=int(input(―Enter the value to search‖))
print(binary_search(list_val,search))
Additional programs
1. Python program to find the factorial of a number provided by the user.
num = int(input("Enter a number: "))
factorial = 1
# check if the number is negative, positive or zero
if num< 0:
print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
print("The factorial of 0 is 1")
else:
for i in range(1,num + 1):
factorial = factorial*i
print("The factorial of",num,"is",factorial)
3. Python program to find the largest number among the three input numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if (num1 >= num2) and (num1 >= num3):
37
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
print("The largest number between",num1,",",num2,"and",num3,"is",largest)
11. Program to sort alphabetically the words from a string provided by the user
my_str = input("Enter a string: ")
wordswords = my_str.split() #breakdown the string into a list of
# words.sort() #sort the list
# display the sorted words
print("The sorted words are:")
for word in words:
print(word)
s=raw_input("Enter string:")
count = 0
vowels = ['a','e','i','o','u']
for letter in s:
if letter in vowels:
count += 1
print("Count of the vowels is:")
print(count)
Output
Enter string: hello welcome
Count of the vowels is:
5
Explanation
raw_input: raw_input() takes exactly what the user typed and passes it back as a string.
input() first takes the raw_input() and then performs an eval() on it as well.
Part A:
1. What are Boolean values?
2. Define operator and operand?
3. Write the syntax for if with example?
4. Write the syntax and flowchart for if else.
5. Write the syntax and flowchart for chained if.
6. Define state
7. Write the syntax for while loop with flowchart.
8. Write the syntax for for loop with flowchart.
9. Differentiate break and continue.
10. Mention the use of pass
11. What is fruitful function
12. What is void function
13. Mention the different ways of writing return statement
14. What is parameter and list down its type?
15. What is local and global scope?
16. Differentiate local and global variable?
17. What is function composition, give an example?
18. Define recursion.
19. Differentiate iteration and recursion.
20. Define string. How to get a string at run time.
21. What is slicing? Give an example.
22. What is immutability of string?
23. List out some string built in function with example?
24. Define string module?
25. How can list act as array?
Part B:
1. Explain conditional statements in detail with example(if, if..else, if..elif..else)
2. explain in detail about operators in detail
3. Explain in detail about iterations with example.(for, while)
4. Explain in detail about string built in function with suitable examples?
5. Explain about loop control statement(break, continue, pass)
6. Briefly discuss fruitful function.
7. Discuss with an example about local and global variable and function composition
8. Explain in detail about recursion with example.
9. Explain in detail about strings and its operations(slicing,immutablity)
10. program to search an element using linear search.
11. program to search an element using binary element.
12. program to find factorial of a given number using recursion