0% found this document useful (0 votes)
7 views49 pages

Chapter 9 - 3

The document discusses Python conditional statements and control flow including if, else, elif statements and nested if statements. It also covers string manipulation in Python including concatenating, selecting, and modifying strings. Various string methods like split, replace, count, and removing whitespace are demonstrated with examples.

Uploaded by

Pratik Kanjilal
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)
7 views49 pages

Chapter 9 - 3

The document discusses Python conditional statements and control flow including if, else, elif statements and nested if statements. It also covers string manipulation in Python including concatenating, selecting, and modifying strings. Various string methods like split, replace, count, and removing whitespace are demonstrated with examples.

Uploaded by

Pratik Kanjilal
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/ 49

Chapter 9

Introduction to Python
Declaration
 These slides are made for UIT, BU students only. I am not
holding any copy write of it as I had collected these study
materials from different books and websites etc. I have not
mentioned those to avoid complexity.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.2


Conditional and control statement
 There comes situations in real life when we need to make some
decisions and based on these decisions, we decide what should
we do next. Similar situations arise in programming also where
we need to make some decisions and based on these decisions
we will execute the next block of code. Decision-making
statements in programming languages decide the direction of the
flow of program execution.
 In Python, if-else elif statement is used for decision making.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.3


if statement
 if statement is the most simple decision-making statement. It is
used to decide whether a certain statement or block of
statements will be executed or not i.e. if a certain condition is
true then a block of statement is executed otherwise not.
 Syntax:
if condition:
# Statements to execute if
# condition is true
 Here, the condition after evaluation will be either true or false. if
the statement accepts Boolean values – if the value is true then it
will execute the block of statements below it otherwise not.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.4


if statement
 Flowchart of Python if statement

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.5


if statement
# python program to illustrate If statement
i = 10
if (i > 15):
print("10 is less than 15")
print("I am Not in if")

Output:
I am Not in if

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.6


if-else
 The if statement alone tells us that if a condition is true it will
execute a block of statements and if the condition is false it
won‟t. But what if we want to do something else if the condition is
false. Here comes the else statement. We can use
the else statement with if statement to execute a block of code
when the condition is false.
 Syntax:
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.7


if-else
 FlowChart of Python if-else statement

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.8


if-else
# python program to illustrate If else statement
#!/usr/bin/python

i = 20
if (i < 15):
print("i is smaller than 15")
print("i'm in if Block")
else:
print("i is greater than 15")
print("i'm in else Block")
print("i'm not in if and not in else Block")

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.9


if-else
 Output:
i is greater than 15
i'm in else Block
i'm not in if and not in else Block

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.10


nested-if
 A nested if is an if statement that is the target of another if
statement. Nested if statements mean an if statement inside
another if statement. Yes, Python allows us to nest if statements
within if statements. i.e, we can place an if statement inside
another if statement.
 Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# inner if Block is end here
# outer if Block is end here

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.11


nested-if
 Flowchart of Python Nested if Statement

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.12


nested-if
# python program to illustrate nested If statement
#!/usr/bin/python
i = 10
if (i == 10):
# First if statement
if (i < 15):
print("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print("i is smaller than 12 too")
else:
print("i is greater than
8/16/2023 3:35 PM 15") Dutta, UIT, BU
Dr. Dipankar 1.13
nested-if
 Output:
i is smaller than 15
i is smaller than 12 too

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.14


if-elif-else ladder
 Here, a user can decide among multiple options. The if
statements are executed from the top down. As soon as one of
the conditions controlling the if is true, the statement associated
with that if is executed, and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will
be executed.
 Syntax:
if (condition):
statement
elif (condition):
statement
..
else:
statement

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.15


if-elif-else ladder
 FlowChart of Python if else elif statements

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.16


if-elif-else ladder
# Python program to illustrate if-elif-else ladder
#!/usr/bin/python

i = 20
if (i == 10):
print("i is 10")
elif (i == 15):
print("i is 15")
elif (i == 20):
print("i is 20")
else:
print("i is not present")

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.17


if-elif-else ladder
 Output:
i is 20

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.18


String manipulation
 The text type is one of the most common types out there and is
often called string or, in Python, just str.
my_city = "New York"
print(type(my_city))
#Single quotes have exactly
#the same use as double quotes
my_city = 'New York'
print(type(my_city))
#Setting the variable type explicitly
my_city = str("New York")
print(type(my_city))

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.19


String manipulation
 Output:
<class 'str'>
<class 'str'>
<class 'str'>

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.20


Concatenating Strings
word1 = 'New '
word2 = 'York'
print(word1 + word2)

Output:
New York

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.21


Selecting a character
 To select a char, use [] and specify the position of the char.
 Position 0 refers to the first position.
>>> word = "Rio de Janeiro“
>>> char=word[0]
>>> print(char)
Output:
R

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.22


Get the Size of a String
 The len() function returns the length of a string.
>>> len('Rio')
3
>>> len('Rio de Janeiro')
14

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.23


Replace Part of a String
 The replace() method replaces a part of the string with another.
>>> 'Rio de Janeiro'.replace('Rio', 'Mar')
'Mar de Janeiro'

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.24


Count
 Specify what to count as an argument.
 In this case, we are counting how many spaces exist in "Rio de
Janeiro", which is 2.
>>> word = "Rio de Janeiro"
>>> print(word.count(' '))

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.25


Repeat a String
 You can use the * symbol to repeat a string.
 Here we are multiplying the word "Tokyo" by 3.
>>> words = "Tokyo" * 3
>>> print(words)
TokyoTokyoTokyo

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.26


Split a String
 Example 1: use whitespaces as delimiters
my_phrase = "let's go to the town"
my_words = my_phrase.split(" ") # my_words is a list
for word in my_words:
print(word)
output:
let's
go
to
the
town

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.27


Split a String
print(my_words)
output:
["let's", 'go', 'to', 'the', 'beach']

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.28


Split a String
 Example 2: pass different arguments as delimiters
my_csv = "mary;32;australia;[email protected]"
my_data = my_csv.split(";")
for data in my_data:
print(data)
output:
mary
32
australia
[email protected]

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.29


Split a String
print(my_data[3])
output:
[email protected]

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.30


Remove All White Spaces
 The best solution is to use a regular expression.
 You need to import the re module that provides regular
expression operations.
 Notice that the \s represents not only space ' ', but also form
feed \f, line feed \n, carriage return \r, tab \t, and vertical tab \v.
 In summary, \s = [ \f\n\r\t\v].
 The + symbol is called a quantifier and is read as 'one or more'.
This means that it will consider, in this case, one or more white
spaces since it is positioned right after the \s.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.31


Remove All White Spaces
import re
phrase = ' Do or do not there is no try '
phrase_no_space = re.sub(r'\s+', '', phrase)
print(phrase)
# Do or do not there is no try

print(phrase_no_space)
#Doordonotthereisnotry

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.32


Handling Multiline Strings
 Triple Quotes
 To handle multiline strings in Python you use triple quotes, either
single or double.
long_text = """This is a multiline,
a long string with lots of text,
I'm wrapping it in triple quotes to make it work."""
print(long_text)
Output:
This is a multiline,
a long string with lots of text,
I'm wrapping it in triple quotes to make it work.
 In place of “”” we can use „‟‟. We will get same result.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.33


Handling Multiline Strings
 Parentheses
long_text = ("This is a multiline, "
"a long string with lots of text "
"I'm wrapping it in brackets to make it work.")
print(long_text)

#This is a multiline, a long string with lots of text I'm wrapping it in


triple quotes to make it work.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.34


Handling Multiline Strings
 As you can see, the result is not the same. To achieve new lines
I have to add \n, like this:
long_text = ("This is a multiline, \n\n"
"a long string with lots of text \n\n"
"I'm wrapping it in brackets to make it work.")
print(long_text)
Output:
#This is a multiline,
#
#a long string with lots of text
#
#I'm wrapping it in triple quotes to make it work.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.35


lstrip()
 lstrip(): To Remove Spaces and Chars from the Beginning of
a String
regular_text = " This is a regular text."
no_space_begin_text = regular_text.lstrip()
print(regular_text)
#' This is a regular text.'
print(no_space_begin_text)
#'This is a regular text.'

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.36


Remove Chars
regular_text = "$@G#This is a regular text."
clean_begin_text = regular_text.lstrip("#$@G")
print(regular_text)
#$@G#This is a regular text.

print(clean_begin_text)
#This is a regular text.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.37


Remove Chars
 rstrip(): To Remove Spaces and Chars from the End of a
String
regular_text = "This is a regular text. "
no_space_end_text = regular_text.rstrip()
print(regular_text)
#'This is a regular text. '
print(no_space_end_text)
#'This is a regular text.'

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.38


Remove Chars
regular_text = "This is a regular text.$@G#"
clean_end_text = regular_text.rstrip("#$@G")
print(regular_text)
#This is a regular text.$@G#
print(clean_end_text)
#This is a regular text.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.39


Remove Chars
 strip(): To Remove Spaces and Chars from the Beginning
and End of a String
regular_text = " This is a regular text. "
no_space_text = regular_text.strip()
print(regular_text)
#' This is a regular text. '
print(no_space_text)
#'This is a regular text.'

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.40


To Lowercase
regular_text = "This is a Regular TEXT."
lower_case_text = regular_text.lower()
print(regular_text)
#This is a Regular TEXT.
print(lower_case_text)
#this is a regular text.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.41


To Uppercase
regular_text = "This is a regular text."
upper_case_text = regular_text.upper()
print(regular_text)
#This is a regular text.
print(upper_case_text)
#THIS IS A REGULAR TEXT.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.42


Title Case
regular_text = "This is a regular text.“
title_case_text = regular_text.title()
print(regular_text)
#This is a regular text.
print(title_case_text)
#This Is A Regular Text.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.43


Swap Case
regular_text = "This IS a reguLar text."
swapped_case_text = regular_text.swapcase()
print(regular_text)
#This IS a reguLar text.
print(swapped_case_text)
#tHIS is A REGUlAR TEXT.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.44


Empty String or not
my_string = ''
if not my_string:
print("My string is empty!!!")

my_string = 'amazon, microsoft'


if my_string:
print("My string is NOT empty!!!")

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.45


Right-justify
word = „town'
number_spaces = 32
word_justified = word.rjust(number_spaces)
print(word)
#'town'
print(word_justified)
#„ town„
 Notice the spaces in the second string. The word „town' has 4
characters, which gives us 28 spaces to fill with empty space.

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.46


Right-justify
 The rjust() also accepts a specific char as a parameter to fill the
remaining space.
word = „town'
number_chars = 32
char = '$'
word_justified = word.rjust(number_chars, char)
print(word)
#town
print(word_justified)
#$$$$$$$$$$$$$$$$$$$$$$$$$$$$town

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.47


Left-justify
word = „town'
number_spaces = 32
word_justified = word.ljust(number_spaces)
print(word)
#„town'
print(word_justified)
#„town „

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.48


Left-justify
word = „town'
number_chars = 32 char = '$'
word_justified = word.ljust(number_chars, char)
print(word)
# town
print(word_justified)
# town$$$$$$$$$$$$$$$$$$$$$$$$$$$$

8/16/2023 3:35 PM Dr. Dipankar Dutta, UIT, BU 1.49

You might also like