SlideShare a Scribd company logo
INTRODUCTION
TO
PYTHON
PROGRAMMING
-By
Ziyauddin Shaik
Btech (CSE)
(PART - 3)
Contents
• Reassignment
• loops ( for,while)
• break & continue statements
• string
• string slices
• string operations
• string methods
• lists
• list operations
• list methods
Reassignment
it is to make more than one assignment to the same variable.
 A new assignment makes an existing variable refer to a new value (and stop
referring to the old value).
Ex:
x = 5
print( x)
x = 7
print( x )
Output :
5
7
The first time we display x, its value is 5; the second time, its value is 7.
Update :
A common kind of reassignment is an update,
where the new value of the variable depends
on the old.
EX:
x = x + 1
This means “get the current value of x, add
one, and then update x with the new value.”
Loops :
when you need to execute a block of code several number of times.
A loop statement allows us to execute a statement or group of statements
multiple times
The python provide two types of loops for iterative statements execution:
1. for loop
2. While loop
1. for loop :
A for loop is used for iterating over a sequence (that is a list, a tuple, a
dictionary, a set, or a string).
In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for
in” loop which is similar to “for each” loop in other languages.
Syntax:
for iterator_variable in sequence:
statements(s)
Example :
fruits = ["apple", "banana",
"cherry"]
for x in fruits:
print(x)
Example :
s = "python"
for i in s :
print(i)
OUTPUT:
apple
banana
cherry
OUTPUT:
p
y
t
h
o
n
For loop Using range() function:
The range() function is used to generate the sequence of the numbers.
If we pass the range(10), it will generate the numbers from 0 to 9.
Syntax: range(start, stop, step size)
optional
optional
beginning of the iteration. the loop will iterate till stop-1 used to skip the specific
numbers from the iteration.
Example :
for i in range(10):
print(i,end = ' ')
Output:
0 1 2 3 4 5 6 7 8 9
Nested for loop :
Python allows us to nest any number of for loops inside a for loop.
The inner loop is executed n number of times for every iteration of the outer
loop. The syntax is given below.
Syntax:
for var1 in sequence:
for var2 in sequence:
#block of statements
#Other statements
Example :
rows = int(input("Enter the rows:"))
for i in range(0,rows+1):
for j in range(i):
print("*",end = '')
print()
Output:
Enter the rows:5
*
**
***
****
*****
2. while loop
The Python while loop allows a part of the code to be executed until
the given condition returns false.
Syntax:
while expression:
statements Program :
i=1;
while i<=10:
print(i);
i=i+1;
Output:
1
2
3
4
5
6
7
8
9
10
break statement:
The break statement is used to
terminate the loop intermediately.
 “break” is keyword in python
Syntax:
#loop statements
break;
Example :
n=10
for i in range(n):
if i==5:
break;
print(i)
OUTPUT:
0
1
2
3
4
continue Statement:
With the continue statement we can
stop the current iteration of the loop,
and continue with the next.
Syntax:
#loop statements
continue;
Example :
n=10
for i in range(n):
if i==5:
continue;
print(i)
OUTPUT:
0
1
2
3
4
6
7
8
9
String:
string is the collection of the characters enclosed by single /double /triple quotes.
Ex: str=‘Hello’
str= “Hello”
str=‘’’Hello’’’
1. Length using len()
Example :
str=“hello”
print(len(str))
String length : 5
Output :
5
2. Traversal with a for loop:
Example :
str=“HELLO”
for i in str:
print(i)
OUTPUT:
H
E
L
L
O
String slices:
We can access the portion(sub part ) of the string using slice operator–[:]”.
we use slice operator for accessing range elements.
Syntax: Variable[begin:end:step]
The step may be +ve( or ) –ve
If step is +ve it is forward direction (left to right)(begin to end-1)
If step is -ve it is backward direction(right to left)(begin to end+1)
In forward direction The default value of “begin” is 0
In forward direction The default value of “end” is length of sequence
The default value of “step” is 1
In backward direction The default value of “begin” is -1
In forward direction The default value of “end” is –(length of sequence)
Introduction to python programming ( part-3 )
Example :
str=“welcome”
print(str[2:5]) output: lco
print(str[2:5:2]) output: lo
print(str[-1:-5:-1]) output: emoc
print(str[-1:5:1]) output:
default step size is 1,in forword
direction
end position is:5-1=4
step size is 2,in forword direction end
position is:5-1=4
step size is -1,in back word direction end
position is:-5+1=-4
because in forward
direction there is no -1 index
Strings are immutable:
String are immutable in python that mean we can’t change the string
elements, but we replace entire string.
Example :
str=“HELLO”
str[0]=‘M’ output: error
print(str)
Example :
str=“HELLO”
str=“welcome”
print(str) output: welcome
Looping and Counting:
While iterating the string we can count the number of characters(or) number of
words present in the string.
Ex:
Str=“welcome to python programming”
count=0
for c in str:
if c==‘e’:
count=count+1
print(“the letter e is present:”,count,”times”)
OUTPUT:
The letter e is present 2 times
String Operations:
Operator Description
+
It is known as concatenation operator used to join the strings
given either side of the operator.
*
It is known as repetition operator. It concatenates the multiple
copies of the same string.
[] It is known as slice operator. It is used to access the sub-strings
of a particular string.
[:] It is known as range slice operator. It is used to access the
characters from the specified range.
in It is known as membership operator. It returns if a particular
sub-string is present in the specified string.
not in It is also a membership operator and does the exact reverse of
in. It returns true if a particular substring is not present in the
specified string.
Example :
str = "Hello"
str1 = " world"
print(str*3)
print(str+str1)
print(str[4])
print(str[2:4])
print('w' in str)
print('wo' not in str1)
Output:
HelloHelloHello
Hello world
o
ll
False
False
String Methods:
3.Find() : The find() method finds the first
occurrence of the specified value.
Ex :
txt = "Hello, welcome to my world.“
x = txt.find("e")
print(x)
4.index():
It is almost the same as the find() method, the only
difference is that the find() method returns -1 if
the value is not found
Ex:
txt = "Hello, welcome to my world.“
print(txt.find("q"))
print(txt.index("q"))
Output
1
Output :
-1
valueError
1.capitalize():Converts the first character to
upper case
Ex : txt = "hello, and welcome to my world.“
x = txt.capitalize()
print (x)
Output : Hello, and welcome to my world.
2.count() :Returns the number of times a
specified value occurs in a string
Ex : txt = "I love apple, apple is my favorite fruit"
x = txt.count("apple")
print(x)
Output
2
5. isalnum(): returns True if all the
characters are alphanumeric
Ex:
txt = "Company 12“
x = txt.isalnum()
print(x)
6.isalpha(): Returns True if all
characters in the string are in the
alphabet
Ex:
txt = "Company10“
x = txt.isalpha()
print(x)
Output :
False
Output :
False
7.islower(): Returns True if all characters in the
string are lower case
Ex:
a = "Hello world!“
b = "hello 123“
c = "mynameisPeter“
print(a.islower())
print(b.islower())
print(c.islower())
Output :
False
True
False
8. isupper(): Returns True if all characters in the
string are upper cases
Ex:
a = "Hello World!"
b = "hello 123"
c = "HELLO“
print(a.isupper())
print(b.isupper())
print(c.isupper())
Output :
False
False
True
9.split(): It splits a string into a list.
Ex:
txt = "welcome to the jungle“
x = txt.split()
print(x)
Output:
['welcome', 'to', 'the', 'jungle']
13.replace():It replaces the old sequence of
characters with the new sequence.
Ex :
str1 = ”python is a programming language"
str2 = str.replace(“python","C")
print(str2)
Output:
C is a programming language
Reading word lists:
Ex:
file= open(‘jk.txt','r‘)
for line in file:
for word in line.split():
print(word)
input file consisting the following
text file name is ‘jk.txt’
Welcome To Python Programming
Hello How Are You
Output:
Welcome
To
Python
Programming
Hello
How
Are
You
Lists:
 A list is a collection of different elements. The items in the list are
separated with the comma (,) and enclosed with the square brackets [].
Creating Empty list
Syntax: List variable=[ ]
Ex: l=[ ]
Creating List with elements
Syntax: List variable=[element1,element2,--------,element]
Ex1: l=[10,20,30,40]
Ex2: l1=[10,20.5,”Selena”]
Program:
l=[10,20,30]
l1=[10,20.5,”Selena”]
print(l)
print(l1)
Output :
[10,20,30]
[10, 20.5, Selena]
Accessing List elements (or)items:
 We Access list elements by using “index” value like Array in C language. We
use index vale for access individual element.
 We can also Access list elements by using “Slice Operator –[:]”. we use slice
operator for accessing range elements.
Loop Through a List:
You can apply loops on the list items. by using a for loop:
Program:
list = [10, "banana", 20.5]
for x in list:
print(x)
Output:
10
banana
20.5
Program:
List = ["Justin", "Charlie", "Rose", "Selena"]
for i in List:
print(i)
Output:
Justin
Charlie
Rose
Selena
Operations on the list:
 The concatenation (+) and repetition (*) operator work in the same way as
they were working with the strings.

The + operator concatenates lists:
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
[1, 2, 3, 4, 5, 6]
The * operator repeats a list a given number of times:
>>> [0] * 4
[0, 0, 0, 0]
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
The first example repeats [0] four times.
The second example repeats the list [1, 2, 3] threetimes.
List Built-in functions:
Program
L1=[10,20,4,’a’]
print(len(L1))
Program:
L1=[10,20,4,2]
print(max(L1))
Program:
L1=[10,20,4,2]
print(min(L1))
Output :
4
Output :
20
Output :
2
len()
max()
min()
List built-in methods:
Program:
l=[ ]
l.append(10)
l.append(20)
l.append(30)
print(“The list elements are:”)
print(l)
Output:
The list elements are:
[10,20,30]
Program:
l=[10,20,30,15,20]
print(“Before insert list elements:”,l)
l.insert(1,50)
print(“After insert list elements:”,l)
Output:
Before insert list elements:[10, 20, 30, 15, 20]
After insert list elements:[10, 50,20, 30, 15, 20]
append() insert() extend()
reverse() index() clear()
sort() pop() copy() count()
Ex:
l1=[10,20,30]
l2=[100,200,300,400]
print(“Before extend list1 elements are:”,l1)
l1.extend(l2).
print(“After extend list1 elements are:”,l1)
Output:
Before extend list1 elements are:[10,20,30]
After extend list1 elements
are:[10,20,30,100,200,300,400]
Ex:
l=[10,20,30,40]
x=l.index(20)
print(“The index of 20 is:”,x)
Output:
The index of 20 is:1
Program:
L=[10,20,30,15]
print(“Before reverse the list elements:”,L)
L.reverse()
print(“After revers the list elements:”,L)
Output:
Before reverse the list elements:[10,20,30,15]
After reverse the list elements:[15,30,20,10]
Program:
l=[10,20,30,40]
print(“Before clear list elements are:”, l)
l.clear()
print(“After clear list elements are:”, l)
Output:
Before clear list elements are: [10,20,30,40]
After clear list elements:
Program:
L=[10,20,5,14,30,15]
print(“Before sorting list elements are:”,L)
L.sort()
print(“After sort list elements are:”,L)
Output:
Before sorting list elements are:[10,20,5,14.30,15]
After sorting list elements are:[5,10,14,15,20,30]
Program:
l=[10,20,30,40]
print(“Before pop list elements are:”, l)
#here pop last element in the list
x=l.pop()
print(“The pop element is:”, x)
print(“After pop list elements are:”, l)
Output:
Before pop list elements are:[10, 20, 30, 40]
The pop element is: 40
After pop list elements are:[10, 20, 30]
Program :
l1=[10,20,30,40]
l2=[]
l2=l1.copy()
print(“Original list element L1:”,l1)
print(“Copy list elements l2:”,l2)
Output:
Original list element L1:[10,20,30,40]
Copy list element L2:[10,20,30,40]
Ex:
l1=[10,20,30,40,20,50,20]
x=l1.count(20)
print(“The count of 20 is:”,x)
Output:
The count of 20 is:3
# THANK YOU

More Related Content

PPTX
String Manipulation in Python
Pooja B S
 
PPTX
Python ppt
Anush verma
 
PPTX
Python Revision Tour.pptx class 12 python notes
student164700
 
PPTX
Python Datatypes by SujithKumar
Sujith Kumar
 
PPTX
Keep it Stupidly Simple Introduce Python
SushJalai
 
PPTX
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
PPT
2025pylab engineering 2025pylab engineering
srilakshmime
 
String Manipulation in Python
Pooja B S
 
Python ppt
Anush verma
 
Python Revision Tour.pptx class 12 python notes
student164700
 
Python Datatypes by SujithKumar
Sujith Kumar
 
Keep it Stupidly Simple Introduce Python
SushJalai
 
Introduction to python programming ( part-2 )
Ziyauddin Shaik
 
2025pylab engineering 2025pylab engineering
srilakshmime
 

Similar to Introduction to python programming ( part-3 ) (20)

PPTX
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
ODP
Day2
Karin Lagesen
 
PDF
Python Loop
Soba Arjun
 
PDF
updated_tuple_in_python.pdf
Koteswari Kasireddy
 
PPTX
iPython
Aman Lalpuria
 
PDF
Introduction to python programming
Rakotoarison Louis Frederick
 
PDF
Python Data Types.pdf
NehaSpillai1
 
PDF
Python Data Types (1).pdf
NehaSpillai1
 
PPTX
Python basics
Hoang Nguyen
 
PPTX
Python basics
Young Alista
 
PPTX
Python basics
Harry Potter
 
PPTX
Python basics
Fraboni Ec
 
PPTX
Python basics
Tony Nguyen
 
PPTX
Python basics
James Wong
 
PPTX
Python basics
Luis Goldster
 
PPT
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
PPTX
PRESENTATION ON STRING, LISTS AND TUPLES IN PYTHON.pptx
kirtisharma7537
 
PDF
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
PPT
PYTHON
JOHNYAMSON
 
PDF
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Python Workshop - Learn Python the Hard Way
Utkarsh Sengar
 
Python Loop
Soba Arjun
 
updated_tuple_in_python.pdf
Koteswari Kasireddy
 
iPython
Aman Lalpuria
 
Introduction to python programming
Rakotoarison Louis Frederick
 
Python Data Types.pdf
NehaSpillai1
 
Python Data Types (1).pdf
NehaSpillai1
 
Python basics
Hoang Nguyen
 
Python basics
Young Alista
 
Python basics
Harry Potter
 
Python basics
Fraboni Ec
 
Python basics
Tony Nguyen
 
Python basics
James Wong
 
Python basics
Luis Goldster
 
chap 06 hgjhg hghg hh ghg jh jhghj gj g.ppt
santonino3
 
PRESENTATION ON STRING, LISTS AND TUPLES IN PYTHON.pptx
kirtisharma7537
 
23UCACC11 Python Programming (MTNC) (BCA)
ssuser7f90ae
 
PYTHON
JOHNYAMSON
 
Python Cheatsheet_A Quick Reference Guide for Data Science.pdf
zayanchutiya
 
Ad

More from Ziyauddin Shaik (6)

PPTX
Operating Systems
Ziyauddin Shaik
 
PPTX
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
PPTX
Introduction to python programming ( part-1)
Ziyauddin Shaik
 
PPTX
Product Design
Ziyauddin Shaik
 
PPTX
Capsule Endoscopy
Ziyauddin Shaik
 
PPTX
Amazon Go : The future of shopping
Ziyauddin Shaik
 
Operating Systems
Ziyauddin Shaik
 
Webinar : P, NP, NP-Hard , NP - Complete problems
Ziyauddin Shaik
 
Introduction to python programming ( part-1)
Ziyauddin Shaik
 
Product Design
Ziyauddin Shaik
 
Capsule Endoscopy
Ziyauddin Shaik
 
Amazon Go : The future of shopping
Ziyauddin Shaik
 
Ad

Recently uploaded (20)

PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
PPTX
Role Of Python In Programing Language.pptx
jaykoshti048
 
PDF
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
PPTX
Presentation about variables and constant.pptx
safalsingh810
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PPTX
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PPTX
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
PPTX
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PPTX
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
PDF
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Appium Automation Testing Tutorial PDF: Learn Mobile Testing in 7 Days
jamescantor38
 
Role Of Python In Programing Language.pptx
jaykoshti048
 
Become an Agentblazer Champion Challenge Kickoff
Dele Amefo
 
Presentation about variables and constant.pptx
safalsingh810
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
slidesgo-unlocking-the-code-the-dynamic-dance-of-variables-and-constants-2024...
kr2589474
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Why Use Open Source Reporting Tools for Business Intelligence.pptx
Varsha Nayak
 
Web Testing.pptx528278vshbuqffqhhqiwnwuq
studylike474
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Why Use Open Source Reporting Tools for Business Intelligence.pdf
Varsha Nayak
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PFAS Reporting Requirements 2026 Are You Submission Ready Certivo.pptx
Certivo Inc
 
Teaching Reproducibility and Embracing Variability: From Floating-Point Exper...
University of Rennes, INSA Rennes, Inria/IRISA, CNRS
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 

Introduction to python programming ( part-3 )

  • 2. Contents • Reassignment • loops ( for,while) • break & continue statements • string • string slices • string operations • string methods • lists • list operations • list methods
  • 3. Reassignment it is to make more than one assignment to the same variable.  A new assignment makes an existing variable refer to a new value (and stop referring to the old value). Ex: x = 5 print( x) x = 7 print( x ) Output : 5 7 The first time we display x, its value is 5; the second time, its value is 7. Update : A common kind of reassignment is an update, where the new value of the variable depends on the old. EX: x = x + 1 This means “get the current value of x, add one, and then update x with the new value.”
  • 4. Loops : when you need to execute a block of code several number of times. A loop statement allows us to execute a statement or group of statements multiple times The python provide two types of loops for iterative statements execution: 1. for loop 2. While loop 1. for loop : A for loop is used for iterating over a sequence (that is a list, a tuple, a dictionary, a set, or a string). In Python, there is no C style for loop, i.e., for (i=0; i<n; i++). There is “for in” loop which is similar to “for each” loop in other languages.
  • 5. Syntax: for iterator_variable in sequence: statements(s) Example : fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) Example : s = "python" for i in s : print(i) OUTPUT: apple banana cherry OUTPUT: p y t h o n
  • 6. For loop Using range() function: The range() function is used to generate the sequence of the numbers. If we pass the range(10), it will generate the numbers from 0 to 9. Syntax: range(start, stop, step size) optional optional beginning of the iteration. the loop will iterate till stop-1 used to skip the specific numbers from the iteration. Example : for i in range(10): print(i,end = ' ') Output: 0 1 2 3 4 5 6 7 8 9
  • 7. Nested for loop : Python allows us to nest any number of for loops inside a for loop. The inner loop is executed n number of times for every iteration of the outer loop. The syntax is given below. Syntax: for var1 in sequence: for var2 in sequence: #block of statements #Other statements Example : rows = int(input("Enter the rows:")) for i in range(0,rows+1): for j in range(i): print("*",end = '') print() Output: Enter the rows:5 * ** *** **** *****
  • 8. 2. while loop The Python while loop allows a part of the code to be executed until the given condition returns false. Syntax: while expression: statements Program : i=1; while i<=10: print(i); i=i+1; Output: 1 2 3 4 5 6 7 8 9 10
  • 9. break statement: The break statement is used to terminate the loop intermediately.  “break” is keyword in python Syntax: #loop statements break; Example : n=10 for i in range(n): if i==5: break; print(i) OUTPUT: 0 1 2 3 4 continue Statement: With the continue statement we can stop the current iteration of the loop, and continue with the next. Syntax: #loop statements continue; Example : n=10 for i in range(n): if i==5: continue; print(i) OUTPUT: 0 1 2 3 4 6 7 8 9
  • 10. String: string is the collection of the characters enclosed by single /double /triple quotes. Ex: str=‘Hello’ str= “Hello” str=‘’’Hello’’’ 1. Length using len() Example : str=“hello” print(len(str)) String length : 5 Output : 5 2. Traversal with a for loop: Example : str=“HELLO” for i in str: print(i) OUTPUT: H E L L O
  • 11. String slices: We can access the portion(sub part ) of the string using slice operator–[:]”. we use slice operator for accessing range elements. Syntax: Variable[begin:end:step] The step may be +ve( or ) –ve If step is +ve it is forward direction (left to right)(begin to end-1) If step is -ve it is backward direction(right to left)(begin to end+1) In forward direction The default value of “begin” is 0 In forward direction The default value of “end” is length of sequence The default value of “step” is 1 In backward direction The default value of “begin” is -1 In forward direction The default value of “end” is –(length of sequence)
  • 13. Example : str=“welcome” print(str[2:5]) output: lco print(str[2:5:2]) output: lo print(str[-1:-5:-1]) output: emoc print(str[-1:5:1]) output: default step size is 1,in forword direction end position is:5-1=4 step size is 2,in forword direction end position is:5-1=4 step size is -1,in back word direction end position is:-5+1=-4 because in forward direction there is no -1 index
  • 14. Strings are immutable: String are immutable in python that mean we can’t change the string elements, but we replace entire string. Example : str=“HELLO” str[0]=‘M’ output: error print(str) Example : str=“HELLO” str=“welcome” print(str) output: welcome
  • 15. Looping and Counting: While iterating the string we can count the number of characters(or) number of words present in the string. Ex: Str=“welcome to python programming” count=0 for c in str: if c==‘e’: count=count+1 print(“the letter e is present:”,count,”times”) OUTPUT: The letter e is present 2 times
  • 16. String Operations: Operator Description + It is known as concatenation operator used to join the strings given either side of the operator. * It is known as repetition operator. It concatenates the multiple copies of the same string. [] It is known as slice operator. It is used to access the sub-strings of a particular string. [:] It is known as range slice operator. It is used to access the characters from the specified range. in It is known as membership operator. It returns if a particular sub-string is present in the specified string. not in It is also a membership operator and does the exact reverse of in. It returns true if a particular substring is not present in the specified string. Example : str = "Hello" str1 = " world" print(str*3) print(str+str1) print(str[4]) print(str[2:4]) print('w' in str) print('wo' not in str1) Output: HelloHelloHello Hello world o ll False False
  • 17. String Methods: 3.Find() : The find() method finds the first occurrence of the specified value. Ex : txt = "Hello, welcome to my world.“ x = txt.find("e") print(x) 4.index(): It is almost the same as the find() method, the only difference is that the find() method returns -1 if the value is not found Ex: txt = "Hello, welcome to my world.“ print(txt.find("q")) print(txt.index("q")) Output 1 Output : -1 valueError 1.capitalize():Converts the first character to upper case Ex : txt = "hello, and welcome to my world.“ x = txt.capitalize() print (x) Output : Hello, and welcome to my world. 2.count() :Returns the number of times a specified value occurs in a string Ex : txt = "I love apple, apple is my favorite fruit" x = txt.count("apple") print(x) Output 2
  • 18. 5. isalnum(): returns True if all the characters are alphanumeric Ex: txt = "Company 12“ x = txt.isalnum() print(x) 6.isalpha(): Returns True if all characters in the string are in the alphabet Ex: txt = "Company10“ x = txt.isalpha() print(x) Output : False Output : False 7.islower(): Returns True if all characters in the string are lower case Ex: a = "Hello world!“ b = "hello 123“ c = "mynameisPeter“ print(a.islower()) print(b.islower()) print(c.islower()) Output : False True False 8. isupper(): Returns True if all characters in the string are upper cases Ex: a = "Hello World!" b = "hello 123" c = "HELLO“ print(a.isupper()) print(b.isupper()) print(c.isupper()) Output : False False True
  • 19. 9.split(): It splits a string into a list. Ex: txt = "welcome to the jungle“ x = txt.split() print(x) Output: ['welcome', 'to', 'the', 'jungle'] 13.replace():It replaces the old sequence of characters with the new sequence. Ex : str1 = ”python is a programming language" str2 = str.replace(“python","C") print(str2) Output: C is a programming language
  • 20. Reading word lists: Ex: file= open(‘jk.txt','r‘) for line in file: for word in line.split(): print(word) input file consisting the following text file name is ‘jk.txt’ Welcome To Python Programming Hello How Are You Output: Welcome To Python Programming Hello How Are You
  • 21. Lists:  A list is a collection of different elements. The items in the list are separated with the comma (,) and enclosed with the square brackets []. Creating Empty list Syntax: List variable=[ ] Ex: l=[ ] Creating List with elements Syntax: List variable=[element1,element2,--------,element] Ex1: l=[10,20,30,40] Ex2: l1=[10,20.5,”Selena”] Program: l=[10,20,30] l1=[10,20.5,”Selena”] print(l) print(l1) Output : [10,20,30] [10, 20.5, Selena]
  • 22. Accessing List elements (or)items:  We Access list elements by using “index” value like Array in C language. We use index vale for access individual element.  We can also Access list elements by using “Slice Operator –[:]”. we use slice operator for accessing range elements.
  • 23. Loop Through a List: You can apply loops on the list items. by using a for loop: Program: list = [10, "banana", 20.5] for x in list: print(x) Output: 10 banana 20.5 Program: List = ["Justin", "Charlie", "Rose", "Selena"] for i in List: print(i) Output: Justin Charlie Rose Selena
  • 24. Operations on the list:  The concatenation (+) and repetition (*) operator work in the same way as they were working with the strings.  The + operator concatenates lists: >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> c = a + b >>> print c [1, 2, 3, 4, 5, 6] The * operator repeats a list a given number of times: >>> [0] * 4 [0, 0, 0, 0] >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] The first example repeats [0] four times. The second example repeats the list [1, 2, 3] threetimes.
  • 26. List built-in methods: Program: l=[ ] l.append(10) l.append(20) l.append(30) print(“The list elements are:”) print(l) Output: The list elements are: [10,20,30] Program: l=[10,20,30,15,20] print(“Before insert list elements:”,l) l.insert(1,50) print(“After insert list elements:”,l) Output: Before insert list elements:[10, 20, 30, 15, 20] After insert list elements:[10, 50,20, 30, 15, 20] append() insert() extend() reverse() index() clear() sort() pop() copy() count()
  • 27. Ex: l1=[10,20,30] l2=[100,200,300,400] print(“Before extend list1 elements are:”,l1) l1.extend(l2). print(“After extend list1 elements are:”,l1) Output: Before extend list1 elements are:[10,20,30] After extend list1 elements are:[10,20,30,100,200,300,400] Ex: l=[10,20,30,40] x=l.index(20) print(“The index of 20 is:”,x) Output: The index of 20 is:1 Program: L=[10,20,30,15] print(“Before reverse the list elements:”,L) L.reverse() print(“After revers the list elements:”,L) Output: Before reverse the list elements:[10,20,30,15] After reverse the list elements:[15,30,20,10] Program: l=[10,20,30,40] print(“Before clear list elements are:”, l) l.clear() print(“After clear list elements are:”, l) Output: Before clear list elements are: [10,20,30,40] After clear list elements:
  • 28. Program: L=[10,20,5,14,30,15] print(“Before sorting list elements are:”,L) L.sort() print(“After sort list elements are:”,L) Output: Before sorting list elements are:[10,20,5,14.30,15] After sorting list elements are:[5,10,14,15,20,30] Program: l=[10,20,30,40] print(“Before pop list elements are:”, l) #here pop last element in the list x=l.pop() print(“The pop element is:”, x) print(“After pop list elements are:”, l) Output: Before pop list elements are:[10, 20, 30, 40] The pop element is: 40 After pop list elements are:[10, 20, 30] Program : l1=[10,20,30,40] l2=[] l2=l1.copy() print(“Original list element L1:”,l1) print(“Copy list elements l2:”,l2) Output: Original list element L1:[10,20,30,40] Copy list element L2:[10,20,30,40] Ex: l1=[10,20,30,40,20,50,20] x=l1.count(20) print(“The count of 20 is:”,x) Output: The count of 20 is:3