0% found this document useful (0 votes)
3 views48 pages

Python Unit2

The document provides notes on Python programming, focusing on control flow statements, variables, and data types. It introduces Python's features, modes of execution, and the importance of keywords and identifiers. Additionally, it discusses the structure of statements and expressions, as well as the characteristics of various data types, including numbers and strings.

Uploaded by

j.priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
0% found this document useful (0 votes)
3 views48 pages

Python Unit2

The document provides notes on Python programming, focusing on control flow statements, variables, and data types. It introduces Python's features, modes of execution, and the importance of keywords and identifiers. Additionally, it discusses the structure of statements and expressions, as well as the characteristics of various data types, including numbers and strings.

Uploaded by

j.priya
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
You are on page 1/ 48

EASWARI ENGINEERING COLLEGE

(AUTONOMOUS)
DEPARTMENT OF ARTIFICIAL INTELLIGENCE AND DATA
SCIENCE

231GES201T – PROBLEM SOLVING THROUGH PYTHON


PROGRAMMING

Unit II -Notes

I YEAR –B.E/B.TECH
(Common to all Branches)

PREPARED BY APPROVED BY

J.PRIYA HOD

1
UNIT II
CONTROL FLOW STATEMENTS

Python interpreter, interactive mode and script mode; variables, expressions, statements;
values and data types; Operators and Precedence of operators, comments; Conditionals:
conditional, alternative, chained conditional, nested conditional; Iterations: while, for,
break, continue.

1. INTRODUCTION TO PYTHON:
Python is a general-purpose interpreted, interactive, object-oriented, and high-
level programming language.
It was created by Guido van Rossum during 1985- 1990.Python got its name from “Monty
Python’s flying circus”. Python was released in the year 2000.
❖ Python is interpreted: Python is processed at runtime by the interpreter. You
do not need to compile your program before executing it.
❖ Python is Interactive: You can actually sit at a Python prompt and interact with
the interpreter directly to write your programs.
❖ Python is Object-Oriented: Python supports Object-Oriented style or technique
of programming that encapsulates code within objects.
❖ PythonisaBeginner'sLanguage:Pythonisagreatlanguageforthebeginner-
level programmers and supports the development of a wide range of
applications.
Python Features:
❖ Easy-to-learn: Python is clearly defined and easily readable. The structure
of the program is very simple. It uses few key words.
❖ Easy-to-maintain: Python's source code is fairly easy-to-maintain.
❖ Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.
❖ Interpreted: Python is processed at runtime by the interpreter. So, there is no
needtocompileaprogrambeforeexecutingit.Youcansimplyruntheprogram.
❖ Extensible: Programmers can embed python within their C,C++,Javascript
ActiveX, etc.
❖ Free and Open Source: Anyone can freely distribute it, read the source code, and
edit it.
❖ High Level Language: When writing programs, programmers concentrate on
solutions of the current problem, no need to worry about the low level details.
❖ Scalable: Python provides a better structure and support for large programs
than shell scripting.
Applications:
❖ Bit Torrent file sharing
❖ Google search engine, Youtube
❖ Intel, Cisco, HP,IBM
❖ i–Robot
❖ NASA

2
Python interpreter:
Interpreter: To execute a program in a high-level language by translating it one line at a
time.
Compiler: To translate a program written in a high-level language into a low-
level language all at once, in preparation for later execution.

MODES OF PYTHONINTERPRETER:
Python Interpreter is a program that reads and executes Python code. It uses 2 modes
of Execution.
1. Inter active mode
2. Script mode
Interactive mode:
❖ Interactive Mode, as the name suggests, allows us to interact with OS.
❖ When we type Python statement, interpreter displays the result(s)
immediately.
Advantages:
❖ Python, in interactive mode, is good enough to learn, experiment or explore.
❖ Working in interactive mode is convenient for beginners and for testing small
pieces of code.
Drawback:
❖ We cannot save the statements and have to retype all the statements once again to
re-run them.
In interactive mode, you type Python programs and the interpreter displays the result:
>>> 1 + 1
2
The chevron, >>>, is the prompt the interpreter uses to indicate that it is ready for you
to enter code. If you type 1 + 1, the interpreter replies 2.
>>> print ('Hello, World!')
Hello, World!
This is an example of a print statement. It displays a result on the screen. In this case,
the result is the words.
3
Script mode:
❖ In script mode, type python program in a file and then use interpreter to
execute the content of the file.
❖ Scripts can be saved to disk for future use. Python scripts have
the extension .py, meaning that the filename ends with.py
❖ Save the code with filename.py and run the interpreter in script mode to
execute the script.

Interactive mode Script mode


A way of using the Python interpreter by A way of using the Python interpreter to
typing commands and expressions at the read and execute statements in a script.
prompt.
Can’t save and edit the code Can save and edit the code
If we want to experiment with the code, If we are very clear about the code, we can
we can use interactive mode. use script mode.
we cannot save the statements for further we can save the statements for further use
use and we have to retype and we no need to retype
all the statements to re-run them. all the statements to re-run them.
We can see the results immediately. We cant see the code immediately.

Integrated Development Learning Environment(IDLE):


❖ Is a graphical user interface which is completely written in Python.
❖ It is bundled with the default implementation of the python language and also
comes with optional part of the Python packaging.
Features of IDLE:
o Multi-window text editor with syntax highlighting.
o Auto completion with smart indentation.
Python shell to display output with syntax highlighting.

4
VARIABLES:

❖ A variable allows us to store a value by assigning it to a name, which can be used


later.
❖ Named memory locations to store values.
❖ Programmers generally choose names for their variables that are meaningful.
❖ It can be of any length. No space is allowed.
❖ We don't need to declare a variable before using it. In Python, we simply
assign a value to a variable and it will exist.
Assigning value to variable:
Syntax:
<variable name> = <expression>
Eg: num=10, here num is the variable name storing the value 10
Variables and assignment operator:
Variables are assigned values by use of the assignment operator.
Examples:
num=10
num=num+1
a=5
b = 3.2
c = "Hello"
KEYWORDS:

Keywords are the reserved words in Python.


❖ Keywords cannot be used as variable name, function name or any other
identifier.
❖ They are used to define the syntax and structure of the Python language.
❖ Keywords are case sensitive.

IDENTIFIERS:

Identifier is the name given to entities like class, functions, variables etc. in
Python.
❖ Identifiers can be a combination of letters in lower case(a to z) or uppercase(A to
Z) or digits (0 to 9) or an underscore (_).
❖ An identifier cannot start with a digit.
Keywords cannot be used as identifiers.

5
❖ Cannot use special symbols like !, @, #, $, % etc. in identifier.
❖ Identifier can be of any length.
Example:
Names like myClass, var_1, and this_is_a_long_variable

Valid declarations Invalid declarations


Num Number 1
Num num1
Num1 addition of program
_NUM 1Num
NUM_temp2 Num.no
IF if
Else else

STATEMENTS AND EXPRESSIONS:


Statements:
-Instructions that a Python interpreter can executes are called statements.
-A statement is a unit of code like creating a variable or displaying a value.
>>> n = 17
>>> print(n)
Here, the first line is an assignment statement that gives a value to
n. The second line is a print statement that displays the value of n.

Expressions:
-An expression is a combination of values, variables, and operators.
- A value all by itself is considered an expression, and also a variable.
- So the following are all legal expressions:

>>> 42
42
>>>a=2
>>>
a+3+27
>>> z=("hi"+"friend")
>>> print(z)
hifriend

VALUES AND DATATYPES


Value:
Value can be any letter, number or string. Values are the core things that Python
programs manipulate. Every value has a type that defines the kinds of things that
programs can do with values of that type.
6
Examples:

In the above interpreter mode, 5, 15, hello, python, program are the values used
Literal
A literal is a sequence of one or more characters that stands for itself.
Example:12 is a literal. A literal is the way a value of a data type looks to a
programmer. The programmer can use a literal in a program to mention a
data value.

Data type:
Every value in Python has a data type. It is a set of values, and the allowable
operations on those values. For example, the integer data type consists of the
set of integers, and operators for addition, subtraction, multiplication, and
division, among others.

Python standard data types:

Numbers:
❖ Number data type stores Numerical Values.
❖ This data type is immutable [i.e. values/items cannot be changed].
❖ Python supports integers, floating point numbers and complex numbers.
A numeric literal is a literal containing only the digits 0–9, an optional sign
character ( 1 or 2 ), and a possible decimal point. Number data types store
numeric values. Python supports four different numerical types –
7
➢ int (signed integers)
➢ long (long integers, they can also be represented in octal and hexadecimal)
➢ float (floating point real values)
➢ complex (complex numbers)

int long float complex


10 51924361L 0.0 3.14j
100 -0x19323L 15.20 45.j
-786 0122L -21.9 9.322e-36j
080 0xDEFABCECBDAECBFBAEl 32.3+e18 .876j
Commas are never used in numeric literals.
Booleans
Booleans are either true or false. Python has two constants, named True and False,
which can be used to assign Boolean values directly. Expressions can also evaluate
to a Boolean value. Booleans can be treated as numbers. True is 1; False is 0.

type() and isinstance()


The type() function is used to check the type of any value or variable.
The isinstance() function is used to check whether a value or variable is of a given
type.
>>> 5
5
>>>type(5)
<class'int'>
>>> 5.2
5.2
>>>type(5.2)
<class'float'>
>>>
"hello"
'hello'
>>> type("hello")
<class 'str'>
>>>
True
8
True
>>> type(True)
<class 'bool'>
>>> a=2+3j
>>> type(a)
<class 'complex'>
>>>
isinstance(a,complex) True
>>> isinstance(a,int)
False

#Program to demonstrate the various numbers in Numeric data types


a=10
print(a)
print(type(a))
b="python"
print(b)
print(type(b))
c=6.4
print(c)
print(type(c))
d=6+5j print(d)
print(type(d))
e=-5678
print(e)
print(type(e))
f=2.12e-2
print(f)
print(type(f))
g=-5.7
print(g)
print(type(g))
a=0
b=False c=a+b
print(a)
print(b)
print(type(a))
print(type(b))
print(c)
print(type(c))

9
Sequence:
❖ A sequence is an ordered collection of items, indexed by positive integers.
❖ It is a combination of mutable (value can be changed) and immutable (values
cannot be changed) data types.
❖ There are three types of sequence data type available in Python, they are
1. Strings
2. Lists
3. Tuples
Strings:
A string is a sequence of characters enclosed in matching pain of single or
double quotation marks. A string may contain zero or more characters,
including letters, digits, special characters, and blanks. A string consisting of
only a pair of matching quotes (with nothing in between) is called the empty
string
Examples:
'Hello' 'Smith, John' "Baltimore, Maryland 21210"

Multi-line strings can be denoted using triple quotes, ''' or """.


Example:
>>> a="Iam a single-line string"
>>> print(a)
Iam a single-line string
>>> a="""Iam multi-line string"""
>>>
print(a)
Iam
multi-line
string
>>> a='''Iam multi-line string
using triple single quotes'''
>>> print(a)
Iam multi-line string using
triple single quotes
>>>

Indexing/Accessing Strings:
The characters of the string can be accessed as one character at a time with
the bracket operator and index. In Python, the indexes start from 0: the first
character is at index 0, the second is at index 1, and so on.

Example:
>>> s="python"
>>> print(s)
python
10
>>>
print(s[0])
p
>>> print(s[-1])
n
>>>
Positive indexing helps in accessing the string from the beginning

• Negative subscript helps in accessing the string from the end.


• Subscript 0 or –ve n(where n is length of the string) displays the first element.
Example: A[0] or A[-5] will display “H”
• Subscript 1 or –ve (n-1) displays the second element.
Example: A[1] or A[-4] will display ”E”
• Operations on string:
i. Indexing
ii. Slicing
iii. Concatenation
iv. Repetitions
v. Membership
Creating a string >>> s="good morning" Creating the list with elements of
different data types.
Indexing >>>print(s[2]) ❖ Accessing the item in the
o position0
>>>print(s[6]) ❖ Accessing the item in the
O position2
Slicing( ending >>>print(s[2:]) - Displaying items from 2nd till
position-1) od morning last.
Slice operator is >>>print(s[:4]) - Displaying items from
used to extract Good 1stposition till 3rd.
part of a data
type
Concatenation >>>print(s+"friends") -Adding and printing the
good morning friends characters of two strings.

Repetition >>>print(s*2) Creates new strings,


good morninggood concatenating multiple copies of
morning the samestring

11
in, not in >>> s="good morning" Using membership operators to
(membership >>>"m" in s check a particular character is in
operator) True string or not. Returns true if
>>> "a" not in s present.
True

Program for strings and string operations


#Program to demonstrate strings and string operations
s1="Python"
s2='program'
print(s1)
print(s1[0])
print(s1[2:5])
print(s1[2:])
print(s1+s2)
print(s2*3)
print(s1[-1:])
print(s2[-4:-2]) #slicing with step as third parameter
ss = "Sammy Shark!"
print(ss[6:11])
print(ss[6:11:1])
print(ss[0:12:2])
print(ss[0:12:4])
print(ss[::4])
print(ss[::-1])

OUTPUT:

Strings are immutable


The strings are immutable, i.e. they cannot be changed in-place after
they are created. For example, you can’t change a string by assigning to
one of its positions.
Example to show strings are immutable:
>>> a="python"
>>> a[5]
'n'
>>> a[5]='N'
Traceback (most recent call last):
File "<pyshell#16>", line 1, in
<module> a[5]='N'
12
TypeError: 'str' object does not support item assignment
>>>
Control characters and Escape Sequences
Control characters are special characters that are not displayed on the
screen. Rather, they control the display of output (among other things).
Control characters do not have a corresponding keyboard character.
Therefore, they are represented by a combination of characters called an
escape sequence.
An escape sequence begins with an escape character that causes the
sequence of characters following it to “escape” their normal meaning. The
backslash (\) serves as the escape character in Python. For example, the
escape sequence '\n', represents the newline control character , used to begin
a new screen line.
An example of its use is given below,
print('Hello\n Jennifer Smith')
which is displayed as follows,

Here is a list of all the escape sequence supported by Python.

Escape Sequence in Python


Escape Description
Sequence
\newline Backslash and newline ignored
\\ Backslash
\' Single quote
\" Double quote
\a ASCII Bell
\b ASCII Backspace
\f ASCII Formfeed
\n ASCII Linefeed
\r ASCII Carriage Return
\t ASCII Horizontal Tab
\v ASCII Vertical Tab
\ooo Character with octal value ooo
\xHH Character with hexadecimal value
HH

#Program To Demonstrate Escape Sequences


str="\"google\""
print(str)
str1='Example\'s'
print(str1)
print("\n This is an example of escape sequences")
print("\b example for backspace")
print("\a example for bell")
print("\f example for form feed")
print("\rexample for carriage return in escape sequences")
13
print("\texample \tfor \thorizontal \ttab")
print("\v\nexample \v\nfor \v\nvertical \v\ntab")

Output:

"google"
Example's

This is an example of escape sequences


example for backspace
example for bell

example for form feed

example for carriage return in escape sequences


example for horizontal tab

example

for

vertical

tab

Lists
List is an ordered sequence of items. It is one of the most used datatypes in
Python and is very flexible. All the items in a list do not need to be of the
same type. Items separated by commas are enclosed within brackets [ ].
Operations on list:
Indexing Slicing
Concatenation
Repetitions
Updation, Insertion, Deletion

Creating a list >>>list1=["python", 7.79, 101, Creating the list with


"hello”] Elements of different data
>>>list2=["god",6.78,9] types.
Indexing >>>print(list1[0]) ❖ Accessing the item in
python the position0
>>>list1[2] ❖ Accessing the item in
101
the position2

14
Slicing( ending >>>print(list1[1:3]) - Displaying items from 1st
position-1) [7.79, 101] till2nd.
Slice operator is >>>print(list1[1:]) - Displaying items from
used to extract [7.79, 101, 'hello'] 1stposition till last.
part of a string, or
some part of a list
Python
Concatenation >>>print( list1+list2) -Adding and printing the
['python', 7.79, 101, 'hello', 'god', items of two lists.
6.78, 9]
Repetition >>>list2*3 Creates new strings,
['god', 6.78, 9, 'god', 6.78, 9, 'god', concatenating multiple
6.78, 9] copies of the same string
Updating the list >>>list1[2]=45 Updating the list using index
>>>print( list1) value
[‘python’, 7.79, 45, ‘hello’]
Inserting an >>>list1.insert(2,"program") Inserting an element in 2nd
element >>> print(list1) position
['python', 7.79, 'program', 45,
'hello']
Removing an >>>list1.remove(45) Removing an element by
element >>> print(list1) giving the element directly
['python', 7.79, 'program', 'hello']
Lists are mutable:
Lists are mutable, meaning; value of elements of a list can be altered.
Example:
>>> a = [1,2,3]
>>> a[2]=4
>>> a [1, 2, 4]
# Program To demonstrate lists

list1 = [ 'abcd', 786 , 2.23, 'xxx', 70.2 ]


list2 = [123,'yyy']
print(list1) # Prints complete list print(list1[0])
# Prints first element of the list
print(list1[1:3]) # Prints elements starting from 2nd till 3rd
print(list1[2:]) # Prints elements starting from 3rd element
print(list2 * 2) # Prints list two times
print(list1 + list2) # Prints
concatenated lists print(list1[-1])
print(list1[-3:])
print(list1[-4:-1])
print(list1[:])
OUTPUT:
['abcd', 786, 2.23, 'xxx', 70.2]
abcd
15
[786, 2.23]
[2.23, 'xxx', 70.2]
[123, 'yyy', 123, 'yyy']
['abcd', 786, 2.23, 'xxx', 70.2, 123, 'yyy']
70.2
[2.23, 'xxx', 70.2]
[786, 2.23, 'xxx']
['abcd', 786, 2.23, 'xxx', 70.2]
Tuples:
Tuple is an ordered sequences of items enclosed within parentheses () where
items are separated by commas. Tuples are same as list. The only difference is
that tuples are immutable.
>>> t = (5,'program', 1+3j)
Benefit of Tuple:
❖ Tuples are faster than lists.
❖ If the user wants to protect the data from accidental changes, tuple can be used.
❖ Tuples can be used as keys in dictionaries, while lists can't.
Basic Operations:
Creating a tuple >>>t=("python", 7.79, 101, Creating the tuple with elements
"hello”) of different data types.
Indexing >>>print(t[0]) ❖ Accessing the item in
python the position0
>>>t[2] ❖ Accessing the item in
101
the position2
Slicing( ending >>>print(t[1:3]) ❖ Displaying items from1st
position -1) (7.79, 101) till2nd.

Concatenation >>>t+("ram", 67) Adding tuple elements at



('python', 7.79, 101, 'hello', 'ram',
the end of another tuple
67) elements
Repetition >>>print(t*2) ❖ Creates new strings,
('python', 7.79, 101, 'hello', concatenating multiple copies of
'python', 7.79, 101, 'hello') the same string

Difference between tuple and list


The difference between the two is that we cannot change the elements of a tuple
once it is assigned whereas in a list, elements can be changed.
Example:
>>> l=[1,3.4,"hello"]
>>> print(l) [1, 3.4, 'hello']
>>> t=(1,3.4,"hello")
>>> print(t)
(1, 3.4, 'hello')
>>> l[0]=2
16
>>> print(l)
[2, 3.4, 'hello']
>>> t[0]=2
Traceback (most recent call last):
File "<pyshell#6>", line 1, in
<module> t[0]=2
TypeError: 'tuple' object does not support item assignment
#To demonstrate tuples
t1 = ('abcd', 786 , 2.23, 'xxx', 70.2 )
t2 = (123, 'yyy')
print(t1) # Prints complete list
print(t1[0]) # Prints first element of the
list print(t1[1:3]) # Prints elements
starting from 2nd till 3rd
print(t1[2:]) # Prints elements starting
from 3rd element
print(t2 * 2) # Prints list two times
print(t1 + t2) # Prints concatenated lists
print(t1[-1])
print(t1[-3:])
print(t1[-4:-1])
print(t1[:])
#difference between tuple and list
list1 = ['abcd', 786 , 2.23, 'xxx', 70.2]
list1[2]=1000 #lists are mutable
print(list1)
t1 = ('abcd', 786 , 2.23, 'xxx', 70.2 )
t1[2]=1000 #tuples are immutable
print(t1)
OUTPUT:
('abcd', 786, 2.23, 'xxx', 70.2)
abcd
(786, 2.23)
(2.23, 'xxx', 70.2)
(123, 'yyy', 123, 'yyy')
('abcd', 786, 2.23, 'xxx', 70.2, 123, 'yyy')
70.2
(2.23, 'xxx', 70.2)
(786, 2.23, 'xxx')
('abcd', 786, 2.23, 'xxx', 70.2)
['abcd', 786, 1000, 'xxx', 70.2]
Traceback (most recent call last):
line 19, in
<module>
t1[2]=1000
TypeError: 'tuple' object does not support item assignment
17
Dictionaries:
Dictionary is an unordered collection of key-value pairs. In Python,
dictionaries are defined within braces {} with each item being a pair in the
form key: value. Key and value can be of any type.

>>> d = {1:'value','key':2}
>>> type(d)
<class 'dict'>
We use keys as index to retrieve the respective value. But values cannot used to
access keys.

Creating a >>> food = {"ham":"yes", "egg" : Creating the dictionary with


dictionary "yes", "rate":450 } elements of different data
>>>print(food) types.
{'rate': 450, 'egg': 'yes', 'ham':
'yes'}
Indexing >>>>print(food["rate"]) Accessing the item with keys.
450
Slicing( ending >>>print(t[1:3]) Displaying items from 1st till
position -1) (7.79, 101) 2nd.

#Program to demonstrate dictionaries


dict1={1:"first line","second":2}
print(dict1)
print(dict1[1]) #keys are used to access values
dict1[3]="third line"
print(dict1)
print(dict1.keys())
print(dict1.values())
dict1[3]="new line"
print(dict1)
print(dict1[2])#values cannot be used to access keys
OUTPUT:

{1: 'first line', 'second': 2}


first line
{1: 'first line', 'second': 2, 3: 'third line'}
dict_keys([1, 'second', 3])
dict_values(['first line', 2, 'third line'])
{1: 'first line', 'second': 2, 3: 'new line'}
Traceback (most recent call
last):
print(dict1[2])#values cannot be used to access keys
KeyError: 2

18
2.5
>>>str(25)
'25'
Coercion vs. Type Conversion
Coercion is the implicit (automatic) conversion of operands to a common type.

Type conversion is the explicit conversion of operands to a specific type. Type


conversion can be applied even if loss of information results.

Data type Compile time Run time


int a=10 a=int(input(“enter a”))
float a=10.5 a=float(input(“enter a”))
string a=”panimalar” a=input(“enter a string”)
list a=[20,30,40,50] a=list(input(“enter a list”))
tuple a=(20,30,40,50) a=tuple(input(“enter a tuple”))

INPUT AND OUTPUT

INPUT: Input is data entered by user (end user) in the program. In python, input ()
function is available for input.
Syntax for input() is:
variable = input (“data”)

Example:
>>> x=input("enter the name:")
enter the name: george
>>>y=int(input("enter the number"))
enter the number 3
#python accepts string as default data type. conversion is required for type.

OUTPUT: Output can be displayed to the user using Print statement .


Syntax:
print (expression/constant/variable)
Example:
>>> print ("Hello")
Hello

COMMENTS:
A hash sign (#) that is not inside a string literal is the beginning of a
comment. All characters after the #, up to the end of the physical line, are
part of the comment .It extends up to the newline character.
19
Comments are for programmers for better understanding of a program.
Python Interpreter ignores comment.

Example:

On execution, the output is as follows:

OUTPUT:

this is single line comment


>>>
Single line and multi-line comment:

The single line comment is written using #

Multi line comment: The multiple line comments are written using triple
single quotes („ „ „) or triple double quotes(“ “ “)
DOCSTRING:
❖ Docstring is short for documentation string.
❖ It is a string that occurs as the first statement in a module, function, class, or method
definition. We must write what a function/class does in the docstring.
❖ Triple quotes are used while writing docstrings.
❖ Accessing Docstrings: The docstrings can be accessed using the doc method of
the object or using the help function .
Syntax:
Functionname.__doc__
Example:

LINES AND INDENTATION:


❖ Most of the programming languages like C, C++, Java use braces { } to define a
block of code. But, python uses indentation.

20
❖ Blocks of code are denoted by line indentation.
❖ It is a space given to the block of codes for class and function definitions or
flow control.

Example:

QUOTATION IN PYTHON:
Python accepts single ('), double (") and triple (''' or """) quotes to denote string
literals.
Anything that is represented using quotations are considered as string.

❖ Single quotes(' ') Eg, 'This a string in single quotes'


❖ double quotes(" ") Eg, "'This a string in double quotes'"
❖ triplequotes(""" """) Eg, This is a paragraph. It is made up of multiple lines
and sentences."""
Multiple assignments in a single line
In Python, multiple assignments can be made in a single statement as follows: a,
b, c = 5, 3.2, "Hello"
This statement assigns the values 5 to a, 3.2 to b and “Hello” to c
If we want to assign the same value to multiple variables at once, we can do this
as x = y = z = 5
This assigns the value 5 to all the three variables.
Use of id()
Variables may also be assigned to the value of another variable. The id function
produces a unique number identifying a specific value (object) in memory.
Variables num and k are both associated with the same value 10 in memory. One way to
see this is by use of built-in function id

TUPLE ASSIGNMENT

An assignment to all of the elements in a tuple using a single assignment statement.


❖ Python has a very powerful tuple assignment feature that allows a tuple of
variables on the left of an assignment to be assigned values from a tuple on the
21
right of the assignment.
❖ The left side is a tuple of variables; the right side is a tuple of values.
❖ Each value is assigned to its respective variable.
❖ All the expressions on the right side are evaluated before any of the
assignments. This feature makes tuple assignment quite versatile.
❖ Naturally, the number of variables on the left and the number of values on the
right have to be the same.

Example:
-It is useful to swap the values of two variables. With conventional assignment
statements, we have to use a temporary variable. For example, to swap a and b:

Swap two numbers Output:


a=2;b=3
print(a,b) (2, 3)
temp = a (3, 2)
a=b >>>
b = temp
print(a,b)
-Tuple assignment solves this problem neatly:

(a, b) = (b, a)

-One way to think of tuple assignment is as tuple packing/unpacking.


In tuple packing, the values on the left are ‘packed’ together in a tuple:

>>>b = ("George",25,"20000") # tuplepacking

-In tuple unpacking, the values in a tuple on the right are ‘unpacked’ into the
variables/names on the right:
>>>b = ("George", 25, "20000") # tuple packing
>>>(name, age, salary)=b # tupleunpacking
>>>name
'George'
>>>age
25
>>>salary
'20000'
-The right side can be any kind of sequence (string,list,tuple)

22
Example:
-To split an email address in to user name and a domain
>>> mailid='[email protected]'
>>> name,domain=mailid.split('@')
>>> print (name)
god
>>> print (domain)
abc.org

OPERATORS:
❖ Operators are the constructs which can manipulate the value of operands.
❖ Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and +
is called operator.
❖ Types of Operators:
-Python language supports the following types of operators
• Arithmetic Operators
• Comparison (Relational)Operators
• Assignment Operators
• Logical Operators
• Bitwise Operators
• Membership Operators
• Identity Operators
Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like
addition, subtraction, multiplication etc.
Arithmetic operators in Python
Operator Meaning Example
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x/y
% Modulus - remainder of the division of left operand by the right x%y
(remainder of x/y)
// Floor division - division that results into whole number adjusted x // y
to the left in the number line
** Exponent - left operand raised to the power of right x**y
(x to the power y)

Example 1: Arithmetic operators in Python


#To demonstrate the arithmetic operators
x=10
y=8
a=x+y
print("The addition is:",a)
b=x-y
print("The subtraction is:",b)
c=x*y
23
print("The multiplication is:",c)
d=x/y
print("The division is:",d)
e=x%y
print("The modulo division is:",e)
f=x//y
print("The floor division is:",f)

g=x**y
print("The exponentiation is:",g)

OUTPUT:

When you run the program, the output


will be:
The addition is: 18
The subtraction is: 2
The multiplication is: 80
The division is: 1.25
The modulo division is: 2
The floor division is: 1
The exponentiation is: 100000000

Comparison (Relational)Operators:
• Comparison operators are used to compare values.
• It either returns True or False according to the condition. Assume, a=10 and b=5

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is

becomes true. not true.

!= If values of two operands are not equal, then condition (a!=b) is


becomes true. true

> If the value of left operand is greater than the value of right (a > b) is
operand, then condition becomes true. not true.

< If the value of left operand is less than the value of right (a < b) is
operand, then condition becomes true. true.

>= If the value of left operand is greater than or equal to the (a >= b) is
value of right operand, then condition becomes true. not true.

24
<= If the value of left operand is less than or equal to the value (a <= b) is
of right operand, then condition becomes true. true.

Example
a=10 Output:
b=5 a>b=> True
print("a>b=>",a>b) a>b=> False
print("a>b=>",a<b) a==b=> False
print("a==b=>",a==b) a!=b=> True
print("a!=b=>",a!=b) a>=b=> False
print("a>=b=>",a<=b) a>=b=> True
print("a>=b=>",a>=b)

Assignment Operators:
-Assignment operators are used in Python to assign values to variables.
Operator Description Example

= Assigns values from right side operands to left side c=a+b


operand assigns
value of a +
b into c

+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent
to c = c +a

-= Subtract It subtracts right operand from the left operand and c -= a is


AND assign the result to left operand equivalent
to c = c -a

*= Multiply It multiplies right operand with the left operand and c *= a is


AND assign the result to left operand equivalent
to c = c *a

/= Divide It divides left operand with the right operand and c /= a


AND assign the result to left operand is
equivalent
to c = c /ac
/= a is
equivalent
to c = c /a
%= It takes modulus using two operands and assign the c %= a is
Modulu result to left operand equivalent
s AND to c = c % a

25
**= Exponent Performs exponential (power) calculation on c **= a is
AND operators and assign value to the leftoperand equivalent
to c = c ** a

//= Floor It performs floor division on operators and assign c //= a is


Division value to the left operand equivalent
to c = c // a
Example:
#To demonstrate assignment operators
x=10
y=12
y+=x print(y)
y-=x print(y)
y*=x print(y)
y/=x print(y)
y%=x print(y)
y**=x
print(y)
y//=x
print(y)
OUTPUT
12
120
12.0
2.0
1024.0

Logical Operators:
-Logical operators are the and, or, not operators.

Example Output
a = True x and y is False
b = False x or y is True
print('a and b is',a and b) not x is False
print('a or b is',a or b)
print('not a is',not a)

26
Truth tables for And ,or ,not
Truth table for or
Truth table for and
A B A or B
A B A and B
True True True True True True Truth table for
True False False True False True not
False True False A not A
False True True
False False False True False
False False False

Bitwise Operators:
• A bitwise operation operates on one or more-bit patterns at the level of
individual bits
Example: Let x = 10 (0000 1010 in binary) and
y = 4 (0000 0100 in binary)

Example:
#To demonstrate bitwise operators
x=10
y=12
print("The bitwise and is:",x&y)
print("The bitwise or is:",x|y)
print("The bitwise xor is:",x^y)
print("The bitwise not is:",~x)
print("The bitwise left shift by 2 positions is:",x<<2)
print("The bitwise right shift by 2 positions is:", x>>2)
OUTPUT:
The bitwise and is: 8 The
bitwise or is: 14 The
bitwise xor is: 6 The
bitwise not is: -11
The bitwise left shift by 2 positions is: 40
The bitwise right shift by 2 positions is: 2
Membership Operators:

❖ Evaluates to find a value or a variable is in the specified sequence of string, list,


tuple, dictionary or not.
❖ Let, x=[5,3,6,4,1]. To check particular item in list or not, in and not in
operators are used.
27
Example:
x=[5,3,6,4,1]
>>>5 in x
True
>>>5 not in x
False

Identity Operators:
❖ They are used to check if two values (or variables) are located on the same
part of the memory.

Example
x =5 Output
y =5 False
x2 = 'Hello' True
y2 = 'Hello'
print(x1 is not y1)
print(x2 is y2)
OPERATOR PRECEDENCE:

When an expression contains more than one operator, the order of evaluation
depends on the order of operations.
Operator Description

** Exponentiation (raise to the power)

~+- Complement, unary plus and minus (method


names for the last two are +@ and -@)

* / % // Multiply, divide, modulo and floor division

28
+- Addition and subtraction

>><< Right and left bitwise shift

& Bitwise 'AND'

^| Bitwise exclusive `OR' and regular `OR'

<= <>>= Comparison operators

<> == != Equality operators

= %= /= //= -= += *= **= Assignment operators

is is not Identity operators

in not in Membership operators

not or and Logical operators


-For mathematical operators, Python follows mathematical convention.
-The acronym PEMDAS (Parentheses, Exponentiation, Multiplication, Division, Addition,
Subtraction) is a useful way to remember the rules:
❖ Parentheses have the highest precedence and can be used to force an expression to
evaluate in the order you want. Since expressions in parentheses are evaluated
first, 2 * (3-1)is 4, and (1+1)**(5-2) is8.
❖ You can also use parentheses to make an expression easier to read, as in (minute
* 100) / 60, even if it doesn’t change the result.
❖ Exponentiation has the next highest precedence, so 1 + 2**3 is 9, not 27, and2
*3**2 is 18, not 36.
❖ Multiplication and Division have higher precedence than Addition and Subtraction.
So 2*3-1 is 5, not 4, and 6+4/2 is 8, not5.
❖ Operators with the same precedence are evaluated from left to right (except
exponentiation).
Example:
a=9-12/3+3*2-1 A=2*3+4%5-3/2+6
a=? A=6+4%5-3/2+6 find m=?
a=9-4+3*2-1 A=6+4-3/2+6 m=-43||8&&0||-2
a=9-4+6-1 A=6+4-1+6 m=-43||0||-2
a=5+6-1 A=10-1+6 m=1||-2
a=11-1 A=9+6 m=1
a=10 A=15

29
a=2,b=12,c=1 a=2*3+4%5-3//2+6
d=a<b>c a=2,b=12,c=1 a=6+4-1+6
d=2<12>1 d=a<b>c-1 a=10-1+6
d=1>1 d=2<12>1-1 a=15
d=0 d=2<12>0
d=1>0
d=1

Associativity of operators:

Associativity decides the order in which the operators with same precedence are executed.
There are two types of associativity:
Left-to-right: In left-to-right associativity, the operator of same precedence are executed from
the left side first. Eg:*, // are examples for left to right associative operators
Right-to-left: In right-to-left associativity, the operator of same precedence are executed from
right side first. Eg: ** is right to left associative
Example:
>>> 3*4//6 2
>>> 3*(4//6) 0
>>> 3**4**2 43046721
>>> (3**4)**2 6561
>>>

CONTROL FLOW STATEMENTS:

Control flow is the order that instructions are executed in a program. A control
statement is a statement that determines the control flow of a set of instructions.
There are three fundamental forms of control that programming languages provide-
sequential control , selection control , and iterative control
Sequential control is an implicit form of control in which instructions are executed in
the order that they are written. A program consisting of only sequential control is
referred to as a ―straight- line program
Selection control is provided by a control statement that selectively executes instructions
Iterative control is provided by an iterative control statement that repeatedly
executes instructions. Each is based on a given condition.

30
CONDITIONALS
The conditional statements are the statements that alter the flow of execution of the
program based on a condition. These statements decide upon the result of test
condition and execute certain set of statements. These are known as selection or
decision making or branching statements or conditional statements

The following are the conditional statements in python:


• if statement (conditional)
• if..else statement(alternative)
• if..elif..else statement(chained conditional)
• Nested if else(nested conditional

Conditional(if):
conditional (if) is used to test a condition, if the condition is true the statements
inside if will be executed.
syntax:

Flowchart:

Example:
1. Program to provide flat Rs 500, if the purchase amount is greater than2000.
2. Program to provide bonus mark if the category is sports.

Program to provide flat Rs 500, if the purchase amount output


is greater than 2000.
purchase=int(input(“enter your purchase amount”)) enter your purchase
if(purchase>=2000): amount 2500
purchase=purchase-500 amount to
print(“amount to pay”,purchase) pay 2000

31
Program to provide bonus mark if the category is sports output
m=int(input(“enter ur mark out of 100”)) enter ur mark out of
c=input(“enter ur categery G/S”) 100 85
if(c==”S”): enter ur categery G/S
m=m+5 S
print(“mark is”,m) mark is 90

Conditional(if-else)
In the alternative the condition must be true or false. In this else statement can be
combined with if statement. The else statement contains the block of code that executes
when the condition is false. If the condition is true statements inside the if get executed
otherwise else part gets executed. The alternatives are called branches, because they are
branches in the flow of execution.
syntax:

Flowchart:

Examples:
1. odd or even number
2. positive or negative number
3. leap year or not
4. greatest of two numbers
5. eligibility for voting

Odd or even number Output


n=int(input("enter a number")) enter a number
if(n%2==0): 4
print("even number") even number
else:
print("odd number")
32
positive or negative number Output
n=int(input("enter a number")) enter a number
if(n>=0): 8
print("positive number") positive number
else:
print("negative number")
leap year or not Output
y=int(input("enter a year")) enter a year
if(y%4==0): 2000
print("leap year") leap year
else:
print("not leap year")

greatest of two numbers Output


a=int(input("enter a value:")) enter a value:
b=int(input("enter b value:")) 4
if(a>b): enter b value:7
print("greatest:",a) greatest: 7
else:
print("greatest:",b)

eligibility for voting Output


age=int(input("enter ur age:")) enter ur age:78
if(age>=18): you are eligible for vote
print("you are eligible for vote")
else:
print("you are eligible for vote")

Chained conditionals(if-elif-else)
• The elif is short for elseif.
• This is used to check more than one condition.
• If the condition1 is False, it checks the condition2 of the elif block. If all the
conditions are False, then the else part is executed.
• Among the several if...elif...else part, only one part is executed according to
the condition.
• The if block can have only one else block. But it can have multiple elif blocks.
• The way to express a computation like that is a chained conditional.
syntax:

33
Flowchart:

Example:
1. student mark system
2. traffic light system
3. compare two numbers
4. roots of quadratic equation
student mark system Output
mark=int(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")

34
compare two numbers Output
x=int(input("enter x value:")) enter x value:5
y=int(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


a=int(input("enter a value:")) enter a value:1
b=int(input("enter b value:")) enter b value:0
c=int(input("enter c value:")) enter c value:0
d=(b*b-4*a*c) same and real roots
if(d==0):
print("same and real roots")
elif(d>0):
print("diffrent real roots")
else:
print("imaginagry roots")

Nested conditionals
One conditional can also be nested within another. Any number of condition can be
nested inside one another. In this, if the condition is true it checks another if condition1.
If both the conditions are true statement1 get executed otherwise statement2 get
execute. if condition is false statement3 gets executed
Syntax:

35
Flowchart:

Example:
1. greatest of three numbers
2. positive negative or zero

greatest of three numbers output


a=int(input(“enter the value of a”)) enter the value of a 9
b=int(input(“enter the value of b”)) enter the value of a 1
c=int(input(“enter the value of c”)) enter the value of a 8
if(a>b): the greatest no is 9
if(a>c):
print(“the greatest no is”,a)
else:
print(“the greatest no is”,c)
else:
if(b>c):
print(“the greatest no is”,b)
else:
print(“the greatest no is”,c)
positive negative or zero output
n=int(input("enter the value of n:")) enter the value of n:-
if(n==0): 9 the number is
print("the number is zero") negative
else:
if(n>0):
print("the number is positive")
else:
print("the number is negative")

36
ITERATION:
The process of repeated execution of a set of statements is called iteration or looping
.Python has two statements for iteration.
• while
• for

state
while
for
State:
Transition from one process to another process under specified condition with in a
time is called state.
Whileloop:
• While loop statement in Python is used to repeatedly executes set of
statement as long as a given condition istrue.
• In while loop, test expression is checked first. The body of the loop is entered
only if the test expression is True. After one iteration, the test expression is
checked again. This process continues until the test expression evaluates
toFalse.
• In Python, the body of the while loop is determined throughindentation.
• The statements inside the while start with indentation and the first
unindented line marks the end.

Syntax:

Flowchart:

else in while loop:


❖ If else statement is used within while loop , the else part will be executed when the
condition become false.

37
❖ The statements inside for loop and statements inside else will also execute.
Program output
i=1 1
while(i<=5): 2
print(i) 3
i=i+1 4
else: 5
print("the number greater than 5") the number greater than 5
Nested while:
• While inside another while is called nested while
• The syntax for a nested while loop statement in Python programming language is
as follows
• Syntax

While condition1:
while
condition2:
statement2(
s) statement1(s)
Nested While( to multiply numbers):
i=1 4
while 5
i<4: 8
j=4 10
while j<6: 12
print(i*j) 15
j=j+1
i=i+1
Examples:
1. program to find sum of n numbers:
2. program to find factorial of a number
3. program to find sum of digits of a number:
4. Program to Reverse the given number:
5. Program to find number is Armstrong number or not
6. Program to check the number is palindrome or not
Sum of n numbers: output
n=int(input("enter n")) enter n
i=1 10
sum=0 55
while(i<=n):
sum=sum+i
i=i+1
print(sum)
38
Factorial of a numbers: output
n=int(input("enter n")) enter n
i=1 5
fact=1 120
while(i<=n):
fact=fact*i
i=i+1
print(fact)
Sum of digits of a number: output
n=int(input("enter the number")) enter a
sum1=0 number 123
while n>0: 6
d=n%10
sum1=sum1+
d n=n//10
print(sum1)
Reverse the given number: output
n=int(input("enter the number")) enter a number
rev=0 123
while n>0: 321
d=n%10
rev=(rev*10)+d
n=n//10
print(rev)
Armstrong number or not output
n=int(input("enter the number")) enter a number153
arm=0 The given number is Armstrong number
temp=n
while temp>0:
d=temp%10
arm=arm+(d**3)
temp=temp//10
if n==arm:
print(n,"is a armstrong number")
else:
print(n,"is not armstrong")

39
Palindrome or not output
n=int(input("Enter a number:")) enter a number121
temp=n The given no is palindrome
reverse=0
while(n>0):
d=n%10
reverse=(reverse*10)+d
n=n//10
if(temp==reverse):
print("The number is palindrome")
else:
print("The number is not palindrome")

For loop:
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.

Sequence can be a list, strings or tuples


s.no sequences example output
p
1. For loop in string for i in "python":
print(i) y
t
h

o
n
2
2. For loop in list for i in [2,3,5,6,9]: 3
print(i) 5
6
9
for i in (2,3,1): 2
3. For loop in tuple print(i) 3
1

40
❖ for in range:
- can generate a sequence of numbers using range() function. range(10)
will generate numbers from 0 to 9 (10 numbers).
❖ In range function have to define the start, stop and step size
as range(start,stop,step size). step size defaults to 1 if not provided.
syntax

Flowchart:

else in for loop:


❖ If else statement is used in for loop, the else statement is executed when the loop
has reached the limit.
❖ The statements inside for loop and statements inside else will also execute.
example output
for i in range(1,6): 1
print(i) 2
else: 3
print("the number greater than 6") 4
5 the number greater than 6

Nested for:
• for inside another for is called nested for
• The syntax for a nested for loop statement in Python programming language is as
follows
• Syntax

for iterating_var in sequence:


for iterating_var in sequence:
statements(s)
statements(s)

41
example output
for i in range(1,4): 4
for j in range(4,7): 5
print(i*j) 6
8
10
12
12
15
18

Examples:
1. print nos divisible by 5 not by10:
2. Program to print Fibonacci series.
3. Program to find factors of a given number
4. check the given number is perfect number or not
5. check the no is prime or not
6. Print first n prime numbers
7. Program to print prime numbers in range

print nos divisible by 5 not by 10 output


n=int(input("enter a")) enter a:30
for i in range(1,n,1): 5
if(i%5==0 and i%10!=0): 15
print(i) 25

Fibonacci series output


a=0 Enter the number of terms: 6
b=1 Fibonacci Series:
n=int(input("Enter the number of terms: ")) 01
print("Fibonacci Series: ") 1
print(a,b) 2
for i in range(1,n,1): 3
c=a+b 5
print(c) 8
a=b
b=c

42
find factors of a number Output

n=int(input("enter a number:")) enter a number:10


for i in range(1,n+1): 1
if(n%i==0): 2
print(i) 5
10

check the no is prime or not output

n=int(input("enter a number")) enter a no:7


for i in range(2,n): The num is a prime number.
if(n%i==0):
print("The num is not a prime")
break
else:
print("The num is a prime number.")

check a number is perfect number or not Output

n=int(input("enter a number:")) enter a number:6


sum1=0 the number is perfect number
for i in range(1,n,1):
if(n%i==0):
sum1=sum1+i
if(sum1==n):
print("the number is perfect number")
else:
print("the number is not perfect number")

Program to print first n prime numbers Output

number=int(input("enter no of prime enter no of prime numbers to


numbers to be displayed:")) be displayed:5
count=1 2
n=2 3
while(count<=number): 5
for i in range(2,n): 7
if(n%i==0): 11
break
else:
print(n)
count=count+1
n=n+1

43
Program to print prime numbers in range output:
lower=int(input("enter a lower range")) enter a lower
upper=int(input("enter a upper range")) range5 enter a
for n in range(lower,upper + 1): upper range15 5
if n > 1: 7
for i in range(2,n): 11
if (n % i) == 0: 13
break
else:
print(n)

range() and xrange():


range():

The range is a built-in function in Python that represents an immutable sequence of


numbers. Generally, Python range is used in the for loop to iterate a block of code
for the given number of times.
Syntax:
range([start],stop,[step])

where
• stop is the required parameter.
• The start specifies where to start the range. The default value is0.
• The step specifies the step between each number. The default is1.
• All parameters are integers
• All parameters can be positive or negative
xrange():
This function works similar to range().This function returns the generator object
that can be used to display numbers only by looping. Only particular range is
displayed on demand and hence called―lazy evaluation―.

Syntax:

xrange([start],stop,[step])

where
• stop is the required parameter.
• The start specifies where to start the range. The default value is0.
• The step specifies the step between each number. The default is1.
• All parameters are integers
• All parameters can be positive or negative
Difference between range() and xrange():

s.no range() xrange()


1 returns – the list as returns – xrange() object
return
type
44
2 consumes more consumes less memory
memory
3 As range() returns the xrange() returns the
list, all the operations
that can be applied on xrange object,
the list can be used on operations associated
it to list cannot
be applied on them
4 Slower Faster
Example:
#Examples for range()
#range with one parameter(stop)
for i in range(5):
print(i)
OUTPUT:
0
1
2
3
4
#range with two parameters(start,stop)
for i in range(5,10):
print(i)
OUTPUT:
5
6
7
8
9
#range with three parameters(start,stop,step)
for i in range(5,10,2):
print(i)

OUTPUT:
5
7
9
Loop Control Structures
Loops iterate over a block of code until test expression is false. The statements
that are used to terminate the current iteration or even the whole loop without
checking test expression
The following are the loop control statements in python:
• break
• continue
• pass

45
BREAK
❖ Break statements can alter the flow of a loop.
❖ It terminates the current loop and executes the remaining statement outside the
loop.
❖ If the loop has else statement, that will also gets terminated and come out of the
loop completely.
Syntax:
break

Flowchart

example Output
for i in w
"welcome": e
if(i=="c"): l
brea
k
print(i)
CONTINUE
It terminates the current iteration and transfer the control to the next iteration in th e
loop.
Syntax:Continue

46
Flowchart

Example: Output
for i in "welcome": w
if(i=="c"): e
continue l
print(i) o
m
e
PASS
It is used as a placeholder for future implementation of functions, loops, etc. In Python
programming, pass is a null statement. The difference between a comment and pass
statement in Python is that, while the interpreter ignores a comment entirely, pass is not
ignored. However, nothing happens when pass is executed. It results into no operation
(NOP).

Syntax:
Pass

47
Example Output
for i in w
“welcome”: if (i e
== “c”): l
pas c
s o
print(i) m
e

Difference between break and continue


break continue
It terminates the current loop and executes It terminates the current iteration and
the remaining statement outside the loop. transfer
the control to the next iteration in the loop.
syntax: syntax:
break continue
for i in "welcome": for i in "welcome":
if(i=="c"): if(i=="c"):
break continue
print(i) print(i)
w w
e e
l l
o
m
e

48

You might also like