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

Coding WordProblems Ch1 to Ch6 (1)

Uploaded by

mua347175
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Coding WordProblems Ch1 to Ch6 (1)

Uploaded by

mua347175
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

PYTHON PROGRAMMING III YEAR/II SEM MRCET

OUTCOMES: Upon completion of the course, students will be able to


 Read, write, execute by hand simple Python programs.
 Structure simple Python programs for solving problems.
 Decompose a Python program into functions.
 Represent compound data using Python lists, tuples, dictionaries.
 Read and write data from/to files in Python Programs

TEXT BOOKS
1.Allen B. Downey, ``Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition,
Updated for Python 3, Shroff/O‘Reilly Publishers, 2016.
2.R. Nageswara Rao, “Core Python Programming”, dreamtech
3. Python Programming: A Modern Approach, Vamsi Kurama, Pearson

REFERENCE BOOKS:
1. Core Python Programming, W.Chun, Pearson.
2. Introduction to Python, Kenneth A. Lambert, Cengage
3. Learning Python, Mark Lutz, Orielly
PYTHON PROGRAMMING III YEAR/II SEM MRCET
2.0
Example:
x = 35e3
y = 12E4
z = -87.7e100

print(type(x))
print(type(y))
print(type(z))

Output:

<class 'float'>
<class 'float'>
<class 'float'>

Boolean:

Objects of Boolean type may have one of two values, True or False:

>>> type(True)

<class 'bool'>

>>> type(False)

<class 'bool'>

String:

1. Strings in Python are identified as a contiguous set of characters represented in the


quotation marks. Python allows for either pairs of single or double quotes.

• 'hello' is the same as "hello".

• Strings can be output to screen using the print function. For example: print("hello").

>>> print("mrcet college")

mrcet college

>>> type("mrcet college")

<class 'str'>
8
PYTHON PROGRAMMING III YEAR/II SEM MRCET
For example −

a= 100 # An integer assignment

b = 1000.0 # A floating point

c = "John" # A string

print (a)

print (b)

print (c)

This produces the following result −

100

1000.0

John

Multiple Assignment:

Python allows you to assign a single value to several variables simultaneously.

For example :

a=b=c=1

Here, an integer object is created with the value 1, and all three variables are assigned to the
same memory location. You can also assign multiple objects to multiple variables.

For example −

a,b,c = 1,2,"mrcet“

Here, two integer objects with values 1 and 2 are assigned to variables a and b respectively,
and one string object with the value "john" is assigned to the variable c.

Output Variables:

The Python print statement is often used to output variables.

Variables do not need to be declared with any particular type and can even change type after
they have been set.

12
PYTHON PROGRAMMING III YEAR/II SEM MRCET
x=5 # x is of type int
x = "mrcet " # x is now of type str
print(x)

Output: mrcet

To combine both text and a variable, Python uses the “+” character:

Example

x = "awesome"
print("Python is " + x)

Output

Python is awesome

You can also use the + character to add a variable to another variable:

Example

x = "Python is "
y = "awesome"
z=x+y
print(z)

Output:

Python is awesome

Expressions:

An expression is a combination of values, variables, and operators. An expression is


evaluated using assignment operator.

Examples: Y=x + 17

>>> x=10

>>> z=x+20

>>> z

30

13
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print("Value of (a + b) * (c / d) is ", e)

e = a + (b * c) / d; # 20 + (150/5)
print("Value of a + (b * c) / d is ", e)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/opprec.py
Value of (a + b) * c / d is 90.0
Value of ((a + b) * c) / d is 90.0
Value of (a + b) * (c / d) is 90.0
Value of a + (b * c) / d is 50.0

Comments:

Single-line comments begins with a hash(#) symbol and is useful in mentioning that the
whole line should be considered as a comment until the end of line.

A Multi line comment is useful when we need to comment on many lines. In python, triple
double quote(“ “ “) and single quote(‘ ‘ ‘)are used for multi-line commenting.

Example:

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/comm.py

30

18
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Functions:

Functions and its use: Function is a group of related statements that perform a specific task.
Functions help break our program into smaller and modular chunks. As our program grows
larger and larger, functions make it more organized and manageable. It avoids repetition and
makes code reusable.

Basically, we can divide functions into the following two types:

1. Built-in functions - Functions that are built into Python.

Ex: abs(),all().ascii(),bool()………so on….

integer = -20

print('Absolute value of -20 is:', abs(integer))

Output:

Absolute value of -20 is: 20

2. User-defined functions - Functions defined by the users themselves.

def add_numbers(x,y):
sum = x + y
return sum

print("The sum is", add_numbers(5, 20))

Output:

The sum is 25

Flow of Execution:
1. The order in which statements are executed is called the flow of execution
2. Execution always begins at the first statement of the program.
3. Statements are executed one at a time, in order, from top to bottom.
4. Function definitions do not alter the flow of execution of the program, but remember
that statements inside the function are not executed until the function is called.
5. Function calls are like a bypass in the flow of execution. Instead of going to the next
statement, the flow jumps to the first line of the called function, executes all the
statements there, and then comes back to pick up where it left off.

20
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Note: When you read a program, don’t read from top to bottom. Instead, follow the flow of
execution. This means that you will read the def statements as you are scanning from top to
bottom, but you should skip the statements of the function definition until you reach a point
where that function is called.
Example:
#example for flow of execution
print("welcome")
for x in range(3):
print(x)
print("Good morning college")
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py
welcome
0
1
2
Good morning college
The flow/order of execution is: 2,3,4,3,4,3,4,5

------------------------------------------

21
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/flowof.py
hi
hello
Good morning
mrcet
done!
The flow/order of execution is: 2,5,6,7,2,3,4,7,8

Parameters and arguments:

Parameters are passed during the definition of function while Arguments are passed during
the function call.

Example:
#here a and b are parameters

def add(a,b): #//function definition


return a+b

#12 and 13 are arguments


#function call
result=add(12,13)
print(result)

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/paraarg.py

25

There are three types of Python function arguments using which we can call a function.

1. Default Arguments
2. Keyword Arguments
3. Variable-length Arguments

Syntax:
def functionname():
22
PYTHON PROGRAMMING III YEAR/II SEM MRCET
statements
.
.
.
functionname()

Function definition consists of following components:

1. Keyword def indicates the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of writing
identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements must have
same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Example:

def hf():

hello world

hf()

In the above example we are just trying to execute the program by calling the function. So it
will not display any error and no output on to the screen but gets executed.

To get the statements of function need to be use print().

#calling function in python:

def hf():

print("hello world")

hf()

Output:

hello world

-------------------------------
23
PYTHON PROGRAMMING III YEAR/II SEM MRCET
def hf():

print("hw")

print("gh kfjg 66666")

hf()

hf()

hf()

Output:

hw
gh kfjg 66666
hw
gh kfjg 66666
hw
gh kfjg 66666
---------------------------------

def add(x,y):

c=x+y

print(c)

add(5,4)

Output:

def add(x,y):

c=x+y

return c

print(add(5,4))

Output:

-----------------------------------
24
PYTHON PROGRAMMING III YEAR/II SEM MRCET

def add_sub(x,y):

c=x+y

d=x-y

return c,d

print(add_sub(10,5))

Output:

(15, 5)

The return statement is used to exit a function and go back to the place from where it was
called. This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.

def hf():

return "hw"

print(hf())

Output:

hw

----------------------------

def hf():

return "hw"

hf()

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu.py

>>>
25
PYTHON PROGRAMMING III YEAR/II SEM MRCET
-------------------------------------

def hello_f():

return "hellocollege"

print(hello_f().upper())

Output:

HELLOCOLLEGE

# Passing Arguments

def hello(wish):

return '{}'.format(wish)

print(hello("mrcet"))

Output:

mrcet

------------------------------------------------

Here, the function wish() has two parameters. Since, we have called this function with two
arguments, it runs smoothly and we do not get any error. If we call it with different number
of arguments, the interpreter will give errors.

def wish(name,msg):

"""This function greets to

the person with the provided message"""

print("Hello",name + ' ' + msg)

wish("MRCET","Good morning!")

Output:

Hello MRCET Good morning!

26
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Below is a call to this function with one and no arguments along with their respective error
messages.

>>> wish("MRCET") # only one argument


TypeError: wish() missing 1 required positional argument: 'msg'
>>> wish() # no arguments
TypeError: wish() missing 2 required positional arguments: 'name' and 'msg'

----------------------------------------------

def hello(wish,hello):

return “hi” '{},{}'.format(wish,hello)

print(hello("mrcet","college"))

Output:

himrcet,college

#Keyword Arguments

When we call a function with some values, these values get assigned to the arguments
according to their position.

Python allows functions to be called using keyword arguments. When we call functions in
this way, the order (position) of the arguments can be changed.

(Or)

If you have some functions with many parameters and you want to specify only some
of them, then you can give values for such parameters by naming them - this is
called keyword arguments - we use the name (keyword) instead of the position
(which we have been using all along) to specify the arguments to the function.

There are two advantages - one, using the function is easier since we do not need to
worry about the order of the arguments. Two, we can give values to only those
parameters which we want, provided that the other parameters have default argument
values.

def func(a, b=5, c=10):


print 'a is', a, 'and b is', b, 'and c is', c
27
PYTHON PROGRAMMING III YEAR/II SEM MRCET

func(3, 7)
func(25, c=24)
func(c=50, a=100)

Output:

a is 3 and b is 7 and c is 10
a is 25 and b is 5 and c is 24
a is 100 and b is 5 and c is 50

Note:

The function named func has one parameter without default argument values,
followed by two parameters with default argument values.

In the first usage, func(3, 7), the parameter a gets the value 3, the parameter b gets the
value 5 and c gets the default value of 10.

In the second usage func(25, c=24), the variable a gets the value of 25 due to the
position of the argument. Then, the parameter c gets the value of 24 due to naming i.e.
keyword arguments. The variable b gets the default value of 5.

In the third usage func(c=50, a=100), we use keyword arguments completely to


specify the values. Notice, that we are specifying value for parameter c before that
for a even though a is defined before c in the function definition.

For example: if you define the function like below

def func(b=5, c=10,a): # shows error : non-default argument follows default argument

-------------------------------------------------------

def print_name(name1, name2):

""" This function prints the name """

print (name1 + " and " + name2 + " are friends")

#calling the function

print_name(name2 = 'A',name1 = 'B')


28
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Output:

B and A are friends

#Default Arguments

Function arguments can have default values in Python.

We can provide a default value to an argument by using the assignment operator (=)

def hello(wish,name='you'):

return '{},{}'.format(wish,name)

print(hello("good morning"))

Output:

good morning,you

---------------------------------------------

def hello(wish,name='you'):

return '{},{}'.format(wish,name) //print(wish + ‘ ‘ + name)

print(hello("good morning","nirosha")) // hello("good morning","nirosha")

Output:

good morning,nirosha // good morning nirosha

Note: Any number of arguments in a function can have a default value. But once we have a
default argument, all the arguments to its right must also have default values.

This means to say, non-default arguments cannot follow default arguments. For example, if
we had defined the function header above as:

def hello(name='you', wish):

Syntax Error: non-default argument follows default argument

------------------------------------------

def sum(a=4, b=2): #2 is supplied as default argument


29
PYTHON PROGRAMMING III YEAR/II SEM MRCET
""" This function will print sum of two numbers

if the arguments are not supplied

it will add the default value """

print (a+b)

sum(1,2) #calling with arguments

sum( ) #calling without arguments

Output:

Variable-length arguments

Sometimes you may need more arguments to process function then you mentioned in the
definition. If we don’t know in advance about the arguments needed in function, we can use
variable-length arguments also called arbitrary arguments.

For this an asterisk (*) is placed before a parameter in function definition which can hold
non-keyworded variable-length arguments and a double asterisk (**) is placed before a
parameter in function which can hold keyworded variable-length arguments.

If we use one asterisk (*) like *var, then all the positional arguments from that point till the
end are collected as a tuple called ‘var’ and if we use two asterisks (**) before a variable like
**var, then all the positional arguments from that point till the end are collected as
a dictionary called ‘var’.

def wish(*names):
"""This function greets all
the person in the names tuple."""

# names is a tuple with arguments


for name in names:
print("Hello",name)

wish("MRCET","CSE","SIR","MADAM")

30
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Output:

Hello MRCET
Hello CSE
Hello SIR
Hello MADAM

#Program to find area of a circle using function use single return value function with
argument.

pi=3.14
def areaOfCircle(r):

return pi*r*r
r=int(input("Enter radius of circle"))

print(areaOfCircle(r))

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter radius of circle 3
28.259999999999998

#Program to write sum different product and using arguments with return value
function.

def calculete(a,b):

total=a+b

diff=a-b

prod=a*b

div=a/b

mod=a%b

31
PYTHON PROGRAMMING III YEAR/II SEM MRCET
return total,diff,prod,div,mod

a=int(input("Enter a value"))

b=int(input("Enter b value"))

#function call

s,d,p,q,m = calculete(a,b)

print("Sum= ",s,"diff= ",d,"mul= ",p,"div= ",q,"mod= ",m)

#print("diff= ",d)

#print("mul= ",p)

#print("div= ",q)

#print("mod= ",m)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value 6
Sum= 11 diff= -1 mul= 30 div= 0.8333333333333334 mod= 5

#program to find biggest of two numbers using functions.

def biggest(a,b):
if a>b :
return a
else :
return b

a=int(input("Enter a value"))
b=int(input("Enter b value"))
#function call
big= biggest(a,b)
print("big number= ",big)

Output:

32
PYTHON PROGRAMMING III YEAR/II SEM MRCET
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value-2
big number= 5

#program to find biggest of two numbers using functions. (nested if)

def biggest(a,b,c):
if a>b :
if a>c :
return a
else :
return c
else :
if b>c :
return b
else :
return c

a=int(input("Enter a value"))
b=int(input("Enter b value"))
c=int(input("Enter c value"))
#function call
big= biggest(a,b,c)
print("big number= ",big)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter a value 5
Enter b value -6
Enter c value 7
big number= 7

#Writer a program to read one subject mark and print pass or fail use single return
values function with argument.

def result(a):
if a>40:
return "pass"
33
PYTHON PROGRAMMING III YEAR/II SEM MRCET
else:
return "fail"
a=int(input("Enter one subject marks"))

print(result(a))

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
Enter one subject marks 35
fail

#Write a program to display mrecet cse dept 10 times on the screen. (while loop)

def usingFunctions():
count =0
while count<10:
print("mrcet cse dept",count)
count=count+1

usingFunctions()

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fu1.py
mrcet cse dept 0
mrcet cse dept 1
mrcet cse dept 2
mrcet cse dept 3
mrcet cse dept 4
mrcet cse dept 5
mrcet cse dept 6
mrcet cse dept 7
mrcet cse dept 8
mrcet cse dept 9

34
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Conditional (if):

The if statement contains a logical expression using which data is compared and a decision
is made based on the result of the comparison.

Syntax:
if expression:
statement(s)
If the boolean expression evaluates to TRUE, then the block of statement(s) inside the if
statement is executed. If boolean expression evaluates to FALSE, then the first set of
code after the end of the if statement(s) is executed.

if Statement Flowchart:

Fig: Operation of if statement

Example: Python if Statement

a=3
if a > 2:
print(a, "is greater")
print("done")

a = -1
if a < 0:
print(a, "a is smaller")
print("Finish")

Output:
36
PYTHON PROGRAMMING III YEAR/II SEM MRCET

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if1.py
3 is greater
done
-1 a is smaller
Finish
--------------------------------

a=10

if a>9:

print("A is Greater than 9")

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if2.py

A is Greater than 9

Alternative if (If-Else):

An else statement can be combined with an if statement. An else statement contains the
block of code (false block) that executes if the conditional expression in the if statement
resolves to 0 or a FALSE value.

The else statement is an optional statement and there could be at most only one else
Statement following if.

Syntax of if - else :

if test expression:
Body of if stmts
else:
Body of else stmts
If - else Flowchart :

37
PYTHON PROGRAMMING III YEAR/II SEM MRCET

Fig: Operation of if – else statement

Example of if - else:

a=int(input('enter the number'))


if a>5:
print("a is greater")
else:
print("a is smaller than the input given")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number 2
a is smaller than the input given
----------------------------------------

a=10
b=20
if a>b:
print("A is Greater than B")
else:
print("B is Greater than A")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/if2.py
B is Greater than A

38
PYTHON PROGRAMMING III YEAR/II SEM MRCET
print("a is greater")
elif b>c:
print("b is greater")
else:
print("c is greater")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number5
enter the number2
enter the number9
a is greater
>>>
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelse.py
enter the number2
enter the number5
enter the number9
c is greater

-----------------------------
var = 100
if var == 200:
print("1 - Got a true expression value")
print(var)
elif var == 150:
print("2 - Got a true expression value")
print(var)
elif var == 100:
print("3 - Got a true expression value")
print(var)
else:
print("4 - Got a false expression value")
print(var)
print("Good bye!")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/ifelif.py

3 - Got a true expression value

100

Good bye!
40
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Example Programs:

1. --------------------------------------
i=1
while i<=6:
print("Mrcet college")
i=i+1
output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh1.py
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
Mrcet college
2. -----------------------------------------------------
i=1

while i<=3:
print("MRCET",end=" ")
j=1
while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh2.py

MRCET CSE DEPT

MRCET CSE DEPT

MRCET CSE DEPT

3. --------------------------------------------------

i=1
42
PYTHON PROGRAMMING III YEAR/II SEM MRCET
j=1
while i<=3:
print("MRCET",end=" ")

while j<=1:
print("CSE DEPT",end="")
j=j+1
i=i+1
print()
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh3.py

MRCET CSE DEPT


MRCET
MRCET

4. ----------------------------------------

i=1
while (i < 10):
print (i)
i = i+1
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh4.py
1
2
3
4
5
6
7
8
9

2. ---------------------------------------
a=1
b=1
while (a<10):
print ('Iteration',a)
a=a+1
b=b+1

43
PYTHON PROGRAMMING III YEAR/II SEM MRCET
if (b == 4):
break
print ('While loop terminated')

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh5.py
Iteration 1
Iteration 2
Iteration 3
While loop terminated
--------------------------
count = 0
while (count < 9):
print("The count is:", count)
count = count + 1
print("Good bye!")

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/wh.py =
The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4
The count is: 5
The count is: 6
The count is: 7
The count is: 8
Good bye!

For loop:

Python for loop is used for repeated execution of a group of statements for the desired
number of times. It iterates over the items of lists, tuples, strings, the dictionaries and other
iterable objects

Syntax: for var in sequence:


Statement(s) A sequence of values assigned to var in each iteration
Holds the value of item
in sequence in each iteration

44
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Sample Program:

numbers = [1, 2, 4, 6, 11, 20]


seq=0
for val in numbers:
seq=val*val
print(seq)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/fr.py
1
4
16
36
121
400

Flowchart:

45
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Iterating over a list:

#list of items
list = ['M','R','C','E','T']
i=1

#Iterating over the list


for item in list:
print ('college ',i,' is ',item)
i = i+1

Output:

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/lis.py
college 1 is M
college 2 is R
college 3 is C
college 4 is E
college 5 is T

Iterating over a Tuple:

tuple = (2,3,5,7)
print ('These are the first four prime numbers ')
#Iterating over the tuple
for a in tuple:
print (a)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/fr3.py
These are the first four prime numbers
2
3
5
7

Iterating over a dictionary:

#creating a dictionary
college = {"ces":"block1","it":"block2","ece":"block3"}

#Iterating over the dictionary to print keys


print ('Keys are:')

46
PYTHON PROGRAMMING III YEAR/II SEM MRCET
for keys in college:
print (keys)

#Iterating over the dictionary to print values


print ('Values are:')
for blocks in college.values():
print(blocks)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/dic.py
Keys are:
ces
it
ece
Values are:
block1
block2
block3

Iterating over a String:

#declare a string to iterate over


college = 'MRCET'

#Iterating over the string


for name in college:
print (name)

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/strr.py
M
R
C
E
T

Nested For loop:


When one Loop defined within another Loop is called Nested Loops.
Syntax:
for val in sequence:
for val in sequence:
47
PYTHON PROGRAMMING III YEAR/II SEM MRCET
statements
statements

# Example 1 of Nested For Loops (Pattern Programs)


for i in range(1,6):
for j in range(0,i):
print(i, end=" ")
print('')
Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py
1
22
333
4444
55555
--------------------------

# Example 2 of Nested For Loops (Pattern Programs)

for i in range(1,6):

for j in range(5,i-1,-1):

print(i, end=" ")

print('')

C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/nesforr.py

Output:
11111

2222

333

44

48
PYTHON PROGRAMMING III YEAR/II SEM MRCET
while test expression

# code inside while loop


If condition:
break (if break condition satisfies it jumps to outside loop)
# code inside while loop
# code outside while loop

Example:

for val in "MRCET COLLEGE":


if val == " ":
break
print(val)

print("The end")

Output:
M
R
C
E
T
The end

# Program to display all the elements before number 88

for num in [11, 9, 88, 10, 90, 3, 19]:


print(num)
if(num==88):
print("The number 88 is found")
print("Terminating the loop")
break

Output:
11
9
88
The number 88 is found

50
PYTHON PROGRAMMING III YEAR/II SEM MRCET
Terminating the loop

#-------------------------------------
for letter in "Python": # First Example
if letter == "h":
break
print("Current Letter :", letter )

Output:
C:/Users/MRCET/AppData/Local/Programs/Python/Python38-32/pyyy/br.py =

Current Letter : P

Current Letter : y

Current Letter : t

Continue:

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.

Flowchart:

The following shows the working of break statement in for and while loop:

51

You might also like