0% found this document useful (0 votes)
45 views203 pages

Python Programming - Unit 1

Uploaded by

zee928487
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)
45 views203 pages

Python Programming - Unit 1

Uploaded by

zee928487
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/ 203

UNIT-1 PYTHON FOR

PROGRAMMING AND
Getting Started with Python PRODUCT DEVELOPMENT

Programming
© Kalasalingam academy of research and education
Course Outline

CO 1
Course description
This course teaches the core of programming
computers using Python. We deal python
CO 2
programming from basics to core. The course does
not demand any pre-requisites but knowledge of basic
mathematics. The naive computer users can be able to
master the Python. This course will touch upon
CO 3.Implement user defined python functions and build an Python data types, functions, control and looping
efficient program leveraging modules constructs, regular expressions, user interface
modules and the data analytic packages. Once a
student completes this course, they will be ready to
CO 4.Create python programs to handle file I/O and exceptions, perform core python problem solving and also
and solve problems with Object Oriented Concepts develop their own python packages. This course
covers Python 3.

CO 5.Understand Data processing, Validation, Visualization


concepts in python with regex, pandas, matplotlib and numpy
packages.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Syllabus Unit 1:
❑Introduction Introduction
❑Strings & Formatting
❑Language Components Outcomes
Develop basic programs using control flow structure
➢Understand the basic python concept from scratch
➢Analyze the uses of various data types, methods and
control structures
➢Apply control structures to various applications

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Unit 1 Outline

Lesson 1. Unit - 1
Develop basic programs using control flow
structure
Lesson 2. Basics of
➢Understand the basic python concept
from scratch
Lesson 3. ➢Analyze the uses of various data types,
methods and control structures
➢Apply control structures to various
Lesson 4. Language components applications

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Course Progress (use before starting new lesson)

Lesson 1. Introduction

Lesson 2. Basics of Python

Lesson 3. Strings and Formatting

Lesson 4. Language Components

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Topic 1
About Computers & Program
transaltion

Topic 2
About Python & its versions
First Lesson Outline
Topic 3 We will be learning about Computers, Program
Notable Features
translation
Topic 4
Getting Started Python and its versions
Topic 5
Interpreter Features of Python
Topic 6 Interactive mode in Python IDEs
Applications
Applications in mainstream technologies

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Computer

•Computer= Hardware + Software


•A computer is an unit of electronic equipment that can execute millions of instructions per second.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Software

Software makes the hardware components in computer work

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Program Translation

Two approaches for program translation:

• Interpretation

• Compilation

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Program Translation: Interpretation Approach
Interpretation approach

• uses a program known as interpreter

• reads one high-level code statement at a time

- immediately translates and executes the statement before processing the next one

• examples: Python, R, and JavaScript

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Program Translation: Compilation Approach

Compilation approach
•uses a program called compiler
•reads and converts the source code of a high-level language programme into
machine-language instructions in an executable file.
•the converted machine-language instructions can be executed on the computer
when the program is launched
•examples: C and C++

It is also possible to use the combination of both translation techniques

•example: Java

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Interpreter vs. Compiler

Interpreter
Compiler
• very portable across different
computing platforms •program runs very fast after compilation
• produces results almost •smaller in code size after compilation
immediately •must compile the entire program before
execution
• easy to debug
•needs to be re-compiled if to be used on
• program executes more slowly
different computing platforms
• useful for implementing dynamic, •used in large and sophisticated software
interactive features, such as those applications when speed is of the utmost
used on web pages importance

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Object Oriented Vs Functional Programming

Object Oriented
Functional
•Objects are small capsules that hold
some internal state as well as a set of •Functional programming avoids the state
method calls that allow you to modify it, changes as much as possible and works with
and programmes are made up of the data flowing between functions.
correct set of state modifications.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


History of Python

Developed by Guido van Rossum (in 1989)


• Initially developed as a scripting language
• derives All Basic Code (ABC) and Modula-3
• Extensibility
• incorporating the features of the language ABC to work on AMOEBA,
a distributed operating system
• Got its name from a comic troupe Monty Python
• Public release in 1991

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Python Versions

Version 1 (1994)

Version 2 (2000)

Version 3.8 (2019)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Why Python?

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Notable Features

• Easy to learn – Normal English-based syntaxes with interactive compilation


• Supports quick development. – Supports wide variety of packages
• Cross-platform – Capable of executing in any OS
• Open Source – Freely usable and distributable, even for commercial use
• Extensible – extensible with C/C++/Java
• Embeddable – can be used in embedded, small or minimal hardware devices
• Large standard library and active community – Image Processing (opencv), machine learning (sklearn),
deep learning (tensorflow), among others

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Getting Started

•Let’s download and install Python in a Windows machine


•The examples used throughout the material targets this environment

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Installing Python – Download IDLE
https://www.python.org/downloads/

Fig. 1. IDLE Download site

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Install Python – Run Setup

Fig. 2. Installation of Python IDLE – Python Root Path

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Install Python – Installation Page

Fig. 3. Installation setup of Python IDLE – all default packages can be installed

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Install Python – Open IDLE

Fig. 4. Interactive Compiler – Python IDLE

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Interpreter

• The interpreter converts Python code into bytecode, which is then executed by the Python
Virtual Machine.
•Two modes: normal and interactive.
• Normal mode: full .py files are given to the interpreter.
• Interactive mode: piecewise execution of statements by read-eval-print loop (REPL).

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Interpreter: Normal mode

•Let’s write our first Python program!


•In our favorite editor, let’s create helloworld.py with the following contents:

•Python programs are stored with .py extension (eg. filename.py).

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Interpreter: Interactive mode

Let’s accomplish the same task (and


more) in interactive mode.

Some options:
-c : executes single command.
-O: use basic optimizations.
-d: debugging info.
More can be found here:
https://docs.python.org/3/using/cmd
line.html

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Mobile App for Python

Android: https://play.google.com/store/apps/details?id=ru.iiec.pydroid3

Iphone: https://apps.apple.com/us/app/python-ide/id1065305069

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Applications of Python in mainstream technologies

*Source: https://www.cleveroad.com/blog/python-vs-swift

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Applications of Python in mainstream technologies

Application Description
Web Application Web development frameworks
Development •Django
•Flask

Data Science Python Libraries


•Pandas
•NumPy
•SciPy
Data visualization
•Matplotlib
•Seaborn

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Applications of Python in mainstream technologies

Application Description
Artificial Intelligence Libraries for Machine Learning applications.
•SciPy
•Pandas
•Keras
•TensorFlow
•NumPy
Game development Libraries
•PySoy
•PyGame
Internet of Things •Raspberry Pi turns any thing into an electronic
gadget
•Creation of embedded software

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Applications of Python in mainstream technologies

Application Description
Web Scraping Selenium, PythonRequest, MechanicalSoup tools are
used for building web scraping applications

Desktop GUI •PyQT


•Kivy
•PyGUI

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Lesson Summary

❑ Python is with the simplest syntax.


❑ Python allows programmers to code with minimal lines as compared to other programming languages.
❑ Python consists of large number of features useful for a programmer to build efficient applications
❑ Python is an interpreter system which makes code to be executed fast.
❑ IDLE, Jupyter, Spyder, Colab are common platforms are executing the Python program
❑ Python has been serving as development of mainstream technologies

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Course Progress (use before starting new lesson)

Lesson 1.

Lesson 2. Basics of

Lesson 3. Strings and Formatting

Lesson 4. Language Components

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Topic 1
Identifier, rules and keyword
Topic 2
Variables, datatypes and comments
Topic 3
Basic Operations
Topic 4
Conversion of data types
Second Lesson Outline
We will be learning about identifier, syntax rules,
Topic 5
keyword, variable, data types and comments in Python
Simple Input/Output
Operators and its use cases
Conversion of data types
Simple Input / Output statements

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Identifier in Python

• Identifier is a name given to entities


• Entities can be a variable, class, function
• Used to differentiate one entity from another

Example:
• sum
• average
• day

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Rules for Identifier

Rules for Identifier: • cannot begin with any of the following


• can be of any length • digit (0 to 9)
• cannot contain only digits
• can use combination of the following • cannot use special symbols
• lowercase (a to z) • !, @, #, $, %
• uppercase (A to Z)
• digits (0 to 9) •space is not allowed between words
• underscore _
•keywords cannot be used as identifiers

•case sensitive

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Identifier- valid/invalid

Valid identifier Invalid identifier


total total value
total6 6total
total_value total-value
totalvalue total@
fi=10 if=10
total123 123

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Keywords
• Special words reserved in Python
• Programmers should not use keywords to name things
• They must be spelled exactly as written here (sample only given)
is
and
else
if
del
break
class
continue

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Variable

Operations
• Once a variable is created, we can store, retrieve, or modify the value associated with the
variable name.

• Subsequent assignments can update the associated value.

3.14
Name Value
x = 3.14
x 3.14
X

Name Value 5.16


x = 5.16
x 5.16

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Variable

Case Sensitive:

•Variables are case-sensitive

Example:
a=4
a and A are
A=5 treated as
two
different
variables

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Variable- Many values to Multiple variables

Many Values to Multiple Variables:

• In a single line, multiple variables can be assigned to values:

Example:
a1, a2, a3 = 4,5,6
print(a1)
print(a2) a1=4
print(a3) a2=5
a3=6

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Data types

•Variables hold data of varioues data type

Type of variables

Numeric types: Text type: Boolean Type:


int str bool
float
complex

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Numeric Data types

Numeric

int: whole number, Float:


a number, positive or Complex:
positive or negative,
negative, with decimals. "j“ is the imaginary part
without decimals, of
Eg: Eg:
any length
x=1.2 x=1+2j
Eg:
x=1.0 x=2j
x=1
x=-1.2 x=-2j
x=-2
x=2e3

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Text datatype

•A string, or a sequence of characters, is represented by the Text data type.


•The <class 'str'> shows that the variable is of the string data type.

Note: The built in function type(variable) returns the class of the datatype.

st=“cse”
st=“CSE”
st=“Cse”
st=“100”
st‘=“Welcome CSE”

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Boolean datatype

•True or False is the boolean data type.


•True and False are the keywords that define Boolean variables.
•The <class 'bool‘> shows the variable is of boolean data type.

Note: The built in function type(variable) returns the class of the datatype.

x=True
z=False
print(10>12)
Prints
False

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Getting Data types

•Getting the data type

Example:
n= 6
print (n)
print(type(n)) Prints
<class ‘int’> Example:
n= 6j
print (n)
Example: print(type(n)) Prints
n= 6.5 <class ‘complex’>
print (n)
print(type(n)) Prints
<class ‘float’>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Getting Data types

•Getting the data type

Example:
Example:
n= ”KARE”
n= True
print (n)
print (n)
print(type(n)) Prints print(type(n))
<class ‘str’> Prints
<class ‘bool’>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Comments

• Used to describe code and make the code readable


• Prevents execution of code while testing code
• Start comments with #
• Can add a “documentation string” as the first line

Example:
#initialization of variables Commented
line
a=10
b=20

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Comments

Example:
print(“hi”) # It’s a comment line
print(“hello”)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Multi line Comments

No syntax for multiline comment, hence use multiline string (triple quotes)
Example:
”””
This code is
written in Python Multiline
comment
enclosed in triple
to print a message quotes

”””
print(“KARE")

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Basic Operations

Basic Operations in python:


Addition operation(+):

output:
7

Output:

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Arithmetic Operations

Simple Arithmetic Operations in Numerical Data types.


• Addition operation +
• Subtraction operation -
• Multiplication operation *
• exponentiation operation **
• Division /
• floor division // (returns only the integral part of the division)
• Modulus operator % (returns the remainder of the division)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Assignment Operator

•It assigns values to variables


•= is the assignment operator

Operator Example Equivalent to


= w=3 w=3
+= w+=3 w=w+3
-= w-=3 w=w-3
*= w*=3 w=w*3
/= w/=3 w=w/3
%= w%=3 w=w%3

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Arithmetic Operations

Lets’s have an exercise on these arithemetic operators:

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Repetition operator

Multiplication (*) operator between Strings and integer(repetition):


When * operator is used between a string(a) and a integer(n) datatype , then the result would be repetion
of the string (a) n times and the result is also a string.

* With strings
performs
repetition
Output:

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Conversion of datatypes
Type Conversion

•Type conversion is the process of converting the value of one data type (integer, text, float, etc.) to another data
type.

•Two types of type conversion

1.Implicit Type Conversion


2.Explicit Type Conversion

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Implicit Type Conversion

Implicit Type Conversion

• Python converts one data type to another automatically without user interaction

Note:
To avoid data loss, convert the lower data type (integer) to the higher data type (float).

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Implicit Type Conversion

Example 1 : integer to float converted int to


float while
n_int = 123 performing
addition
n_flo = 1.23
n_new = n_int + n_flo
print("datatype of num_int:",type(n_int))
print("datatype of num_flo:",type(n_flo))
print("Value of num_new:",n_new)
print("datatype of num_new:",type(n_new))

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


'

Implicit Type Conversion


Example 2 : String to integer

n_int = 123
n_str = "456"

print("Data type of num_int:",type(n_int))


print("Data type of num_str:",type(n_str))
print(n_int+n_str)

Output
TypeError: unsupported operand type(s) for +: 'int' and
'str’
TypeError

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


'

Implicit Type Conversion

In this previous example


• Two variables n_int and n_str are added
• It has shown TypeError
• as it cannot use Implicit Conversion
•However, can deal such conditions with Explicit Conversion

Note:
Conversion of the higher data type (String) to the lower data type (integer) is not implicit.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


'

Explicit Type Conversion

• The data type of an object is converted to the needed data type by users
• Predefined functions like int(), float(), str(), etc can be used to do explicit type conversion.
• Also known as typecasting as the user casts the data type of objects.

Syntax

<reqd_datatype>(expression)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


'

Explicit Type Conversion

Example : String to Integer


n_int = 123
n_str = "456"
print("Data type of n_int:",type(n_int))
print("Data type of n_str before Type Casting:",type(n_str)) Explicit type
conversion
n_str = int(n_str)
print("Data type of n_str after Type Casting:",type(n_str))
n_sum = n_int + n_str
print("Sum of n_int and n_str:",n_sum)
print("Data type of the sum:",type(n_sum))

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Summary of conversion of datatypes

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


'

Simple Output

Syntax

print(*objects, sep=' ', end='\n', file=sys.stdout)


Purpose of each parameter

• objects - object to the printed. * denotes more than


one object
• sep - objects separation. Default value: ' '
• end - end is printed finally
• file - There must be a write(string) method on the
object. If it is not specified, sys.stdout is used, which
prints objects on the screen.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


'

Simple Output
Example :
print("Python is cool.")

w=5
print(“w =", w)
sFile = open('pyth.txt', 'w')
print(‘KARE’, file = sFile)
z=w
sFile.close()
print(‘w =', w, '= z')

w=5
print(“w =", w, sep='0000', end=‘\n\n')
print(“w =", w, sep='0', end='')

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


end in simple output

• ‘end’ is a parameter in print() function.


• The default value of the end parameter is ‘\n’, (new line character)
• Any character/string can be used to end a print statement.
Example 1:
print("Welcome to " , end = ' ')
Prints Welcome to KARE
print(“KARE", end = ' ')
Example 2:
print("Welcome" , end = @)
Prints Welcome @ KARE
print(“KARE")

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


.
'

Simple Input
Syntax Example
num=input('Enter a num')
input([prompt]) num1=input('Enter another num')
print(num+num1)
• The value 10 and 20 are strings, not a
number. Enter a num10
• use int() or float() functions to convert to Enter another number20
number 1020

num=input('Enter a num')
• Here, we converted both num and num1 to num1=input('Enter another number')
integer and the result we get is integer print(int(num)+int(num1))

Enter a num10
Enter another number20
30

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


.
'

Simple Input

• eval()
It evaluates the expression given as a string and returns integer

Example

>>> int(‘6+6') >>> s=eval('2+3')


ValueError: invalid literal for int() with >>> print(s)
base 10: ‘6+6‘ 5
>>> eval(‘6+6') >>> type(s)
12 <class 'int'>
>>>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Import in Python

•We can import python modules and can use it in program


• Example shows how to import ‘math’ module
Example:
Prints
import math 3.1415

print(math.pi)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Lesson Summary

❑ Python supports various types of Operators including Arithmetic, Boolean, Repetition, among others
❑ Data types of variables are updated based on the operations performed on the variables.
❑ Python supports type conversion at any level. type() is used to check type of the variable
❑ datatype(var) can convert the variable var to the corresponding datatype. Eg. int(3.5) = 3 (Converting
floating point data to integer data)
❑ Simple input and output staements

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Course Progress (use before starting new lesson)

Lesson 1.

Lesson 2. Basics of

Lesson 3. Strings and Formatting

Lesson 4. Language Components

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Topic 1
Strings in Python

Topic 2
Indexing and Slicing Strings Third Lesson Outline
Topic 3
Operators in Strings
We will be learning about strings
Topic 4
Formatting Operators Strings methods for various formatting options
Operators in Strings

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Strings in Python

•String is a data type


•String is the collection of the characters
• Example: KARE

•Enclosed by single quotes or double quotes or triple quotes (only for multiline string)
• Example: ‘KARE’ or “KARE”
• The ASCII or Unicode character is used to encode each character. As a result, Python strings can also be referred
to as a list of Unicode characters.
• The character data-type is not supported in Python; rather, a character written as 'w' is a string of length 1.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String data type in Python

• Example:
st=“KARE”

• To know the data type of the variable st


print(type(st))
Prints a string (st)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String representation in Python

• Single quotes
• Example:
st = 'Hello'
print(st)
Prints Hello

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String representation in Python

• Double quotes
•Example:
st = ”Hello”
print(st)
Prints Hello

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String representation in Python

• Triple quotes
•Example:
st = ”””Hello
World
KARE”””
print(st)
Prints Hello
World
KARE

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String indexing

st=“KARE”

K A R E
0 1 2 3
Indices

st[0]=‘K’
st[1]=‘A’
st[2]=‘R’
st[3]=‘E’

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String indexing

st=“KARE”

K A R E
0 1 2 3

print(st[0])
print(st[1])
print(st[2])
print(st[3])
IndexError: string
print(st[4]) index out of range

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String splitting/slicing

To get to the individual characters in a string, use the slice operator []. However, we can get the substring of the given string
by using the : (colon) operator.
st=‘KARE’
K A R E
0 1 2 3

st[:]= ‘KARE’
st[0:]=‘KARE’
st[:4]=‘KARE’
st[:2]=‘KA’
st[0:3]=‘KAR’
st[1:3]=‘AR’

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String splitting/slicing
Note:
• The slice operator's higher bounds are always exclusive.
• If st = ‘KARE‘, then st[1:3] includes str[1] = ‘A', str[2] = ‘R' and nothing else.

st=‘KARE’
K A R E
0 1 2 3

st[1:3]=‘AR’

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String – negative slicing
•Negative slicing can be done in the string
• -1 indicates the start from the rightmost character
• -2 indicates the second rightmost index indicates -2.
st=‘KARE’

K A R E
-4 -3 -2 -1

st[-1]=‘E’
st[-2]=‘R’
st[-3:-1]=‘AR’

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String – Reversal
st=‘KARE’

K A R E
-4 -3 -2 -1

It prints ERAK

print(st[::-1]

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String- Reassignment

•Strings are immutable


•Item assignment is not supported by string object
•Because the content of a string cannot be partially altered, it can only be replaced with a new string.
Example:
st = “KARE"
st[0] = “c"
print(st) TypeError: 'st' object
does not support item
assignment

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String- Reassignment

The string st can be fully assigned to a new content


Example:
st = “KARE"
print(st)
st = “kare"
print(st)
It prints kare

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String- Deletion

As strings are immutable, the characters cannot be deleted from the string. However, the entire string can
be deleted using the del keyword.
Example:
st = “KARE"
del st[1]
TypeError: 'st' object
doesn't support item
deletion
del st
print(st)
NameError: name 'st'
is not defined

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String Length

The built-in len() method finds length of a string


Example:
st = “KARE"
print(len(st)) Prints
4

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String Operators

• The + and * operators are applied to both numeric operands and strings
+ operator – Concatenation of Strings
Example:
>>> s = ‘cse'
>>> t = ‘ece'
>>> u = ‘eee'
>>> s + t
‘cseece'
>>> s + t + u
‘cseeceeee'

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String Operators

* operator – Creation of multiple copies of strings


Example:
>>> s = ‘cse'
>>> s * 4
‘csecsecsecse'
>>> 4 * s
‘csecsecsecse'

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String Operators

in operator – If the provided string is contained within another string, it returns True; otherwise, it returns
False.
Example:
>>> s = ‘cse'
>>> s in ‘An Engineering department comprises of cse '
True
>>> s in ‘An Engineering department comprises of ece'
False

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String Operators

not in operator – returns True if the given string is not contained within another string, and False otherwise:
Example:
>>> s = ‘cse'
>>> s not in ‘An Engineering department comprises of cse '
False
>>> s not in ‘An Engineering department comprises of ece'
True

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Formatting Operators
Format Symbol Conversion
%c character
%s string conversion via str() prior to formatting
%i signed decimal integer
%d signed decimal integer
%u unsigned decimal integer
%o octal integer
%x hexadecimal integer (lowercase letters)
%X hexadecimal integer (UPPERcase letters)
%e exponential notation (with lowercase 'e')
%E exponential notation (with UPPERcase 'E')
%f floating point real number
%g the shorter of %f and %e
%G the shorter of %f and %E

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String- format method

•The format() method is a method for formatting strings.


•The curly braces {} are used as the placeholder in the string and replaced by the format() method arguments.
Prints CSE and ECE
Curly braces : are Engineering
departments
print("{} and {}are Engineering departments".format(“CSE",”ECE"))

Prints ECE and CSE


Positional Argument : are Engineering
print("{1} and {0} are Engineering departments ".format(“CSE",”ECE")) departments

Keyword Argument: Prints CSE,ECE,IT


print("{x},{y},{z}".format(x = ”CSE", y = ”ECE", z = ”IT"))

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods- (only core methods)
String Method Description
capitalize() The first character is converted to upper case
casefold() String is converted into lower case
startswith() Returns true if the string starts with the given value
endswith() Returns true if the string ends with the given value
find() Returns the position of where a supplied value was discovered after searching the
string for it.
replace() Replaces a provided value with a specified value and returns a string.
index() Returns the position of where a supplied value was discovered after searching the
string for it.
islower() Returns True if the string contains only lower case characters.
isupper() Returns True if the string contains only upper case characters.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods- (only core methods)

String Method Description


upper() a string is converted into upper case
lower() a string is converted into lower case
isspace() If all of the characters in the string are whitespaces, this function returns True.
isalpha() If all of the characters in the string are alphabets, this function returns True.
isdigit() If all of the characters in the string are digits, this function returns True.
split() Returns a list after splitting the string at the provided separator.
join() Connects the elements of an iterable to the string's end.
count() The number of times a provided value appears in a string is returned.
format() Formats specified values in a string
strip() Returns a trimmed section of the string

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

capitalize()
Example:
st = ”cse”

x = st.capitalize()
Prints CSE
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

casefold()
Example:
st = ”CSE”

x = st.casefold()
Prints cse
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

startswith()
Example:
st = ”hi CSE”

x = st.startswith(“hi”)
Prints True
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

endswith()
Example:
st = ”hi CSE”

x = st.endswith(“CSE”)
Prints True
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

find()
Example:
st = ”hi CSE”

x = st.find(“CSE”)
Prints position 3
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

replace()
Example:
st = ”hi CSE”

x = st.replace(“CSE”, “ECE”)
Prints hi ECE
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

index()
Example:
st = ”hi CSE”

x = st.index(“CSE”)
Prints 3
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

islower()
Example:
st = ”CSE”

x = st.islower()
Prints False
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

isupper()
Example:
st = ”CSE”

x = st.isupper()
Prints True
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

upper()
Example:
st = ”cse”

x = st.upper()
Prints CSE
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

lower()
Example:
st = ”CSE”

x = st.lower()
Prints cse
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

isaplpha()
Example:
st = ”CSE”

x = st.isalpha()
Prints True
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

isdigit()
Example:
st = ”555”

x = st.isdigit()
Prints True
print (x)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

split()
Example:
st = ”welcome to KARE”

x = st.split()
Prints
print (x) [‘welcome’,’to’,’KARE’]

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

join()
Example:
tu= (“CSE”,”ECE”,”EEE”)

x = “$”.join(tu)
Prints
print (x) CSE$ECE$EEE

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

count()
Example:
st= ”I like books, books are my friends”

x = st.count(“books”)
Prints
print (x) 2

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

format()
Example:
st =”The book is {price: .2f} rupees”
Prints
The book is 200.00 rupees
print(st.format(price=200))

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

strip()
Example 1:
st =” Diya ”
z=st.strip()
Prints
print(“of all friends”, z, “is my best friend”) of all friends Diya is my best friend

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


String methods

strip()
Example 2:
st =”,,,,…..Diya…..ohhhh”
z=st.strip(“,.oh”)
Prints
print(z) Diya

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Escape Characters

•To insert characters that aren't allowed in a string.


• A backslash followed by a character.
Example: If you use double quotes within a string
that is enclosed by double quotes, you'll
st =”I like “science” books” get an error

Example:
st =”I like \“science\” books” Prints
print(st) I like science books

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Some more programs on strings

• Without len(), try to find length of string


Code:
st=“welcome”
count = 0
for char in st:
count += 1
print count prints
7

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Some more programs on strings

• Generate a string which is made of the first 3 and the last 3 characters from a given string.
•Code:
st=“welcomecse”
if len(st) < 3:
print (‘’)
print (st[0:3] + st[-3:]) prints
welcse

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Some more programs on strings

•Remove the nth index character from a string


•Code:
st=“welcomecse”
n=4
first_half = st[:n]
second_half = st[n+1:]
print (first_half + second_half) prints
welcmecse

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Lesson Summary

❑ Python considers single character and group of characters commonly as strings


❑ Strings are immutable and has various formatting functions
❑ String methods are used to find, search, access and operate over strings
❑ String formatting functions are used in print functions and to derive the inputs in appropriate fashion

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Course Progress (use before starting new lesson)

Lesson 1.

Lesson 2. Basics of

Lesson 3. Strings and Formatting

Lesson 4. Language Components

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Topic 1
indenting requirements

Topic 2
Relational Operators

Topic 3
Logical Operators

Topic 4
Bitwise Operators

Topic 5
if Statements

Topic 6
for Statement

Topic 7
break and continue Statements
Fourth Lesson Outline
Topic 8
pass Statement
We will be learning about the operators and control
flow tools in Python

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Indenting Requirements

•Indentation means the spaces at the beginning


of a statement.
if 3 > 1:
•The indentation in Python needs to be
print(“Three is greater than one")
followed strictly
• Indentation in other programming languages
is for enhancing the readability Indentation

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Indenting Requirements

• Syntax error if indentation is skipped

if 3 > 1:
print(“Three is greater than one")

No Indentation
raises syntax
error

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Indenting Requirements

• The number of spaces is up to the coder, but


it has to be minimum one.
if 3 > 1:
print(" Three is greater than one ")
if 3 > 1:
One Indentation print(" Three is greater than one ")
space

More than one


Indentation
spaces

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Indenting Requirements

• In the same code block, the same number of


spaces must be provided
if 3 > 1:
•Otherwise Python will show an error
print(" Three is greater than one ")
print(" Three is greater than one ")
Syntax error for
different
indentation in each
statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators
Relational operators are otherwise known as comparison operators to compare 2 values

List of relational operators:


•Equals: •Greater than:
• w1 == w2 • w1 > w2
•Not Equals: •Greater than or equal to:
• w1 != w2 • w1 >= w2
•Less than:
• w1 < w2
•Less than or equal to:
• w1 <= w2

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators

•Equals:

Example: returns False


w1 = 7 because 7 is not
equal to 3
w2 = 3
print(w1 == w2)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators

•Not Equals:

Example: returns True


because 7 is not
w1 = 7 equal to 3
w2 = 3
print(w1 != w2)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators

•Less than:

Example: returns False


because 7 is not
w1 = 7 less than 3
w2 = 3
print(w1 < w2)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators

•Greater than:

returns True
Example: because 7 is
w1 = 7 greater than 3
w2 = 3
print(w1 > w2)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators

•Less than or equal to:

Example: returns False


because 7 is not
w1 = 7 less than or equal
w2 = 3 to 3
print(w1 <= w2)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Relational operators

•Greater than or equal to:

returns True
Example: because 7 is
w1 = 7 greater than or
w2 = 3 equal to 3

print(w1 >= w2)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Logical Operators

Logical operators join conditional statements


Types of operators are:
•and
• a < 4 and a < 5
•or
• a < 4 or a < 5
•not
• not(a < 4 and a < 5)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Logical Operators

•and
returns True
because 7 is greater
than 2 AND 7 is less
Example: than 12
a=7
print(a > 2 and a < 12)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Logical Operators

•or returns True because


one of the conditions
are true (7 is greater
than 2, but 7 is not less
Example: than 1)
a=7
print(a > 2 or a < 1)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Logical Operators

•not returns False because


not is used to reverse
the result

Example:
a=7
print(not(a > 4 and a < 12))

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•When comparing binary numbers, bitwise operators are utilised


•Types of operators are:
and - &
or - |
not - !
XOR - ^
left shift - <<
right shift - >>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•and - &

Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is
12
z = x & y; # 12 = 0000 1100
print ("Value of z is ", z)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•or - |

Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0
value of z is 61
z = x | y; # 61 = 0011 1101
print ("Value of z is ", z)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•not - ~
•It is unary and is inverting all the bits

Example:
x = 60 # 60 = 0011 1100
z=0
value of z is
195
z = ~x ; # 195 = 1100 0011
print ("Value of z is ", z)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•XOR - ^
• If just one of two bits is 1, sets each bit to 1.

Example:
x = 60 # 60 = 0011 1100
y = 13 # 13 = 0000 1101
z=0 value of z is 49

z = x ^ y; # 49 = 0011 0001
print ("Value of z is ", z)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•Left shift - <<


•The value of the left operand is shifted left by the number of bits indicated by the
right operand.
Example:
x = 60 # 60 = 0011 1100
z=0
z = x << 2; # 240 = 1111 0000 value of z is 240

print ("Value of z is ", z)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Bitwise Operators

•Right shift - >>


•The value of the left operand is shifted right by the number of bits indicated by
the right operand
Example:
x = 60 # 60 = 0011 1100
z=0
z = x >> 2; # 15 = 0000 1111
value of z is 15
print ("Value of z is ", z)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Practice Session

• Find length of a string without len() method


Code:
st=“welcome”
count = 0
for char in st:
count += 1
print count prints
7

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Conditional Statements in Python

•So far, you've only seen sequential execution, which means that statements are always executed one after the
other, in the exact order defined.
•However, life is frequently more complex than that.
•A program will often need to skip over certain statements, repeat a series of statements, or select between two
sets of statements to execute.
•Control structures play a role in this.
•The order in which statements in a program are executed is guided by a control structure.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Conditional Statements in Python

•Python supports
• if
• if…else
• elif ladder
• nested if

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


if statement

•In reality, we often must analyse information and then select one of two courses of action:

“If the weather is nice, then I’ll go for picnic. (It’s implied that if the weather isn’t nice, then I won’t go for picnic.)”

•The if statement is used to perform this type of decision-making.


•It enables the execution of a statement or a set of statements based expression value.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


if statement

•Syntax
if <expre>:
<statement>

<expre> → An expression evaluated in a Boolean context


<statement> → An indented valid statement
If <expre> is true, then <statement> is executed.
If <expre> is false, then <statement> is not executed.
Note:
colon (:) following <expre> is required.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of if statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


if statement

•Example
w1=4 It executes print
statement as the
w2=5 value of w1 is less
than w2
if w1<w2:
print(“w1 is less than w2”)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Indentation in if statement

•Example
w1=6 It will not execute
print statement as the
w2=5 value of w1 is not less
than w2
if w1<w2: It will skip to this
statement and execute
print(“w1 is less than w2”) it if <expr> evaluates
to false
print(“hi”)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


if else statement

•To evaluate a condition and if it's true take one direction, but another direction if it's false.
•An else clause is used to do this
•Syntax
if <expre>:
<stmt(s)>
else:
<stmt(s)>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of if else statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


if else statement

•Example
w1=5
w2=4 It executes print
statement in else
if w1<w2: block as the value
of w1 is not less
print(“w1 is less than w2”) than w2

else
print(“w2 is less than w1”)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


elif ladder

•For branching execution based on several alternatives


•Syntax
if <expre>:
<stmt(s)>
elif <expre>:
<stmt(s)>
elif <expre>:
<stmt(s)>
else:
<stmt(s)>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of elif ladder

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


elif ladder

•Elif components can be zero or more, and the


else portion is optional.
•The keyword 'elif' stands for 'else if,' and it's
important for avoiding over-indentation.
•In other languages, switch or case statements
are replaced by an if... elif... elif... Control flow tools
used for decision
making

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Nested if

Syntax: outer if

if (condition1):
# executes statements when condition1 is true
if (condition2): inner if

# executes statements when condition2 is true


# inner if ends
# outer if ends

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of Nested if

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Nested if
Example:
numb = -20
if numb >= 0:
if numb == 0:
print("Zero")
This print
else: statement is
print("Positive number") executed as
numb carries a
negative value
else:
print("Negative number")

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Conditional expressions

• An additional decision-making entity.


• It is otherwise known as a conditional operator or ternary operator
•Syntax:
<expre1> if <conditional_expre> else <expre2>

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Conditional expressions

•Example
>>> age = 50
>>> s = ‘junior' if age < 25 else ‘senior'
>>> s
‘senior'

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Conditional expressions

•Example
•Example
if x > y:
z = x if x > y else y
z=x equivalent

else:
z=y

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Looping statements

•In programming, loops are used to repeat a block of code.


•Types of looping statements:
• while
• for

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


while loop statement

•The while loop iterates over a code block as long as the test expression is true.
•When it’s not sure how many times we'll iterate ahead of time, we'll use this loop.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


while loop statement

•Syntax
while expr:
body of while

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of while loop statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


while loop statement

Initialization
•Example 1
Test
expression
ind = 1
while ind <= 10:
print("The value of ind is", i)
ind = ind+1

Update
counter

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


while loop statement

•Example 2
ind = 1
while ind < 6:
print(ind)
ind += 1
Prints
1,2,3,4,5

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Infinite while loop statement

•In the while loop, any non-zero value denotes an always-true condition, while zero denotes an always-
false condition
Example
while (1):
print(”KARE”)

Prints KARE
infinitely

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Some more programs using while loop

Program to print table of given numbers Output:


i=1 Enter the number 5
numb=0 5*1=5
numb = int(input("Enter the number:")) 5 * 2 = 10
while i<=5: 5 * 3 = 15
print("%d * %d = %d \n"%(numb,i,numb*i)) 5 * 4 = 20
5 * 5 = 25
i = i+1

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


else in while loop statement

When the test condition is no longer true, the else statement is used to run a code block once.
Example:
ind = 0
while ind < 5:
print(ind) Prints
0
ind += 1 1
2
else: 3
4
i is not less than 5
print("ind is not less than 5")

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Single statement while loop statement

•Example
total = 0
while (total == 0): print("Hello KARE")

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


for loop statement

•Used for sequential traversal


•Iterating over a sequence is called traversal
•When we know how many times we'll iterate ahead of time, we'll use this loop.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


for loop statement

‘in’ is the
Syntax: membership
operator
for value in sequence:
Body of for block

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of for loop statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


for loop statement

Print each number in a list


List of numbers
Example:
numb = [1,2,3,4,5]
Iterate over list of
tot = 0 numbers

for valu in numb:


tot = tot+valu
print("The total is", tot)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


for loop statement

Loop through a string


Example:
for value in “KARE”: Iterate over
string and prints
print(value) KARE

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Else in for loop statement

In a for loop, the else keyword specifies a code block that will be executed when the loop is completed.
Example:
For w in range(3):
Prints
print(w) 0
else: 1
2
print(“done") done

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Else in for loop statement

If the loop is terminated by a break statement, the else block will not be executed.
Example:
for x in range(5): Prints
if x==4: break 0
1
2
print(x) 3

else:
print(“done")

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Nested for loop statement

•Nested means presence of one for loop within another for loop
Syntax:
for v1 in seq: #outer for loop
for v2 in seq: #inner for loop
#block of code
#following statements

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Nested for loop statement

Example:
lt1 = [1, 2, 3]
lt2 = [4, 5, 6]
For w1 in lt1:
14
for w2 in lt2: 15
16
print(w1, w2) 24
25
26
34
35
36

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Some more programs for Nested for loop statement

Example: To print asterisk triangle


n_rows = int(input("Enter the number of rows:"))
for i1 in range(0,n_rows+1):
for j1 in range(i1):
*
print("*",end = '') **
***
print() ****
*****

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


for loop statement

•Example:

Output:

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


range() function

The built-in function range() is used to iterate over a sequence of numbers. It returns a sequence of
numbers that starts at 0 and increments by 1 (by default) and stops before a specified number.

range(end) range(start, end) range(start, end, step)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


range()

Example:
Generate a sequence of numbers from 0 to 6:
n = range(7)
for x1 in n:
print(x1) Prints
0,1,2,3,4,5,6

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


range()

Example:
Generate a sequence of numbers from 2 to 6:
n = range(3, 6)
for x1 in n:
print(x1) Prints 2,3,4,5

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


range()

Example:
Generate a sequence of numbers from 2 to 8,
increment by 2:
n = range(2, 9,2)
for x1 in n: Prints 2,4,6,8
print(x1)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Reverse range()

Example:
Generate a sequence of numbers from 5 to 1,
decrement by 1:
n = range(5, 0,-1)
for x1 in n: Prints 5,4,3,2,1
print(x1)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Negative range()

Example:
Generate a sequence of numbers from -1 to -5,
decrement by 1:
n = range(-1, -6,-1)
for x1 in n: Prints -1,-2,-3,-4,-5
print(x1)

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Some more programs using range()

Example: Output:
numb = int(input("Enter the number ")) Enter the number 5
for w in range(1,6): 5*1=5
m = numb*w 5 * 2 = 10
print(numb,"*",i,"=“,m) 5 * 3 = 15
5 * 4 = 20
5 * 5 = 25

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


range() function

Combine range() and len() to iterate over the indices of a sequence:

Output:
Accessing all
elements of list

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


break and continue Statements

• To change the flow of a loop


• Sometimes we might want to end the current iteration, or even the loop entirely, without checking the test
expression.
•The break and continue statements are used for these cases

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


break and continue Statements

•Break •Continue
o Breaks the loop o Skips the remaining code
inside a loop for the current
oProgram control flows to the iteration only.
statement immediately after the
body of the loop. o The loop does not end, but
instead continues with the next
iteration.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of break statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


break statement

Example:
for x1 in “KARECSE":
if x1 == “C":
Prints
break K
A
R
print(x1) E

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Flow of continue statement

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


continue statement

Example:
for x1 in “KARECSE":
Prints
if x1 == “C": K
A
continue R
E
print(x1) S
E

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


break and continue Statements

Break: Come out


of the current
loop

Output

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


break and continue Statements

The continue statement continues with the next iteration of the loop, skipping the current iteration:

Output

Continue: skip
current iteration

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


pass Statement

•The pass statement a null (means nothing) statement


•The interpreter ignores a comment, whereas pass is not ignored.
•When the pass is run, no operation is performed (NOP).
• It's useful when a statement is required syntactically but no action is required by the programme.

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


pass Statement

•Syntax
pass

•Example:
seq = {‘k', 'a', ‘r', ‘e'}
for x in seq:
Does nothing
pass

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Lesson Summary

❑ Control flow tools include if, if..else, elif ladder, nested if


❑ Looping statements include for loop, while loop
❑ range() function in python is used to access the elements across specified range of index
❑ break, continue, pass statements are used to control iterations in loops and programs

© Kalasalingam academy of research and education PROGRAMMING IN PYTHON


Thank You!
You would have comprehended the python compilers, data types, control flow tools, strings and data
structures
© Kalasalingam academy of research and education PROGRAMMING IN PYTHON

You might also like