0% found this document useful (0 votes)
13 views12 pages

Pp Unit-2 Material

Uploaded by

Dwipendu Kundu
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)
13 views12 pages

Pp Unit-2 Material

Uploaded by

Dwipendu Kundu
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/ 12

Python Programming

UNIT-2
Control Statement:
Decision Making Statements
In Python, the selection statements are also known as decision making statements or branching
statements. The selection statements are used to select a part of the program to be executed based on
a condition. Python provides the following selection statements.

Selective statements:

Simple If statement:

Syntax:
if expression:
Statement(s)

Flow chart:

Example:
age=int(input("enter your age"))
if age>=18:
print("you are eligible to vote")

If- else statement:


Syntax:
if expression:
Statement(s)
else:
Statement(s)

Example:
age=int(input("enter your age"))
if age>=18:
print("you are eligible to vote")
else:
print("you are not eligible to vote")

Flow chart:

Nested if statement:

Syntax:

if expression1:
if expression2:
Statement(s)
else:
Statement(s)
elif expression3:
Statement(s)
else:
Statement(s)
Flow chart:
Example:
a=int(input("enter a"))
b=int(input("enter b"))
c=int(input("enter c"))
if a>b:
if a>c:
print(a)
else:
print(c)
elif b>c:
print(b)
else:
print(c)

Multiple-if statement:

Syntax:

if expression1:
Statement(s)
elif expression2:
Statement(s)
elif expression3:
Statement(s)
elif expression4:
Statement(s)
:
:
:
:
elif expression N:
Statement(s)
else
Statement(s)
Example:

a=int(input("enter any number"))


if a>0:
print("positive")
elif a<0:
print("negetive")
else:
print("neutral")
Looping Statements:

In Python, the iterative statements are also known as looping statements or repetitive
statements. The iterative statements are used to execute a part of the program repeatedly as long as a
given condition is True. Python provides the following iterative statements.

1. while statement
2. for statement

while statement

1. In Python, the while statement is used to execute a set of statements repeatedly.


2. In Python, the while statement is also known as entry control loop statement because in the case
of the while statement, first, the given condition is verified then the execution of statements is
determined based on the condition result.

The general syntax of while statement in Python is as follows.

Syntax:

while condition:
Statement_1
Statement_2
Statement_3
...

The execution flow of while statement is as shown in the following figure.

When we define a while statement, the block of statements must be specified using indentation
only. The indentation is a series of white-spaces. Here, the number of white-spaces may variable, but all
statements must use the identical number of white-spaces. Let's look at the following example Python
code.
Example:

count = int(input('How many times you want to say "Hello": '))


i=1
while i <= count:
print('Hello')
i += 1
print('Done')

while statement with 'else' clause in Python

In Python, the else clause can be used with a while statement. The else block is gets executed
whenever the condition of the while statement is evaluated to false. But, if the while loop is terminated
with break statement then else doesn't execute.

Example:

count = int(input('How many times you want to say "Hello": '))


i=1
while i <= count:
if count > 10:
print('I can’t say more than 10 times!')
break
print('Hello')
i += 1
else:
print('This is else block of while!!!')
print('Done')

for statement in Python

In Python, the for statement is used to iterate through a sequence like a list, a tuple, a set, a
dictionary, or a string. The for statement is used to repeat the execution of a set of statements for every
element of a sequence.

The general syntax of for statement in Python is as follows.

Syntax:
for <variable> in <sequence>:
Statement_1
Statement_2
Statement_3
...

In the above syntax, the variable is stored with each element from the sequence for every iteration.
Examples:

Example: Python code to illustrate for statement with List


my_list = [1, 2, 3, 4, 5]
for value in my_list:
print(value)
print('done!')

Example: Python code to illustrate for statement with Tuple


my_tuple = (1, 2, 3, 4, 5)
for value in my_tuple:
print(value)
print('done!')

Example: Python code to illustrate for statement with Set


my_set = {1, 2, 3, 4, 5}
for value in my_set:
print(value)
print('done!')

Example: Python code to illustrate for statement with Dictionary


my_dictionary = {1:'Rama', 2:'Seetha', 3:'Heyaansh', 4:'Gouthami', 5:'Raja'}
for key, value in my_dictionary.items():
print(f'{key} --> {value}')
print('done!')

Example: Python code to illustrate for statement with String


for item in 'Python':
print(item)
print('done!')

Example: Python code to illustrate for statement with Range function


for value in range(1, 6):
print(value)
print('done!')

for statement with 'else' clause in Python:


In Python, the else clause can be used with a for a statement. The else block is gets executed
whenever the for statement is does not terminated with a break statement. But, if the for loop is
terminated with break statement then else block doesn't execute.
Example: # Here, else block is gets executed because break statement does not executed
for item in 'Python':
if item == 'x':
break
print(item)
else:
print('else block says for is successfully completed!')
print('done!!')

Example: # Here, else block does not gets executed because break statement terminates the loop.
for item in 'Python':
if item == 'y':
break
print(item)
else:
print('else block says for is successfully completed!')
print('done!!')

String:
String is a sequence of characters enclosed by either single or double or triple quotation marks.
Example:
Single quote: ‘Hai’
Double quote: “Hello, hay ACET”
Triple quote: “’ My name is Aditya.
I am studying in ACET.
I live in Rajahmundry”’
Representation of a string:
name=’Aditya’

0 A
name[2] = i
1 d
name[5]=a
2 i
name[7]=out of range error
3 t
4 y
5 a

Whenever we created a string, it is treated as object of “str” class (string)


String Slicing/accessing character:
Subsets of strings can be taken using the slice operator ([ ] and [:] ) with indexes starting
at 0 in the beginning of the string and working their way from -1 at the end.
Example:
>>>message='hai how are you'
>>>print(message[4])
h
>>>print(message[4:9])
how ar
>>>print(message[:5])
hai ho
>>>print(message[2:])
I how are you

string concatenation operator: ( plus (+) )


The plus (+) sign is the string concatenation operator
Example:
>>> s="india"
>>> s1="I Love"
>>> s2=" India"
>>> s1+s2
'I Love India'
string repetition operator ( asterisk (*) )
The asterisk (*) sign is the string repetition operator
Example:
>>> s="India "
>>> s*7
'India India India India India India India '
Built-in String Methods:

S.No Method Name Description Example

>>> s="aditya"
Capitalizes first letter of
1 capitalize() >>> s.capitalize()
string.
'Aditya'

Returns a space-padded string >>> s.center(20)


with the original string ' aditya '
2 center(width, fillchar)
centered to a total of width >>> s.center(20,'*')
columns. '*******aditya*******'

Counts how many times str


>>> s.count('a')
occurs in string or in a
2
3 count(str, beg=0,end=len(string)) substring of string if starting
>>> s.count('a',0,3)
index beg and ending index
1
end are given.

# unicode string
string = 'pythön!'
Returns encoded string
# print string
version of string; on
print('The string is:', string)
encode(encoding='UTF- error,default is to raise a
5 # default encoding to utf-8
8',errors='strict') Value Error unless errors is
string_utf = string.encode()
given with 'ignore' or
# print result
'replace'.(Data encryption)
print('The encoded version is:',
string_utf)

Determines if string or a
>>> s="aditya"
substring of string (if starting
>>> s.endswith('d')
endswith(suffix, index beg and ending index
6 False
beg=0,end=len(string)) end are given) ends with
>>> s.endswith('a')
suffix; returns true if so and
True
false otherwise.
Determine if str occurs in
string or in a substring of >>> s.find('a')
string if starting index beg and 0
7 find(str, beg=0end=len(string))
ending index end are given >>> s.find('z')
returns index if found and -1 -1
otherwise.

>>> s.index('a')
0
Same as find(), but raises an
8 index(str, beg=0,end=len(string)) >>> s.index('z')
exception if str not found.
ValueError: substring not
found
>>> s="aditya"
Returns true if string has at >>> s.isalpha()
least 1 character and all True
10 isalpha()
characters are alphabetic and >>> s="aditya@123"
false otherwise. >>> s.isalpha()
False

>>> s="12345"
>>> s.isdigit()
Returns true if string contains
True
11 isdigit() only digits and false
>>> s="aditya@123"
otherwise.
>>> s.isdigit()
False

>>> s="aditya"
Returns true if string has at >>> s.islower()
least 1 cased character and all True
12 islower()
cased characters are in >>> s="Aditya"
lowercase and false otherwise >>> s.islower()
False

>>> s="1234"
>>> s.isnumeric()
Returns true if a unicode
True
13 isnumeric() string contains only numeric
>>> s="aditya"
characters and false otherwise.
>>> s.isnumeric()
False

>>> s=" "


>>> s.isspace()
Returns true if string contains
True
14 isspace() only whitespace characters
>>> s="@"
and false otherwise.
>>> s.isspace()
False

>>> s="aditya"
>>> s.istitle()
Returns true if string is
False
15 istitle() properly "titlecased" and false
>>> s="Aditya"
otherwise.
>>> s.istitle()
True

>>> s="ADITYA"
Returns true if string has at >>> s.isupper()
least one cased character and True
16 isupper()
all cased characters are in >>> s="Aditya"
uppercase and false otherwise. >>> s.isupper()
False
>>> l=['I','Love','India']
Merges (concatenates) the
>>> " ".join(l)
string representations of
17 join(seq) 'I Love India'
elements in sequence seq into
>>> "-".join(l)
a string, with separator string.
'I-Love-India'

>>> s="aditya"
Returns the length of the
18 len(string) >>> len(s)
string.
6

>>> s.ljust(20)
'India '
>>> s.ljust(20,'*')
string left-justified to a total 'India***************'
of width columns. >>> s.rjust(20)
ljust(width[, fillchar])
string right-justified to a total ' India'
19 rjust(width[, fillchar])
of width columns. >>> s.rjust(20,'*')
center(width[, fillchar])
string center-justified to a '***************India'
total of width columns. >>> s.center(20)
' India '
>>> s.center(20,'*')
'*******India********'

>>> s="Aditya"
>>> s.lower()
Converts all uppercase letters 'aditya'
20 lower()
in string to lowercase. >>> s="ADITYA"
>>> s.lower()
'aditya'

>>>s="India"
Returns the max alphabetical
22 max(str) >>> max(s)
character from the string str.
'n'

>>>s="India"
Returns min alphabetical
23 min(str) >>> min(s)
character from the string str.
'I'

Replaces all occurrences of


>>> s="i love youtube"
old in string with new or at
>>>
24 replace(old, new [, max]) most max occurrences if max
s.replace("youtube","mom")
given.or at most max
'i love mom'
occurrences if max given.

Determines if string or a
>>> s='I love india'
substring of string (if starting
>>> s.startswith('I')
index beg and ending index
25 startswith(str,beg=0,end=len(string)) True
end are given) starts with
>>> s.startswith('l',2,5)
substring str; returns true if so
True
and false otherwise.
>>> s=" I love india "
>>> s
Performs both lstrip() and
26 strip([chars]) ' I love india '
rstrip() on string.
>>> s.strip()
'I love india'

>>> s="i am a good student"


Inverts case for all letters in
27 swapcase() >>> s.swapcase()
string.
'I AM A GOOD STUDENT'

Returns "titlecased" version of


>>> s="i am a good student"
string, that is, all words begin
28 title() >>> s.title()
with uppercase and the rest
'I Am A Good Student'
are lowercase.

>>> s="aditya"
Converts lowercase letters in
29 upper() >>> s.upper()
string to uppercase.
'ADITYA'

You might also like