Python Programming: Control Flow Basics
Python Programming: Control Flow Basics
1
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Operation Result
X or Y If X is false then y, else X
X and Y If X is false, then x else Y
Not X If x is false, then true else False
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)
<type 'bool'>
>>>type(False)
<type 'bool'>
Boolean and Comparison operators:
The == operator is one of the comparison operators; the others are:
x! = y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
Although these operations are probably familiar to you, the Python symbols are different
from the mathematical symbols. A common error is to use a single equal sign (=) instead of a
double equal sign (==). Remember that = is an assignment operator and == is a comparison
operator.
3.2. Branching Statements (or) Conditional Statements
Control Flow is the order in which individual Statements, instructions are executed or
evaluated.
Flow is just a way or sequence of program Execution.
Every Statement of a program is executed one by one. Python provides various tools
for flow Control.
Some of them are if, if...else, if...elif...else, Nested if...elif...else, For, While, Nested,
Break, Continue etc.
2
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
FLOW CONTROL
Conditional Statements:
The execution of the program acts according the conditions. This concept is known
as Conditional statements or Branching Statements.
Syntax:
if (Condition):
True Statement Block
3
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Output 1:
Enter your age69
You are a Senior Citizen TRUE
Good Bye! True Statement Block
Output 2:
Enter your age45
Good Bye!
Example 2:
age=int(input('Enter your age'))
if age>=60:
print('You are eligible for voting')
print('Good Bye!')
Output 1:
Enter your age19
You are eligible for voting
Good Bye!
Output 1:
Enter your age17
Good Bye!
2. Alternative (IF....Else Statement):
A second form of the if statement is alternative execution, in which there are two
possibilities and the condition determines which one gets executed.
Syntax:
if (Condition):
True Statement Block
else:
False Statement Block
4
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Test
Condition
Program:
Output:
Enter a number4567
The given number is odd
[Link] condidtional (If...elif...else Statement):
If there are more than two possibilities and need more than two branches.
One way to express a computation like that is a chained conditional.
elif is an abbreviation of “else if.”
There is no limit onthe number of elif statements
Syntax:
if Condition 1:
Statement Block1
elif Condition 2:
Statement Block 2
elif Condition 3:
Statement Block 3
else:
False Statement
5
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
False
Test
Condition 1
True
elif Test False
Condition 2
True Statement of
condition1 False Statement
True
Statement2 of
condition2
Program
#Greatest among three numbers
x=int(input('Enter a first number'))
y=int(input('Enter a second number'))
z=int(input('Enter a third number'))
if x>y and x>z:
print('x is greater')
elif y>z:
print('y is greater')
elif x==y==z:
print('All are equal')
else:
print('z is greater')
Output:
Enter a first number345
6
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Syntax:
if Condition 1:
if Condition 2:
True Statement
else :
False Statement
False True
Test
Condition 1
False Statement 2
TrueStatement 2
7
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program:
#Greatest among three numbers
a=int(input('Enter a value'))
b=int(input('Enter b value'))
c=int(input('Enter c value'))
if a>b:
if a>c:
print('a is greater')
elif b>c:
print('b is greater')
else:
print('c is greater')
Output:
Enter a value234
Enter b value67
Enter c value78
a is greater
3.3. Iteration (or) Repetition(or)Looping:
Computers often do repetitive task. There is a situation when programmers used to
execute a block of code several number of times.
Repeated execution of a set of statements is called Iteration/Looping.
8
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
[Link] loop:
It executes the sequence of statements multiple times based on the condition given.
The for – loop repeats a given block of codes by specified number of times.
Syntax:
9
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program: Output:
# Print 'n' natural numbers Enter n value10
n=int(input('Enter n value')) 1 2 3 4 5 6 7 8 9 10
for i in range(1,n+1):
print(i,end=' ')
[Link] loop:
While loop is used, when we need to repeatedly execute a statement or group of
statements until the condition is true.
It tests the condition before executing the loop body so this technique is known as
Entry Controlled Loop.
Here, statements may be a single statement or a block of statements.
The condition may be any expression, the loop iterates while the condition is true,
when the condition becomes false, program control passes to the line immediately
following the loop.
Syntax:
while expression:
Statement(s)
Flowchart:
10
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program:
# Print 'n' natural numbers using while loop Output:
n=int(input('Enter n value')) Enter n value10
i=1 #loop variable initialization 1 2 3 4 5 6 7 8 9 10
while i<=n: #condition checking
print(i,end=' ') #loop statement
i=i+1 #loop variable incrementation
[Link] Loop:
Nesting is defined as placing of one loop inside the body of another loop.
It can use one or more loop inside any another while, for..loop etc.,
Syntax:
For <variable> in <sequence>:
For<variable> in <sequence>:
Statement(s)
Statement(s)
#nested for-->define one for loop with in another for loop
#print 'n' prime numbers
num=int(input('Enter range:'))
print('Prime numbers:',end=' ')
for i in range(1,num+1):#outer loop
for j in range(2,i):#inner loop
if i%j==0:
break # when encounter break statement exit the loop where it is placed.
else:
print(i,end=' ')
[Link]:
An algorithm is deterministic automation for accomplishing a goal which, given an
initial state, will terminate in a defined end-state.
When an algorithm is associated with processing information, data is read from an
input source or device, written to an output device, and/or stored for further
processing.
Stored data is regarded as part of the internal state of the algorithm.
The state is stored in a data structure.
11
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
1. Break Statement:
It terminates the current loop and resumes execution at the next statement.
The most common use for break is when some external condition is triggered
requiring a hasty exit from a loop.
The break statement can be used in both while and for loops.
If you are using nested loops, the break statement stops the execution of the
innermost loop and start executing the next line of code after the block.
Syntax:
Break
Condition Code
If
Condition
is True
Break
Condition
If condition is false
12
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program 1:
for letter in 'python':
if letter=='h':
break
print('current letter:',letter)
Output:
current letter: p
current letter: y
current letter: t
Program 2:
var = 10
while var> 0:
print ('Current variable value :', var)
var = var-1
if var == 5:
break
print( "Good bye!")
Output:
Current variable value : 10
Current variable value : 9
Current variable value : 8
Current variable value : 7
Current variable value : 6
Good bye!
[Link] statement:
It returns the control to the beginning of the while loop.
The continue statementrejects all the remaining statements in the current
iteration of the loop and movesthe control back to the top of the loop.
The continue statement can be used in both while and for loops.
Syntax:
Continue
13
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Condition Code
If
Condition
is True
Continue
Condition
If condition is false
Program 1: Output:
for letter in 'Python': Current Letter : P
if letter == 'h': Current Letter : y
continue Current Letter : t
print('Current Letter :',letter) Current Letter : o
Current Letter : n
Program 2: Output:
var = 10
Current variable value : 9
while var> 0:
Current variable value : 8
var = var -1
Current variable value : 7
if var==5:
Current variable value : 6
continue
Current variable value : 4
print('Current variable value :',var)
Current variable value : 3
print('Good bye!')
Current variable value : 2
Current variable value : 1
Current variable value : 0
Good bye!
[Link] statement:
It is used when a statement is required syntactically but you do not want any
command or code to execute.
The pass statement is a null operation; nothing happens when it executes.
14
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
The pass is also useful in places where your code will eventually go, but has not been
written yet (e.g., in stubs for example)
Syntax:
Pass
Program: Output:
for letter in 'Python': Current Letter: P
if letter=='h': Current Letter: y
pass Current Letter: t
print('This is pass block') This is pass block
print('Current Letter:',letter) Current Letter: h
print('Good bye') Current Letter: o
Current Letter: n
Good bye
3.5 Function:
A function is a named sequence of statements that performs a computation.
When define a function, specify the name of the function and the sequence of
statements.
Call the function by name.
Commonly function takes” an argument and “returns” a result. The result is called
the return value.
The expression in parentheses is called the argument of the function. The result, for
this function, is the type of the argument.
Functions usually take in data, process it, and return a result. Once a function is
written, it can be used again and again.
Functions can be from inside of other functions.
Syntax of Function
def function_name(parameters):
function body
return
15
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program: Output:
x = bool(1) True
print(x)
eval() Evaluates and executes an expression
Program: Output:
x = '3*(3+1)*(3+2)' 60
print(eval(x))
float() float converts integers and strings to floating-point numbers
Program: Output:
float(32) 32.0
Output:
Addition value is 7
Advantages of Functions:
Make a code modular
Functions are reusable
A program divided into functions, easier to understand and maintain.
Parts of a function
Function call – add(3,4)
Function definition – def add( x,y):
z=x+y
return z
Steps to Writing a function
Understand the purpose of the function.
Define the data that comes into the function from the caller.
Define data variables are needed inside the function to accomplish a goal.
Decide on the steps that the program will use to accomplish this goal.
16
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Example: The square function will take one number as parameter and return the
result of squaring that number.
Return values:
Return is a keyword which is used to return a value from the function definition
block to the function calling line.
Return takes zero, values or an expression.
Default value is none.
If many values are used then, use a tuple or list.
A function in python,
Takes input data, called parameters or arguments.
Perform computation
Returns the result.
def func(param1,param2):
#computations
return result
Parameter is the input data that is sent from one function to another.
Parameter is of two types,
Actual Arguments.
Formal Arguments.
Actual arguments:
Argument is defined in the function call.
Formal arguments:
Argument is defined as part of function definition.
Actual parameter value is received by formal parameter.
Program:
# Function with actual and formal parameters
def cube(x):#x is formal parameter
return x*x*x
a=int(input('enter the number:'))
b=cube(a)# a is actual parameter
print('cube of the given number:',b)
Output:
enter the number:3
cube of the given number: 27
17
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Output:
100
TypeError: a() takes 1 positional argument but 2 were given
>>>
#Example for Keyword argument
[Link]
def a(s,d):
print(s,d)
return
a(s=100,d="Black")
a(d="Black",s=100)
Output:
Black
Black
#Example for Default argument
[Link]
def a(s,d=20):
print(d,s)
return
a(15)
a(15,5)
Output:
15
15
#Example for Variable-length argument
[Link]
def a(*s):
for i in s:
print(i)
return
a(10,20,30)
a("hai")
18
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Output:
10
20
30
hai
#Program to add two numbers by passing parameters
[Link]
def add(a,b):
c=a+b
return c
y=add(2,2)
print(y)
Output:
4
Program:
def f1():
s=55
print(s)
s=10
f1()
Output:
55
19
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Output:
Enter a value: 2.5
6.25
Here the input function is used inside float function.
Input function considers any input value as a string, and according to our needs we
have to use either int() or float() to convert the input value into integer or floating value
to process in our program.
3.8 Recursion:
Recursion is a process of calling a function by itself again and again until some
condition is satisfied.
A recursive function must have,
A statement to test whether the function is calling itself again.
A statement that calls the function itself must be an argument.
A conditional statement
A return statement.
Advantages:
The code looks clean and elegant.
Large problems broken down into small problems
Disadvantages:
Logic is hard to follow.
It takes more memory.
It is hard to debug.
20
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program:
#Program to find factorial using recursion
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
num=int(input('Enter the number'))
print('Factorial of given number is',factorial(num))
Output:
Enter the number5
Factorial of given number is 120
3.9 Strings:
A string is a sequence of characters. (i.e) it can be a letter , a number, or a backslash.
Python strings are immutable, which means they cannot be changed after they are
created.
String slice:
Example
0 1 2 3 4
B L A C K
-5 -4 -3 -2 -1
The above example contains both positive and negative indexing.
21
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
[Link]
3.10 Immutability:
Strings in python are immutable i.e after created it cannot be changed.
No assignments can be done later but updating is possible.
[Link]
#NO ITEM ASSIGNMENT IN PYTHON
var1="python"
var1[2]="T"
Output:
var1[2]="T"
Type Error: 'str' object does not support item assignment
[Link]
[Link] Operators:
Example
Operator Description a=’Hello’
b=’boys’
Concatenation - Adds values on either side
+ a + b will give ‘Helloboys’
of the operator
22
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Program:
Output:
The Concatenation of the String is: I hate bitter foodbadly
The Repetition of the String is: I hate bitter foodI hate bitter food
The Slicing of the string is: h
The Slicing of the string is: ate
The membership operator of the string is: True
The membership operator of the string is: True
23
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
EX: [Link](‘substring’,start,end)
(iv) isalpha()
Return True, if one character (or) all the characters are alphabetical.
EX:[Link]()
(v) isdigit()
Return True, if one character (or) all the characters are digit.
EX:[Link] ()
(vi) islower()
Return True, if one character (or) all the characters are in lowercase.
EX:[Link]()
(vii) isupper()
Return True, if one character (or) all the characters are in uppercase.
EX:[Link]()
(viii) isspace()
Return True, if the string has white space.
EX:[Link] ()
(ix) lower()
Covert the string into lowercase.
EX: [Link]()
(x) upper()
Convert the string into uppercase.
EX: [Link]()
(xi) max()
Returns the maximum alphabetical character in a string.
EX:max(s)
(xii) min()
Returns the minimum alphabetical character in a string.
EX: min(s)
(xiii) replace()
Replace the old string with new string.
EX: [Link](‘old’,’new’,maxtime) (or) [Link](‘old’,’new’)
(xiv) len()
Returns the length of the string.
EX: len(s)
Program:
s='welcome'
print(max(s))
print(min(s))
print(len(s))
print([Link]('e',0,7))
print([Link]())
print([Link]())
print([Link]('c',0,7))
print([Link]())
print([Link]('e','c',1))
24
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Output:
w
c
7
2
WELCOME
Welcome
3
True
Wclcome
Output:
A list in Python is just an ordered collection of items which can be of any type.
By comparison an array is an ordered collection of items of a single type - so in
principle a list is more flexible than an array but it is this flexibility that makes things
slightly harder when you want to work with a regular structure.
A list is also a dynamic mutable type and this means you can add and delete
elements from the list at any time.
To define a list you simply write a comma separated list of items in square brackets,
25
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
myList=[1,2,3,4,5,6]
This looks like an array because you can use "slicing" notation to pick out an
individual element - indexes start from 0.
For example print myList[2]
It will display the third element, i.e. the value 3 in this case. Similarly to change the
third element you can assign directly to it:
myList[2]=100
The slicing notation looks like array indexing but it is a lot more flexible.
For example myList[2:5]
It is a sublist from the third element to the fifth i.e. from myList[2] to myList[4].
The final element specified i.e. [5] is not included in the slice.
26
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
27
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
Question Bank
GE3151 / Problem Solving and Python Programming
Knowledge
[Link]. Part –A (2 marks) Competence
Level
1. Write the syntax of if and if-else statements. BTL1 Remember
2. Differentiate for loop and while loop. BTL4 Analyze
3. Illustrate the flowchart of if-elif-else statements. BTL3 Apply
4. Present the flow of execution for a while statement. BTL1 Remember
5. Write the syntax for function definition BTL1 Remember
6. Name the type of Boolean operators. BTL1 Remember
7. Describe break statement with an example. BTL2 Understand
8. Write a program to find square root of a given number BTL3 Apply
9. Analyze different ways to manipulate strings in python. BTL4 Analyze
10. List out the applications of arrays. BTL1 Remember
11. Discuss about continue and pass statements. BTL2 Understand
12. What will be the output of print str[2:5] if str=’hello world!’? BTL1 Remember
13. Give the use of return () statement with a suitable example. BTL2 Understand
14. Write a program to iterate a range using continue statement. BTL1 Remember
15. Where does indexing starts in python? BTL1 Remember
16. Describe various methods used on a string. (Any Four) BTL3 Apply
17. What are the advantages and disadvantages of recursion function? BTL3 Apply
18. Explain the significance of for loop with else in an example BTL 5 Evaluate
19. Define array with an example. BTL1 Remember
20. Classify global variable with local variable BTL 4 Analyze
21. Summarize string modules BTL 5 Evaluate
22. Justify the effects of slicing operations on an array. BTL 5 Evaluate
23. How to access the elements of an array using index? BTL 4 Analyze
Part – B ( 16 Marks)
28
GE3151 PROBLEM SOLVING AND PYTHON PROGRAMMING
1. (i) Write a python program to find the sum of N natural numbers. Remember
BTL1
(ii) What is the use of pass statement, illustrate with an example.
(i) Define methods in a string with an example program using at
2. least five methods. BTL1 Remember
(ii) How to access characters of a string?
3. Write a program for binary search using Arrays BTL1 Remember
(i). Write a python program to find the given number is odd or
4. even.
BTL2 Understand
(ii). Explain break and continue statement with the help of for loop
in an example.
5. Write a python program to count the number of vowels in a string
BTL 3 Apply
provided by the user.
6. Explain the types of function arguments in python. BTL2 Understand
7. Explain the syntax and flow chart of the following loop statements
BTL2 Understand
(i) for loop (ii) while loop
8. (i). Illustrate the flow chart and syntax of if-elif- else statements
BTL 3 Apply
(ii). Develop a program to find the largest among three numbers
9. Explain recursive function. How do recursive function works? BTL 3 Apply
10. (i). Create a python program to find the given year is leap or not BTL 4 Analyze
(ii). Investigate on mutability and immutability in python
11. Examine the program on Fibonacci series BTL 3 Apply
(i). Generate a program that uses lambda function to multiply two
12. numbers. BTL 4 Analyze
(ii). Discuss the methods to manipulate the arrays in python
13. (i). Create a program to reverse a string without using recursion BTL 3 Apply
(ii). Illustrate the concept of local and global variables
Write a python program to design simple calculator performing
14. arithmetic functions like addition, subtraction, multiplication and BTL 5 Evaluate
division with the input given by user.
Create a program to print the following pattern
29