SlideShare a Scribd company logo
Online Workshop on ‘How to develop
Pythonic coding rather than Python
coding – Logic Perspective’
21.7.20 Day 1 session 2
Dr. S.Mohideen Badhusha
Professor/ CSE department
Alva’s Institute Engineering and
Technology
Mijar, Moodbidri, Mangalore
1
2
Iteration & String
3
To acquire knowledge of iteration and string in Python
To comprehend the concept of looping statements in
Python
To practice the simple problems in iteration and string
Objectives of the Day 1 session 2
4
Iteration
for loop
for var in <collection>:
<statements>
where collection is iterable obj like list, tuple,dictionary,string
and range
a = [’i’, ’say’, ’hello’] # a list of string elements
for i in range(len(a)):
print (i,end=’ ’)
print (a[i])
Output
0 I
1 say
2 hello
5
Iteration
while loop
while condition :
<Statements>
i=0
while (i < 10):
print( i)
i += 1
o/p
0
1
2
.
9
6
Another Example for loop
for someChar in “Hello” :
print(someChar)
Output
H
e
l
l
o
7
d=[(1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e')]
for (x, y) in d :
print (x,y)
o/p
1 a
2 b
3 c
4 d
5 e
8
for loop using range()
for x in range(5):
print x
o/p
0
1
2
3
4
9
Python program but not Pythonic
def traverse(string):
index = 0
while index < len(string):
letter = string[index]
print(letter)
index += 1
traverse('Monty Python')
Output ?
10
def traverse(string):
for letter in string:
print (letter)
traverse('Monty Python’)
Pythonic program
11
in operator
in is a boolean operator that checks
membership within a sequence
It is also called membership operator.
'a' in 'banana'
True
'o' in 'banana'
False
12
String Operations 12
13
String handling functions
s=’HELLO’
s.lower() # hello
s1=’hello’
s1.upper() # HELLO
s.strip() -- returns a string with whitespace
removed from the start and end
s=’ I am happy ‘
s.strip() # I am happy ( no front and back spaces)
s.isalpha()# True
s.isdigit() # False
s.isspace() #False
14
split() and join() functions
s.split('delim') - returns a string into a list of
words separated by delim
Ex:
'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc'].
Defalut delim is space
s.join(list) -- opposite of split(), joins the
elements in the given list together using the
string as the delimiter.
Ex:
'---'.join(['aaa', 'bbb', 'ccc']) -> ‘aaa---bbb---ccc’
14
15
String Formatting Operator: %
The operator % allows strings to be built out of many
data items in a “fill in the blanks” fashion.
x = “Ram”
y = 34
print(“%s’s age is %d” % (x, y))
o/p
Ram’s age is 34
The tuple following the % operator is used to fill in
the blanks in the original string marked with %s %g
%d to represent string, float and integer values
16
Converting anything to a String
The built-in str() function can convert an
instance of any data type into a string
Ex:
print(“Hello ” + str(2))
o/p
Hello 2
17
Slicing strings
A segment of a string is called a slice.
Selecting a slice is similar to selecting a
character:
Ex:
s = 'Monty Python'
print(s[0:5])
Monty
print(s[6:12])
Python
18
String Indexing
print(s[:3])
o/p
Hel
print(s[3:])
o/p
lo
18
19
String Indexing
print(s[-1])
o/p
'o' #last char (1st from the end)
print(s[-4])
o/p
'e' # 4th from the end
print(s[:-3])
o/p
'He' – from starting, going up to but not
including the last 3 chars.
s[-3:] is 'llo' -- starting with the 3rd char from
the end and extending to the end of the string.
20
s[1:4] is 'ell' -- chars starting at index 1 and
extending up to but not including index 4
s[1:] is 'ello' -- omitting either index defaults
to the start or end of the string
s[:] is 'Hello' -- omitting both always gives
us a copy of the whole thing
s[1:100] is 'ello' -- an index that is too big is
truncated down to the string length
21
Concluding Tips
for loop in Python is entirely different from
other programming languages[ for var in
collection]
while loop in Python is similar to the
programming constructs in other languages
There is no do… while loop existing in Python
To be Pythonic, we should use data
structures and PEP 8 rules in Python
In slicing of string, st[i:n], we have to consider
from i th index to n-1 .
st[:n] from 0 th index to n-1.
st[i:] from i th index to end of the string

More Related Content

Similar to ‘How to develop Pythonic coding rather than Python coding – Logic Perspective’ (20)

Strings brief introduction in python.pdf
Strings brief introduction in python.pdfStrings brief introduction in python.pdf
Strings brief introduction in python.pdf
TODAYIREAD1
 
Python data handling
Python data handlingPython data handling
Python data handling
Prof. Dr. K. Adisesha
 
PPS_Unit 4.ppt
PPS_Unit 4.pptPPS_Unit 4.ppt
PPS_Unit 4.ppt
KundanBhatkar
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdfpython1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
varthini python .pptx
varthini python .pptxvarthini python .pptx
varthini python .pptx
MJeyavarthini
 
UNIT 4 python.pptx
UNIT 4 python.pptxUNIT 4 python.pptx
UNIT 4 python.pptx
TKSanthoshRao
 
Python Programming-UNIT-II - Strings.pptx
Python Programming-UNIT-II - Strings.pptxPython Programming-UNIT-II - Strings.pptx
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
nitamhaske
 
ppt notes python language operators and data
ppt notes python language operators and datappt notes python language operators and data
ppt notes python language operators and data
SukhpreetSingh519414
 
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvbecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
JayPatil347597
 
Python Strings.pptx
Python Strings.pptxPython Strings.pptx
Python Strings.pptx
adityakumawat625
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
TanushTM1
 
strings in python (presentation for DSA)
strings in python (presentation for DSA)strings in python (presentation for DSA)
strings in python (presentation for DSA)
MirzaAbdullahTariq
 
Python course in_mumbai
Python course in_mumbaiPython course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbaiPython course in_mumbai
Python course in_mumbai
vibrantuser
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Notes3
Notes3Notes3
Notes3
hccit
 
ADST university of Sussex foundation class
ADST university of Sussex foundation classADST university of Sussex foundation class
ADST university of Sussex foundation class
MarufFarhanRigan1
 
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoiiStrings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
pawankamal3
 
Chapter05.ppt
Chapter05.pptChapter05.ppt
Chapter05.ppt
afsheenfaiq2
 
Strings brief introduction in python.pdf
Strings brief introduction in python.pdfStrings brief introduction in python.pdf
Strings brief introduction in python.pdf
TODAYIREAD1
 
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdfpython1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
python1uhaibueuhERADGAIUSAERUGHw9uSS.pdf
rohithzach
 
varthini python .pptx
varthini python .pptxvarthini python .pptx
varthini python .pptx
MJeyavarthini
 
Python Programming-UNIT-II - Strings.pptx
Python Programming-UNIT-II - Strings.pptxPython Programming-UNIT-II - Strings.pptx
Python Programming-UNIT-II - Strings.pptx
KavithaDonepudi
 
Strings in Python
Strings in PythonStrings in Python
Strings in Python
nitamhaske
 
ppt notes python language operators and data
ppt notes python language operators and datappt notes python language operators and data
ppt notes python language operators and data
SukhpreetSingh519414
 
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvbecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
ecFDkQifGYWkHLXQ395.pptxbbbbngvbngrrghxcvvb
JayPatil347597
 
STRINGS IN PYTHON
STRINGS IN PYTHONSTRINGS IN PYTHON
STRINGS IN PYTHON
TanushTM1
 
strings in python (presentation for DSA)
strings in python (presentation for DSA)strings in python (presentation for DSA)
strings in python (presentation for DSA)
MirzaAbdullahTariq
 
Python course in_mumbai
Python course in_mumbaiPython course in_mumbai
Python course in_mumbai
vibrantuser
 
Python course in_mumbai
Python course in_mumbaiPython course in_mumbai
Python course in_mumbai
vibrantuser
 
python_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptxpython_computer engineering_semester_computer_language.pptx
python_computer engineering_semester_computer_language.pptx
MadhusmitaSahu40
 
Notes3
Notes3Notes3
Notes3
hccit
 
ADST university of Sussex foundation class
ADST university of Sussex foundation classADST university of Sussex foundation class
ADST university of Sussex foundation class
MarufFarhanRigan1
 
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoiiStrings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
Strings3a4esrxdfgcbhjjjjjiiol;lkljiojoii
pawankamal3
 

More from S.Mohideen Badhusha (7)

Introduction to Python Data Analytics.pdf
Introduction to Python Data Analytics.pdfIntroduction to Python Data Analytics.pdf
Introduction to Python Data Analytics.pdf
S.Mohideen Badhusha
 
Simple intro to HTML and its applications
Simple intro to HTML and its applicationsSimple intro to HTML and its applications
Simple intro to HTML and its applications
S.Mohideen Badhusha
 
PHP Programming and its Applications workshop
PHP Programming and its Applications workshopPHP Programming and its Applications workshop
PHP Programming and its Applications workshop
S.Mohideen Badhusha
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Object oriented Programming using C++ and Java
Object oriented Programming using C++ and JavaObject oriented Programming using C++ and Java
Object oriented Programming using C++ and Java
S.Mohideen Badhusha
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Introduction to Python Data Analytics.pdf
Introduction to Python Data Analytics.pdfIntroduction to Python Data Analytics.pdf
Introduction to Python Data Analytics.pdf
S.Mohideen Badhusha
 
Simple intro to HTML and its applications
Simple intro to HTML and its applicationsSimple intro to HTML and its applications
Simple intro to HTML and its applications
S.Mohideen Badhusha
 
PHP Programming and its Applications workshop
PHP Programming and its Applications workshopPHP Programming and its Applications workshop
PHP Programming and its Applications workshop
S.Mohideen Badhusha
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Object oriented Programming using C++ and Java
Object oriented Programming using C++ and JavaObject oriented Programming using C++ and Java
Object oriented Programming using C++ and Java
S.Mohideen Badhusha
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
‘How to develop Pythonic coding rather than Python coding – Logic Perspective’
S.Mohideen Badhusha
 
Ad

Recently uploaded (20)

Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank22PCOAM16 _ML_Unit 3 Notes & Question bank
22PCOAM16 _ML_Unit 3 Notes & Question bank
Guru Nanak Technical Institutions
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
IntroSlides-June-GDG-Cloud-Munich community [email protected]
IntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdfIntroSlides-June-GDG-Cloud-Munich community gathering@Netlight.pdf
IntroSlides-June-GDG-Cloud-Munich community [email protected]
Luiz Carneiro
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptxSemi-Conductor ppt ShubhamSeSemi-Con.pptx
Semi-Conductor ppt ShubhamSeSemi-Con.pptx
studyshubham18
 
chemistry investigatory project for class 12
chemistry investigatory project for class 12chemistry investigatory project for class 12
chemistry investigatory project for class 12
Susis10
 
First Review PPT gfinal gyft ftu liu yrfut go
First Review PPT gfinal gyft  ftu liu yrfut goFirst Review PPT gfinal gyft  ftu liu yrfut go
First Review PPT gfinal gyft ftu liu yrfut go
Sowndarya6
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODSWIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought                           .社内勉強会資料_Chain of Thought                           .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journeyRigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
IOt Based Research on Challenges and Future
IOt Based Research on Challenges and FutureIOt Based Research on Challenges and Future
IOt Based Research on Challenges and Future
SACHINSAHU821405
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Ad

‘How to develop Pythonic coding rather than Python coding – Logic Perspective’

  • 1. Online Workshop on ‘How to develop Pythonic coding rather than Python coding – Logic Perspective’ 21.7.20 Day 1 session 2 Dr. S.Mohideen Badhusha Professor/ CSE department Alva’s Institute Engineering and Technology Mijar, Moodbidri, Mangalore 1
  • 3. 3 To acquire knowledge of iteration and string in Python To comprehend the concept of looping statements in Python To practice the simple problems in iteration and string Objectives of the Day 1 session 2
  • 4. 4 Iteration for loop for var in <collection>: <statements> where collection is iterable obj like list, tuple,dictionary,string and range a = [’i’, ’say’, ’hello’] # a list of string elements for i in range(len(a)): print (i,end=’ ’) print (a[i]) Output 0 I 1 say 2 hello
  • 5. 5 Iteration while loop while condition : <Statements> i=0 while (i < 10): print( i) i += 1 o/p 0 1 2 . 9
  • 6. 6 Another Example for loop for someChar in “Hello” : print(someChar) Output H e l l o
  • 7. 7 d=[(1,'a'),(2,'b'),(3,'c'),(4,'d'),(5,'e')] for (x, y) in d : print (x,y) o/p 1 a 2 b 3 c 4 d 5 e
  • 8. 8 for loop using range() for x in range(5): print x o/p 0 1 2 3 4
  • 9. 9 Python program but not Pythonic def traverse(string): index = 0 while index < len(string): letter = string[index] print(letter) index += 1 traverse('Monty Python') Output ?
  • 10. 10 def traverse(string): for letter in string: print (letter) traverse('Monty Python’) Pythonic program
  • 11. 11 in operator in is a boolean operator that checks membership within a sequence It is also called membership operator. 'a' in 'banana' True 'o' in 'banana' False
  • 13. 13 String handling functions s=’HELLO’ s.lower() # hello s1=’hello’ s1.upper() # HELLO s.strip() -- returns a string with whitespace removed from the start and end s=’ I am happy ‘ s.strip() # I am happy ( no front and back spaces) s.isalpha()# True s.isdigit() # False s.isspace() #False
  • 14. 14 split() and join() functions s.split('delim') - returns a string into a list of words separated by delim Ex: 'aaa,bbb,ccc'.split(',') -> ['aaa', 'bbb', 'ccc']. Defalut delim is space s.join(list) -- opposite of split(), joins the elements in the given list together using the string as the delimiter. Ex: '---'.join(['aaa', 'bbb', 'ccc']) -> ‘aaa---bbb---ccc’ 14
  • 15. 15 String Formatting Operator: % The operator % allows strings to be built out of many data items in a “fill in the blanks” fashion. x = “Ram” y = 34 print(“%s’s age is %d” % (x, y)) o/p Ram’s age is 34 The tuple following the % operator is used to fill in the blanks in the original string marked with %s %g %d to represent string, float and integer values
  • 16. 16 Converting anything to a String The built-in str() function can convert an instance of any data type into a string Ex: print(“Hello ” + str(2)) o/p Hello 2
  • 17. 17 Slicing strings A segment of a string is called a slice. Selecting a slice is similar to selecting a character: Ex: s = 'Monty Python' print(s[0:5]) Monty print(s[6:12]) Python
  • 19. 19 String Indexing print(s[-1]) o/p 'o' #last char (1st from the end) print(s[-4]) o/p 'e' # 4th from the end print(s[:-3]) o/p 'He' – from starting, going up to but not including the last 3 chars. s[-3:] is 'llo' -- starting with the 3rd char from the end and extending to the end of the string.
  • 20. 20 s[1:4] is 'ell' -- chars starting at index 1 and extending up to but not including index 4 s[1:] is 'ello' -- omitting either index defaults to the start or end of the string s[:] is 'Hello' -- omitting both always gives us a copy of the whole thing s[1:100] is 'ello' -- an index that is too big is truncated down to the string length
  • 21. 21 Concluding Tips for loop in Python is entirely different from other programming languages[ for var in collection] while loop in Python is similar to the programming constructs in other languages There is no do… while loop existing in Python To be Pythonic, we should use data structures and PEP 8 rules in Python In slicing of string, st[i:n], we have to consider from i th index to n-1 . st[:n] from 0 th index to n-1. st[i:] from i th index to end of the string