0% found this document useful (0 votes)
4 views

7894110371ControlStructures

The document discusses control structures in Python, focusing on conditional execution and loops. It covers various types of selection statements, including one-way, two-way, and chained conditionals, as well as nested conditionals and loop constructs like 'while' and 'for' loops. Additionally, it introduces loop control statements, inbuilt functions, and the use of modules, providing examples and sample programs for practical understanding.

Uploaded by

stefinmathew0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

7894110371ControlStructures

The document discusses control structures in Python, focusing on conditional execution and loops. It covers various types of selection statements, including one-way, two-way, and chained conditionals, as well as nested conditionals and loop constructs like 'while' and 'for' loops. Additionally, it introduces loop control statements, inbuilt functions, and the use of modules, providing examples and sample programs for practical understanding.

Uploaded by

stefinmathew0
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Control Structures

Module III
Conditional Execution(Selection
statements)
Control Structures
• The Python programs encountered so far are
very simple.
• These follow the sequencing construct .
• Python also supports the other two
constructs, viz. selection, and looping.
• These constructs enable Python to solve real-
life problems effectively.
One-way selection statement
• It needs to check conditions and change the behaviour of the
program accordingly
• Conditional statements give us this ability

• The simplest form is the if statement


• If the condition is true then the indented statements get executed
• Syntax:
if condition:
statements
Eg: if x>0:
print(“Positive”)
Alternative Execution( Two-way selection
statement )
• A second form of if statement is alternative
execution,in which there are two possibilities
and the condition determines which one get
executed

– Eg. If x>0:
print(“positive”)
else:
print(“negative”)
Chained conditionals or Multi-way selection
statement
• Sometimes there are more than two possibilities and we
need more than two branches
• One way to express a computation like this is to use
chained conditionals using if…elif…else statement
• Syntax:
if condition 1:
Body of if
elif condition 2:
Body of elif
else:
Body of else
Chained conditionals
• Eg:
if x>0:
print(“positive”)
elif x<0:
print(“negative”)
else:
print(“zero”)
Nested conditionals
• One conditionals can be nested within another
• Syntax
if condition 1:
statement 1
else:
if condition 2:
statement 2
else:
condition 3
Nested conditionals
• Eg:
if x=0:
print(“zero”)
else:
if x>0:
print(“positive”)
else:
print(“negative”)
Sample Programs
1.Write a python program to find the area and
Perimeter of a circle

2.Write a program to find the roots of a quadratic


equation

3.Write a program to calculate the simple interest using


the formula

4.Write a program to swap two numbers without using


temporary variable
Sample Programs
5.Write a program to find the largest of three numbers.

6.Write a program to check whether a number is even or odd.

7.Write a program to enter Name,Roll No.,Marks of three


subjects of student.Calculate the total and percentage
.If percentage>=50 print Result=“pass” else Result=“Fail”.
If percentage is :
>=90 print Grade=“Excellent”,
>=80 and <90 Grade=“Good” ,
>=70 and <80 Grade=“Satisfactory”,
>=50 and <70 Grade=“Poor”
Escape Sequences
• Escape sequences are the way Python
expresses special characters, such as the tab,
the newline, and the backspace
Escape Sequence Meaning

\b Backspace
\n Newline
\t Horizontal tab
\’ Single quotation mark

\\” Double quotation mark


\\ The \ character
Repetition statements or loops
• Python supports two types of loops
→ those that repeat an action a fixed number
of times (definite iteration)
→and those that act until a condition becomes
false (conditional iteration).
Iterations

• Loops executes a group of statements as long


as required
• Two options:

1.while…. statement
2.for…. statement
Conditional Iteration: The While loop
• Conditional iteration requires that a condition be tested within
the loop to determine whether the loop should continue.

• Executes a group of statements as long as a condition is True

• Python’s while loop is tailormade for this type of control logic.


• Syntax:
while condition:
statements
Example
Here is the code to print the first 10 natural numbers, but this
time with while.

Eg:
i=1
while(i<=10):
print(i ,end=“ “)
i=i+1
print(“End”)

Output
1 2 3 4 5 6 7 8 9 10
Definite iteration: The For loop
• Repeats a set of statements over a group of values
• Group of values can be a range of integers ,specified with the
range function
• range() function dictates the number of iterations
• range(k) when used with for causes the loop to iterate k
times.

• Syntax:
For variable in group of Values:
statements
Example
Eg.To print first 10 natural numbers

for x in range(1,11):
print(x)

for x in range(1,6):
print( x, “Square is”, x**x)

for i in range(5):
print("Hello")
Range function
• Specifies a range of integers
• Range(start,stop)
– The integers between start(inclusive) and stop(exclusive)
– It can also accept a third value specifying the change between values
Range(start,stop,step)
Eg.
>>>for x in range(1,6):
print (x)

>>>for x in range(5,0,-1):
print( x)
o/p
5
4
3
2
1
Nested loops
• It is possible to have a loop inside another loop.
• We can have a for loop inside a while loop or inside another
for loop.
• The same is possible for while loops too.
• The enclosing loop is called the outer loop, and the other loop
is called the inner loop.
• The inner loop will be executed once for each iteration of the
outer loop:
Example
for i in range(1,5): #This is the outer loop
for j in range(1,5): #This is the inner loop .
print(j, end=" ")
print(“\n”)

Output
1234
1234
1234
1234

• The loop variable i varies from 1 to 4 (not 5).


• For each value of i, the variable j varies from 1 to 4.
• The statement print(j, end=" ") prints the j values on a single line, and the
statement print() takes the control to the next line after every iteration of the
outer loop.
Loop Control Statements
• Python provides three loop control statements
that control the flow of execution in a loop.
–Break
– continue
Break statement
• Break statement is used to jump out of the loop
• The break statement is used to terminate loops.
• Any statements inside the loop following the break will be
neglected, and the control goes out of the loop.
• break stops the current iteration and skips the succeeding
iterations (if any) and passes the control to the first statement
following (outside) the loop
• Example 1
for num in range(1,5):
if num%2==0:
print(num,"is even")
break
print("The number is",num)
print("Outside the loop")
• Output

The number is 1
2 is even
Outside the loop
Example 2
Example
i=0
while i<10:
num=int(input())
if num==5:
break
else:
print(num)
i++
print(“Finished the loop”)
Continue statement
• The continue statement is used to bypass the
remainder of the current iteration through a
loop.
• The loop does not terminate when a continue
statement is encountered.
• Rather, the remaining loop statements are
skipped and the control proceeds directly to
the next pass through the loop
Example
for num in range(1,5):
if num%2==0:
print(num,"is even")
continue
print("The number is",num)
print("Outside the loop")

Output
The number is 1
2 is even
The number is 3
4 is even
Outside the loop
Print statement
• Syntax:
print( value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)
• Parameters:

– value(s) : Any value, and as many as you like. Will be converted to string
before printed

– sep=’separator’ : (Optional) Specify how to separate the objects, if there is


more than one. Default :’ ‘

– end=’end’: (Optional) Specify what to print at the end. Default : ‘\n’

– file : (Optional) An object with a write method. Default :sys.stdout

– flush : (Optional) A Boolean, specifying if the output is flushed (True) or


buffered (False). Default: False

Sample Programs
• 1.Write a program to find the sum of the first n natural numbers

• 2.Write a program to find the sum of the squares of first n natural


numbers

• 3.Write a program to display the multiplication table of a given


number

• 4.Write a python program to generate prime numbers up to a certain


limit

• 5.Write a program to display the first n fibonacci numbers


Sample Programs
• 6.Write a program to find the GCD of two
given numbers
• 7.Write a program to check whether a given
number is palindrome or not
• 8.Write a program to check whether a number
is Armstrong or not
• 9.Write a program to display Armstrong
numbers within a range
• 10.Write a program to find the largest of n
numbers given .
Using Inbuilt functions and modules
• Functions is a named sequence of statements
that performs a computation
• It is a group related statements that perform a
specific task
• Function requires
• Function definition
• Function call
Inbuilt functions
• Inbuilt functions
-Already defined

Eg:
type( ),max( ),min( ),int( ),str( )

>>>int(‘60’)
60
>>>str(60)
‘60’
>>>max(10,45)
45
>>>min( 67,12)
12
Mathematical functions
• Some of the mathematical functions are defined in the module
“math”

• Module
– Module is a file that contains a collection of related function
– Before we use a module,we have to import it

>>>import math
>>>root=math.sqrt(16)
>>>print(root)
4
>>>print(math.pi)
3.141592653589793
>>>print(math.pow(3,2))
9
Mathematical functions
• Two ways to import module

1)import math
-we get a module object named math
-the math object contains constants like pi and functions like
sqrt( ),sin ( ),exp( ) etc
-the module object along with dot operator is used to access a
function or variables
Eg: math.sqrt()
2)from math import pi
-This will import an object from a module
-Now we can access ‘pi’ directly
>>>print(pi)
3.14….
-to import everything from the module we can use
from math import *
Modules

• The advantage of importing everything from math module is


that your code can be more concise

• The disadvantage is that there might be coflicts between names


defined in different modules or between a name from a module
and one of your variable.
map function
• Python map() applies a function on all the items of an iterator given as input.
• An iterator, for example, can be a list, a tuple, a set, a dictionary, a string, and it
returns an iterable map object.
• Python map() is a built-in function.
• The map() function is going to apply the given function on all the items inside the
iterator and return an iterable map object i.e a tuple, a list, etc.
• The map() function takes two inputs as a function and an iterable object. The
function that is given to map() is a normal function, and it will iterate over all the
values present in the iterable object given.
• function: A mandatory function to be given to map, that will be applied to all the
items available in the iterator.
• iterator: An iterable compulsory object. It can be a list, a tuple, etc. You can pass
multiple iterator objects to map() function.
• The output of the map() function, as seen in the output, is a map object displayed on
the screen as <map object at 0x0000002C59601748>.
Syntax:

map(function, iterator1,iterator2 ...iteratorN)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy