SlideShare a Scribd company logo
Rahul Kumar
CS Deptt. KIET
rahul.kumar@kiet.edu
Conditional statement
Bibek Kumar-Assistant Professor-CSE,
KIET
If, elif, else statement
Bibek Kumar-Assistant Professor-CSE,
KIET
if Statements in Python allows us to tell the computer to perform alternative actions based on a
certain set of results.
Verbally, we can imagine we are telling the computer:
"Hey if this case happens, perform some action"
We can then expand the idea further with elif and else statements, which allow us to tell the
computer:
"Hey if this case happens, perform some action. Else, if another case happens, perform some other
action. Else, if none of the above cases happened, perform this action."
If the condition "condition_1" is True, the statements of the block
statement_block_1 will be executed. If not, condition_2 will be
evaluated. If condition_2 evaluates to True, statement_block_2 will
be executed, if condition_2 is False, the other conditions of the
following elif conditions will be checked, and finally if none of them
has been evaluated to True, the indented block below the else
keyword will be executed.
Bibek Kumar-Assistant Professor-CSE,
KIET
The if, elif and else Statements
Examples Multiple Branches
Note how the nested if statements are each checked until a
True Boolean causes the nested code below it to run. We should
also note that we can put in as many elif statements as we want
before we close off with an else.
While
Bibek Kumar-Assistant Professor-CSE,
KIET
The while statement in Python is one of most general ways to perform
iteration. A while statement will repeatedly execute a single statement or
group of statements as long as the condition is true. The reason it is called a
'loop' is because the code statements are looped through over and over
again until the condition is no longer met.
Notice how many times the print statements
occurred and how the while loop kept going until
the True condition was met, which occurred once
x==10. It's important to note that once this
occurred the code stopped.
While Loops
We can also add else statement in the loop as shown
When the loop completes, the else statement is read
5
While Loops
We can use break, continue, and pass statements in our loops to add additional functionality for
various cases. The three statements are defined by:
•break: Breaks out of the current closest enclosing loop.
•continue: Goes to the top of the closest enclosing loop.
•pass: Does nothing at all.
Syntax:
while test:
code
statement
if test:
break
if test:
continue
else:
break and continue statements can appear anywhere inside the loop’s body, but we will usually
put them further nested in conjunction with an if statement to perform an action based on
some condition.
A word of caution however! It is possible to create an
infinitely running loop with while statements.
6
A for loop acts as an iterator in Python; it goes through items
that are in a sequence or any other iterable item. Objects that
we've learned about that we can iterate over include strings,
lists, tuples, and even built-in iterables for dictionaries, such as
keys or values.
for item in object:
statements to do
stuff
Example
Let's print only the even numbers from that list!
We could have also put an else statement in there
7
For loop
Using the for Statement
Another common idea during a for loop is keeping some sort of
running tally during multiple loops
We've used for loops with lists, how about with strings?
Remember strings are a sequence so when we iterate through
them we will be accessing each item in that string.
Let's now look at how a for loop can be used with a tuple
Tuples are very similar to lists, however, unlike lists they are
immutable meaning they can not be changed. You would use
tuples to present things that shouldn't be changed, such as days
of the week, or dates on a calendar.
The construction of a tuples use () with elements separated by
commas.
8
Using the for Statement
Tuples have a special quality when it comes to for loops. If you
are iterating through a sequence that contains tuples, the item
can actually be the tuple itself, this is an example of tuple
unpacking. During the for loop we will be unpacking the tuple
inside of a sequence and we can access the individual items
inside that tuple!
Iterating through Dictionaries
9
Break statement
• Used to terminate the execution of the nearest enclosing loop .
• It is widely used with for and while loop
Example
I = 1
while I <= 10:
print(I, end=“ “)
if I==5:
break
I = I+1
Print (“Out from while loop”)
10
Continue statement
• The Continue statement is used to skip the rest of the code inside a
loop for the current iteration only. Loop does not terminate but
continues on with the next iteration.
Example
for val in "string":
if val == "i":
continue
print(val)
print("The end")
11
Range() function
12
The range() is an in-built function in Python. It returns a sequence
of numbers starting from zero and increment by 1 by default and
stops before the given number.
x = range(5)
for n in x:
print(n)
Example : range(5) will start from 0 and end at 4.
range(start, stop, step)
Range() function
13
Along with loops, range() is also used to iterate over the list types using
the len function and access the values through the index
Example
listType = ['US', 'UK', 'India', 'China']
for i in range(len(listType)):
print(listType[i])
Reverse Range
•We can give either positive or negative numbers for any of the
parameters in the range.
•This feature offers the opportunity to implement reverse loops.
•We can do this by passing a higher index as a start and a negative step
value.
for i in range(10, 5, -1):
print(i) #OutPut : 10, 9, 8, 7, 6
Range() function
14
Create List, Set and Tuple using Range
range() comes handy in many situations, rather than only using to write
loops.
For example, we create List, Set, and Tuple using range function instead
of using loops to avoid boilerplate code.
Example:
print(list(range(0, 10, 2)))
print(set(range(0, 10, 2)))
print(tuple(range(0, 10, 2)))
print(list(range(10, 0, -2)))
print(tuple(range(10, 0, -2)))
pass statement
•In Python programming, pass is a null statement.
•The difference between a comment and pass statement in Python is that,
while the interpreter ignores a comment entirely, pass is not ignored.
•However, nothing happens when pass is executed. It results into no
operation (NOP).
•Suppose we have a loop or a function that is not implemented yet, but we
want to implement it in the future. They cannot have an empty body. So, we
use the pass statement to construct a body that does nothing.
•Example
sequence = {‘p’, ‘a’, ‘s’, ‘s’}
for val in sequence:
pass
Lambda OR Anonymous function
They are not declared as normal function.
They do not required def keyword but they are declared with a lambda
keyword.
Lambda function feature added to python due to
Demand from LISP programmers.
Syntax: lambda argument1,argument2,….argumentN: expression
Example:
Sum = lambda x,y : x+y
Program:
Program that passes lambda function as an argument to a function
def func(f, n):
print(f(n))
Twice = lambda x:x *2
Thrice = lambda y:y*3
func(Twice, 5)
func(Thrice,6)
Output: 10
18
Functional programming decomposes a problem into set of functions.
1.filter( )
This function is responsible to construct a list from those elements of the list
for which a function returns True.
Syntax: filter (function, sequence)
Example:
def check(x):
if(x%2==0 or x%4==0):
return 1
evens = list(check, range(2,22))
print(evens)
O/P: [2,4,6,8…….16,18,20]
Functional Programming
2. map():
It applies a particular function to every element of a list.
Its syntax is similar to filter function
After apply the specified function on the sequence the map() function
return the modified list.
map(function, sequence)
Example:
def mul_2(x):
x*=2
return x
num_list = [1,2,3,4,5,6,7]
New_list = list(map(mul_2, num_list)
Print(New_list)
Functional Programming
2. reduce():
It returns a single value generated by calling the function on the first two
items of the sequence then on result and the next item, and so on.
Syntax: reduce(function, sequence)
Example:
import functools
def add(a,b):
return x,y
num_list = [1,2,3,4,5]
print(functools.reduce(add, num_list))
Functional Programming
List comprehension offers a shorter syntax when we want to create a new
list
Based on the values of an existing list.
Example
Fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”]
newlist = [ ]
for x in Fruits:
if “a” in x:
newlist.append(x)
Print(newlist)
List Comprehension
Strings
•A string is a sequence of characters.
•Computers do not deal with characters, they deal with numbers (binary).
Even though you may see characters on your screen, internally it is stored
and manipulated as a combination of 0’s and 1’s.
•How to create a string?
•Strings can be created by enclosing characters inside a single quote or
double quotes.
•Even triple quotes can be used in Python but generally used to represent
multiline strings and docstrings.
myString = ‘Hello’
print(myString) myString = "Hello"
print(myString) myString = ‘’’Hello’’’
print(myString)
How to access characters in a string?
myString = "Hello"
#print first Character
print(myString[0])
#print last character using negative indexing
print(myString[-1])
#slicing 2nd to 5th character
print(myString[2:5])
#print reverse of string
print(myString[::-1])
How to change or delete a string ?
•Strings are immutable.
•We cannot delete or remove characters from a string. But deleting the
string entirely is possible using the keyword del.
String Operations
•Concatenation
s1 = "Hello "
s2 = “KNMIET"
#concatenation of 2 strings
print(s1 + s2)
#repeat string n times
print(s1 * 3)
•Iterating Through String
count = 0
for l in "Hello World":
if l == "o":
count += 1
print(count, " letters found")
String Membership Test
•To check whether given character or string is present or not.
•For example-
print("l" in "Hello World")
print("or" in "Hello World")
•String Methods
•lower()
•join()
•split()
•upper()
Python Program to Check whether a String is
Palindrome or not ?
myStr = "Madam"
#convert entire string to either lower or upper
myStr = myStr.lower()
#reverse string
revStr = myStr[::-1]
#check if the string is equal to its reverse
if myStr == revStr:
print("Given String is palindrome")
else:
print("Given String is not palindrome")
Python Program to Sort Words in Alphabetic Order?
myStr = "python Program to Sort words in Alphabetic Order"
#breakdown the string into list of words
words = myStr.split()
#sort the list
words.sort()
#printing Sorted words
for word in words:
print(word)

More Related Content

PPT
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
PDF
Notes2
PPTX
Introduction to Python Part-1
PPTX
Python Session - 4
DOCX
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
PDF
Python_Module_2.pdf
PDF
Loops_in_Rv1.2b
PDF
Python revision tour i
PPT3-CONDITIONAL STATEMENT LOOPS DICTIONARY FUNCTIONS.ppt
Notes2
Introduction to Python Part-1
Python Session - 4
ISTA 130 Lab 21 Turtle ReviewHere are all of the turt.docx
Python_Module_2.pdf
Loops_in_Rv1.2b
Python revision tour i

Similar to ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt (20)

PPTX
Unit - 2 CAP.pptx
PPTX
My Presentation ITPdcjsdicjscisuchc.pptx
PPTX
UNIT – 3.pptx for first year engineering
PPTX
Improve Your Edge on Machine Learning - Day 1.pptx
PPTX
Python Revision Tour.pptx class 12 python notes
PPTX
My Presentation ITPsdhjccjh cjhj (1).pptx
PPTX
Chapter 2-Python and control flow statement.pptx
PPTX
Basic of Python- Hands on Session
PPTX
Python For Data Science.pptx
DOCX
This first assignment will focus on coding in Python, applying kno.docx
PDF
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
PDF
The swift programming language
PPT
Control structures pyhton
PPS
Programming in Arduino (Part 2)
PPTX
Python ppt_118.pptx
PDF
Anton Kasyanov, Introduction to Python, Lecture2
PPTX
Advanced VB: Review of the basics
PPTX
Advanced VB: Review of the basics
PPTX
Brixton Library Technology Initiative Week1 Recap
DOCX
An Introduction to Computer Science with Java, Python an.docx
Unit - 2 CAP.pptx
My Presentation ITPdcjsdicjscisuchc.pptx
UNIT – 3.pptx for first year engineering
Improve Your Edge on Machine Learning - Day 1.pptx
Python Revision Tour.pptx class 12 python notes
My Presentation ITPsdhjccjh cjhj (1).pptx
Chapter 2-Python and control flow statement.pptx
Basic of Python- Hands on Session
Python For Data Science.pptx
This first assignment will focus on coding in Python, applying kno.docx
The Swift Programming Language - Xcode6 for iOS App Development - AgileInfowa...
The swift programming language
Control structures pyhton
Programming in Arduino (Part 2)
Python ppt_118.pptx
Anton Kasyanov, Introduction to Python, Lecture2
Advanced VB: Review of the basics
Advanced VB: Review of the basics
Brixton Library Technology Initiative Week1 Recap
An Introduction to Computer Science with Java, Python an.docx
Ad

More from avishekpradhan24 (13)

PPTX
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
PPTX
Lab-V-N.pptxvfxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
PPTX
Halloween-themed Best in Costume Certificates.pptx
PPTX
what.pptxvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
PPTX
uva-201026072839.pptxvcvczcvzvcxbxcvbcxvbvcxbcx
PPTX
EduWehbhjbjnbbbbbbbbbhhhhjhjjbppt[1].pptx
PPTX
Website Design Consulting by Slidesgo.pptx
PPTX
Technology Consulting _ by Slidesgo.pptx
PPTX
SGMC_Data_Breach_Case_Study_with_Graphics.pptx
PDF
wepik-demystifying-data-structures-understanding-queues-20240417143621GPlM.pdf
PDF
Software vjhghjjkhjkkkghhjhEngineering.pdf
PPTX
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
PPTX
wepik-securing-networks-understanding-the-power-of-https-202402081449138j2r.pptx
python-fefedfasdgsgfahfdshdhunctions-190506123237.pptx
Lab-V-N.pptxvfxbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
Halloween-themed Best in Costume Certificates.pptx
what.pptxvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
uva-201026072839.pptxvcvczcvzvcxbxcvbcxvbvcxbcx
EduWehbhjbjnbbbbbbbbbhhhhjhjjbppt[1].pptx
Website Design Consulting by Slidesgo.pptx
Technology Consulting _ by Slidesgo.pptx
SGMC_Data_Breach_Case_Study_with_Graphics.pptx
wepik-demystifying-data-structures-understanding-queues-20240417143621GPlM.pdf
Software vjhghjjkhjkkkghhjhEngineering.pdf
wepik-mastering-function-in-c-a-comprehensive-guide-20231220121719HZHU.pptx
wepik-securing-networks-understanding-the-power-of-https-202402081449138j2r.pptx
Ad

Recently uploaded (20)

PPTX
HPE Aruba-master-icon-library_052722.pptx
PPT
Package Design Design Kit 20100009 PWM IC by Bee Technologies
PDF
Integrated-2D-and-3D-Animation-Bridging-Dimensions-for-Impactful-Storytelling...
DOCX
The story of the first moon landing.docx
PPTX
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
PDF
Trusted Executive Protection Services in Ontario — Discreet & Professional.pdf
PDF
BRANDBOOK-Presidential Award Scheme-Kenya-2023
PDF
Urban Design Final Project-Site Analysis
PDF
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
DOCX
actividad 20% informatica microsoft project
PDF
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
PPTX
Implications Existing phase plan and its feasibility.pptx
PPTX
6- Architecture design complete (1).pptx
PPTX
An introduction to AI in research and reference management
PPTX
12. Community Pharmacy and How to organize it
PDF
Wio LTE JP Version v1.3b- 4G, Cat.1, Espruino Compatible\202001935, PCBA;Wio ...
PPTX
areprosthodontics and orthodonticsa text.pptx
PDF
Quality Control Management for RMG, Level- 4, Certificate
PPTX
AD Bungalow Case studies Sem 2.pptxvwewev
PDF
High-frequency high-voltage transformer outline drawing
HPE Aruba-master-icon-library_052722.pptx
Package Design Design Kit 20100009 PWM IC by Bee Technologies
Integrated-2D-and-3D-Animation-Bridging-Dimensions-for-Impactful-Storytelling...
The story of the first moon landing.docx
BSCS lesson 3.pptxnbbjbb mnbkjbkbbkbbkjb
Trusted Executive Protection Services in Ontario — Discreet & Professional.pdf
BRANDBOOK-Presidential Award Scheme-Kenya-2023
Urban Design Final Project-Site Analysis
GREEN BUILDING MATERIALS FOR SUISTAINABLE ARCHITECTURE AND BUILDING STUDY
actividad 20% informatica microsoft project
Emailing DDDX-MBCaEiB.pdf DDD_Europe_2022_Intro_to_Context_Mapping_pdf-165590...
Implications Existing phase plan and its feasibility.pptx
6- Architecture design complete (1).pptx
An introduction to AI in research and reference management
12. Community Pharmacy and How to organize it
Wio LTE JP Version v1.3b- 4G, Cat.1, Espruino Compatible\202001935, PCBA;Wio ...
areprosthodontics and orthodonticsa text.pptx
Quality Control Management for RMG, Level- 4, Certificate
AD Bungalow Case studies Sem 2.pptxvwewev
High-frequency high-voltage transformer outline drawing

ppt3-conditionalstatementloopsdictionaryfunctions-240731050730-455ba0fa.ppt

  • 1. Rahul Kumar CS Deptt. KIET rahul.kumar@kiet.edu Conditional statement Bibek Kumar-Assistant Professor-CSE, KIET
  • 2. If, elif, else statement Bibek Kumar-Assistant Professor-CSE, KIET if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results. Verbally, we can imagine we are telling the computer: "Hey if this case happens, perform some action" We can then expand the idea further with elif and else statements, which allow us to tell the computer: "Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if none of the above cases happened, perform this action." If the condition "condition_1" is True, the statements of the block statement_block_1 will be executed. If not, condition_2 will be evaluated. If condition_2 evaluates to True, statement_block_2 will be executed, if condition_2 is False, the other conditions of the following elif conditions will be checked, and finally if none of them has been evaluated to True, the indented block below the else keyword will be executed.
  • 3. Bibek Kumar-Assistant Professor-CSE, KIET The if, elif and else Statements Examples Multiple Branches Note how the nested if statements are each checked until a True Boolean causes the nested code below it to run. We should also note that we can put in as many elif statements as we want before we close off with an else.
  • 4. While Bibek Kumar-Assistant Professor-CSE, KIET The while statement in Python is one of most general ways to perform iteration. A while statement will repeatedly execute a single statement or group of statements as long as the condition is true. The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met. Notice how many times the print statements occurred and how the while loop kept going until the True condition was met, which occurred once x==10. It's important to note that once this occurred the code stopped.
  • 5. While Loops We can also add else statement in the loop as shown When the loop completes, the else statement is read 5
  • 6. While Loops We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by: •break: Breaks out of the current closest enclosing loop. •continue: Goes to the top of the closest enclosing loop. •pass: Does nothing at all. Syntax: while test: code statement if test: break if test: continue else: break and continue statements can appear anywhere inside the loop’s body, but we will usually put them further nested in conjunction with an if statement to perform an action based on some condition. A word of caution however! It is possible to create an infinitely running loop with while statements. 6
  • 7. A for loop acts as an iterator in Python; it goes through items that are in a sequence or any other iterable item. Objects that we've learned about that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values. for item in object: statements to do stuff Example Let's print only the even numbers from that list! We could have also put an else statement in there 7 For loop
  • 8. Using the for Statement Another common idea during a for loop is keeping some sort of running tally during multiple loops We've used for loops with lists, how about with strings? Remember strings are a sequence so when we iterate through them we will be accessing each item in that string. Let's now look at how a for loop can be used with a tuple Tuples are very similar to lists, however, unlike lists they are immutable meaning they can not be changed. You would use tuples to present things that shouldn't be changed, such as days of the week, or dates on a calendar. The construction of a tuples use () with elements separated by commas. 8
  • 9. Using the for Statement Tuples have a special quality when it comes to for loops. If you are iterating through a sequence that contains tuples, the item can actually be the tuple itself, this is an example of tuple unpacking. During the for loop we will be unpacking the tuple inside of a sequence and we can access the individual items inside that tuple! Iterating through Dictionaries 9
  • 10. Break statement • Used to terminate the execution of the nearest enclosing loop . • It is widely used with for and while loop Example I = 1 while I <= 10: print(I, end=“ “) if I==5: break I = I+1 Print (“Out from while loop”) 10
  • 11. Continue statement • The Continue statement is used to skip the rest of the code inside a loop for the current iteration only. Loop does not terminate but continues on with the next iteration. Example for val in "string": if val == "i": continue print(val) print("The end") 11
  • 12. Range() function 12 The range() is an in-built function in Python. It returns a sequence of numbers starting from zero and increment by 1 by default and stops before the given number. x = range(5) for n in x: print(n) Example : range(5) will start from 0 and end at 4. range(start, stop, step)
  • 13. Range() function 13 Along with loops, range() is also used to iterate over the list types using the len function and access the values through the index Example listType = ['US', 'UK', 'India', 'China'] for i in range(len(listType)): print(listType[i]) Reverse Range •We can give either positive or negative numbers for any of the parameters in the range. •This feature offers the opportunity to implement reverse loops. •We can do this by passing a higher index as a start and a negative step value. for i in range(10, 5, -1): print(i) #OutPut : 10, 9, 8, 7, 6
  • 14. Range() function 14 Create List, Set and Tuple using Range range() comes handy in many situations, rather than only using to write loops. For example, we create List, Set, and Tuple using range function instead of using loops to avoid boilerplate code. Example: print(list(range(0, 10, 2))) print(set(range(0, 10, 2))) print(tuple(range(0, 10, 2))) print(list(range(10, 0, -2))) print(tuple(range(10, 0, -2)))
  • 15. pass statement •In Python programming, pass is a null statement. •The difference between a comment and pass statement in Python is that, while the interpreter ignores a comment entirely, pass is not ignored. •However, nothing happens when pass is executed. It results into no operation (NOP). •Suppose we have a loop or a function that is not implemented yet, but we want to implement it in the future. They cannot have an empty body. So, we use the pass statement to construct a body that does nothing. •Example sequence = {‘p’, ‘a’, ‘s’, ‘s’} for val in sequence: pass
  • 16. Lambda OR Anonymous function They are not declared as normal function. They do not required def keyword but they are declared with a lambda keyword. Lambda function feature added to python due to Demand from LISP programmers. Syntax: lambda argument1,argument2,….argumentN: expression Example: Sum = lambda x,y : x+y
  • 17. Program: Program that passes lambda function as an argument to a function def func(f, n): print(f(n)) Twice = lambda x:x *2 Thrice = lambda y:y*3 func(Twice, 5) func(Thrice,6) Output: 10 18
  • 18. Functional programming decomposes a problem into set of functions. 1.filter( ) This function is responsible to construct a list from those elements of the list for which a function returns True. Syntax: filter (function, sequence) Example: def check(x): if(x%2==0 or x%4==0): return 1 evens = list(check, range(2,22)) print(evens) O/P: [2,4,6,8…….16,18,20] Functional Programming
  • 19. 2. map(): It applies a particular function to every element of a list. Its syntax is similar to filter function After apply the specified function on the sequence the map() function return the modified list. map(function, sequence) Example: def mul_2(x): x*=2 return x num_list = [1,2,3,4,5,6,7] New_list = list(map(mul_2, num_list) Print(New_list) Functional Programming
  • 20. 2. reduce(): It returns a single value generated by calling the function on the first two items of the sequence then on result and the next item, and so on. Syntax: reduce(function, sequence) Example: import functools def add(a,b): return x,y num_list = [1,2,3,4,5] print(functools.reduce(add, num_list)) Functional Programming
  • 21. List comprehension offers a shorter syntax when we want to create a new list Based on the values of an existing list. Example Fruits = [“apple”, “banana”, “cherry”, “kiwi”, “mango”] newlist = [ ] for x in Fruits: if “a” in x: newlist.append(x) Print(newlist) List Comprehension
  • 22. Strings •A string is a sequence of characters. •Computers do not deal with characters, they deal with numbers (binary). Even though you may see characters on your screen, internally it is stored and manipulated as a combination of 0’s and 1’s. •How to create a string? •Strings can be created by enclosing characters inside a single quote or double quotes. •Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings. myString = ‘Hello’ print(myString) myString = "Hello" print(myString) myString = ‘’’Hello’’’ print(myString)
  • 23. How to access characters in a string? myString = "Hello" #print first Character print(myString[0]) #print last character using negative indexing print(myString[-1]) #slicing 2nd to 5th character print(myString[2:5]) #print reverse of string print(myString[::-1]) How to change or delete a string ? •Strings are immutable. •We cannot delete or remove characters from a string. But deleting the string entirely is possible using the keyword del.
  • 24. String Operations •Concatenation s1 = "Hello " s2 = “KNMIET" #concatenation of 2 strings print(s1 + s2) #repeat string n times print(s1 * 3) •Iterating Through String count = 0 for l in "Hello World": if l == "o": count += 1 print(count, " letters found")
  • 25. String Membership Test •To check whether given character or string is present or not. •For example- print("l" in "Hello World") print("or" in "Hello World") •String Methods •lower() •join() •split() •upper()
  • 26. Python Program to Check whether a String is Palindrome or not ? myStr = "Madam" #convert entire string to either lower or upper myStr = myStr.lower() #reverse string revStr = myStr[::-1] #check if the string is equal to its reverse if myStr == revStr: print("Given String is palindrome") else: print("Given String is not palindrome")
  • 27. Python Program to Sort Words in Alphabetic Order? myStr = "python Program to Sort words in Alphabetic Order" #breakdown the string into list of words words = myStr.split() #sort the list words.sort() #printing Sorted words for word in words: print(word)