0% found this document useful (0 votes)
16 views24 pages

Unit II Control Statements-Python

This document covers control statements in Python, including conditional branching with if statements and looping with while and for loops. It also discusses lists, tuples, and their operations, emphasizing the importance of indentation in Python syntax. Additionally, it explains the mutability of objects and provides examples of various string and list functions.

Uploaded by

sujanarose2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views24 pages

Unit II Control Statements-Python

This document covers control statements in Python, including conditional branching with if statements and looping with while and for loops. It also discusses lists, tuples, and their operations, emphasizing the importance of indentation in Python syntax. Additionally, it explains the mutability of objects and provides examples of various string and list functions.

Uploaded by

sujanarose2004
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT II CONTROL STATEMENTS 12 hrs

CONTROL STATEMENTS: Control Flow and Syntax - Indenting - if


Statement - statements
And expressions - string operations- Boolean Expressions -while Loop -
break and continue – for Loop. LISTS: List- list slices-list methods-list loop –
mutability – aliasing-cloning lists-list parameters. TUPLES: Tuple
assignment, tuple as return value-Sets– Dictionaries.

Lesson :11

CONTROL STATEMENTS

Python provides conditional branching with if statements and looping with while
and for …in statements. Python also has a conditional expression—this is a kind of
if statement that is Python’s answer to the ternary operator (?:) used in C-style
languages
Indenting
Indentation is a very important concept of Python because without
proper indenting the Pythoncode, you will end up seeing
IndentationError and the code will not get compiled.
In the above example,

 Statement (line 1), if condition (line 2), and statement (last


line) belongs to the same blockwhich means that after
statement 1, if condition will be executed. and suppose the
ifcondition becomes False then the Python will jump to the
last statement for execution.

 The nested if-else belongs to block 2 which means that if


nested if becomes False, thenPython will execute the
statements inside the else condition.

 Statements inside nested if-else belongs to block 3 and only one


statement will be executeddepending on the if-else condition.
Python indentation is a way of telling a Python interpreter that the
group of statements belongs to aparticular block of code. A block is a
combination of all these statements. Block can be regarded asthe
grouping of statements for a specific purpose. Most of the
programming languages like C, C++,Java use braces { } to define a
block of code. Python uses indentation to highlight the blocks of
[Link] is used for indentation in Python. All statements with
the same distance to the rightbelong to the same block of code. If a
block has to be more deeply nested, it is simply indentedfurther to the
right. You can understand it better by looking at the following lines of
code.
#Pythonprogram
showing#indenta
tion
site='gf
g'ifsite
=='gfg':
print('Loggingontogeeksforgeeks...'
)else:
print('retypetheURL.')
print('Allset!')

Output:
Loggingontogeeksforgeeks
...Allset!

Conditional Branching

the general syntax for Python’s conditional branch statement:

If statement

Syntax:
if condition:
# Statements to execute if
# condition is true

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

Python If Else Statement


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 if we want to do something
else if the condition is false, we can use the else statement with the if statement
Python to execute a block of code when the Python if condition is false.
Syntax of If Else in Python
if (condition):
# Executes this block if
# condition is true
else:
# Executes this block if
# condition is false

Example:
# python program to illustrate else if in Python 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")

Lesson :12
Python Nested If Statement
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
# if Block is end here
# if Block is end here
# python program to illustrate nested If statement
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 15")
Python Elif
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
Example:
# 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")

Lesson :13

Statement and Expression


Statements:
A statement is an instruction that the Python interpreter can execute.
We have normally two basicstatements, the assignment statement and
the print statement. Some other kinds of statements thatare if
statements, while statements, and for statements generally called as
control flows.

Examples:

An assignment statement creates new variables and gives them values:

>>> x=10
Expressions in Python

An expression is a combination of operators and operands that is interpreted to


produce some other value. In any programming language, an expression is
evaluated as per the precedence of its operators. So that if there is more than one
operator in an expression, their precedence decides which operation will be
performed first. We have many different types of expressions in Python

[Link] Expressions: These are the expressions that have constant values only.

# Constant Expressions

x = 15 + 1.3

print(x)

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric


values, operators, and sometimes parenthesis. The result of this type of expression
is also a numeric value. The operators used in these expressions are arithmetic
operators like addition, subtraction, etc.

x = 40
y = 12

add = x + y
sub = x - y
3Logical Expressions: These are kinds of expressions that result in
either True or False. It basically specifies one or more conditions.

P = (10 == 9)

Q = (7 > 5)

# Logical Expressions

R = P and Q

S = P or Q

T = not P

print(R)

print(S)

print(T)

Boolean and operator returns true if both operands return true.


>>> a=50
>>> b=25
>>>
a>40
and
b>40F
alse
>>>
a>100
and
b<50Fa
lse
>>>
a==0
and
b==0F
alse
>>> a>0 and b>0
True

Boolean or operator returns true if any one operand is true


>>> a=50
>>> b=25
>>>
a>40
or
b>40
True
>>> a>100 or b<50
True
>>>
a==0
or
b==0
False
>>
>
a>
0
or
b>
0T
rue
The not operator returns true if its operand is a false expression and returns
false if it is true.
>>> a=10
>>> a>10
False
>
>
>
no
t(
a>
10
)T
ru
e

Lesson :14

String operation
[Link]()

Converts the first character to upper case

txt = "hello, and welcome to my world."

x = [Link]()

print (x)
[Link]()

Converts string into lower case

txt = "Hello, And Welcome To My World!"

x = [Link]()

print(x)
[Link]()

Returns a centered string


txt = "banana"
x = [Link](20)
print(x)

4. lower()
Converts a string into lower case

txt = "Hello my FRIENDS"


x = [Link]()
print(x)

[Link]()

Converts a string into upper case

txt = "Hello my friends"


x = [Link]()
print(x)

[Link]()

Returns a string where a specified value is replaced with a specified value

txt = "I like bananas"


x = [Link]("bananas", "apples")
print(x)

[Link]()

Splits the string at the specified separator, and returns a list

txt = "welcome to the jungle"


x = [Link]()
print(x)

Lesson :15
A loop statement in Python:
Ingeneral,statementsareexecutedsequentially:Thefirststatementinafunc
tionisexecuted first, followed by the second, and so on. There may be
a situation when you needto execute a block of code several number
of times.
Programming languages provide various control structures that allow
for more complicatedexecution paths.
A loop statement allows us to execute a statement or group of
statements multiple times.

Pythonprogramminglanguageprovidesfollowingtypesofloopstohan
dleloopingrequirements.

Sr.N Loop Type &


o. Description
1 while loop

[Link]
sthecondition before executing the loop body.

2 for loop

Executesasequenceofstatementsmultipletimesandabbreviatesthecodethatma
nages the loop variable.
3 Nested loops
You can use one or more loop inside any another while, for or do..while
loop.

while loop

RepeatsastatementorgroupofstatementswhileagivenconditionisTR
[Link] before executing the loop body.
Syntax:
while condition :
body of the loop

Ex:
i=1
while i < 6:
print(i)
i += 1

Lesson :16

For loop
ThePythonforloop is an iterator-based forloop. It goes through the
elements in any ordered sequence list, i.e., string, lists, tuples, the
keys of dictionary and other iterables. In each iteration step, a loop
variable isset to a value. The forloop in Python is a bit different
from the forloop in any other programming language you have
gone through.
Syntax
for iterating_var in
sequence:statements(s)
If a sequence contains an expression list, it is evaluated first. Then,
the first item inthe sequence is assigned to the iterating variable
iterating_var. Next, the
[Link]
iterating_var,andthestatement(s) block is executed until the entire
sequence is exhausted.

Ex1 :

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

Ex 2:
for x inrange(6):
print(x)

Ex 3:
for x inrange(2, 30, 3):
print(x)

Lesson :17

Nested loop

A nested loop is a loop inside a loop.


The "inner loop" will be executed one time for each iteration of the "outer loop":
Ex:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)
break statement
Itterminatesthecurrentloopandresumesexecutionatthenextstatement,jus
tlikethetraditional break statement in C.
Themostcommonuseforbreakiswhensomeexternalconditionistriggered
requiringahasty exit from a loop. The break statement can be used in
both while and for loops.
Ifyouareusingnestedloops,thebreakstatementstopstheexecutionofthein
nermostloop and start executing the next line of code after the block.

Syntax
The syntax for a break statement in Python is as follows −
break
Ex:
#!/usr/bin/python

for letter in'Python':# First


Exampleif letter =='h':
break
print'Current Letter :', letter
continue statement
It returns the control to the beginning of the while loop.. The continue statement
rejects
alltheremainingstatementsinthecurrentiterationoftheloopandmovesthecontrolbackto
the top of the loop.
The continue statement can be used in both while and for loops.

Syntax
continue
Ex
#!/usr/bin/python

for letter in'Python':# First


Exampleif letter =='h':
continue
print'Current Letter :', letter
‘’/

Lesson :18
List
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the
other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.
Lists are created using square brackets:
List
* It is like array
* List is zero based Indexing
Syntax:
List variable=[value list]
Example:
lst=[1,2,3]
Forwarding index
Lst=[1,2,3]
Lst[0]=1
Lst[1]=2
Lst[2]=3
Backwarding index
Lst[-3]=1
Lst[-2]=2
Lst[-1]=3

Ex:
thislist = ["apple", "banana", "cherry"]
print(thislist)
Traversal
lst=[1,2,3]
Print (lst)
Or
for i in lst:
print(i)

Lesson :19
List functions
lst=[1,2,3]
len()
print(len(lst))
max()
print(max(lst))
min()
print(min(lst))
append()
[Link](4)
print(lst)
insert()
[Link](0,4)
print(lst) 4,1,2,3
extend()
[Link]([4,5,6])
[Link]([4,5,6])
1,2,3,[4,5,6] adding same location
remove
[Link](1)
sort
lst=[1,20,7]
[Link]()
1,7,20
descending order
[Link](reverse=True)
20,7,1

List in String
lst=list('united college')
print(lst)

Lesson :20
Mutability
An object is considered mutable if its state or value can be modified after it is
created. This means that you can alter its internal data or attributes without
creating a new object. Examples of mutable objects in Python include lists,
dictionaries, and sets.
TUPLES
 tupels value cant be change
 indexing from 0
Syntax:
tupename=(values)
Ex:
tup=(1,2,3)
tuples functions
[Link]()
len(tup)
Python - Tuples
A tuple is a collection of objects which ordered and immutable.
Tuples are sequences, justlike lists. The differences between tuples
and lists are, the tuples cannot be changed unlikelists and tuples use
parentheses, whereas lists use square brackets.
Creating a tuple is as simple as putting different comma-separated
values. Optionally youcan put these comma-separated values between
parentheses also. For example −
tup1 = ('physics', 'chemistry', 1997, 2000);
tup2 = (1, 2, 3, 4, 5 );
tup3 = "a", "b", "c", "d";
The empty tuple is written as two parentheses containing nothing −
tup1 = ();
To write a tuple containing a single value you have to include a
comma, even though thereis only one value −
tup1 = (50,);
Like string indices, tuple indices start at 0, and they can be sliced,
concatenated, and so on.
Accessing Values in Tuples
Toaccessvaluesintuple,usethesquarebracketsforslicingalongwiththeind
exorindicesto obtain value available at that index. For example −

When the above code is executed, it produces the following result −


tup1[0]:physics
tup2[1:5]:[2, 3, 4, 5]

Updating Tuples
Tuplesareimmutablewhichmeansyoucannotupdateorchangethevalueso
ftupleelements. You are able to take portions of existing tuples to
create new tuples as thefollowing example demonstrates −

When the above code is executed, it produces the following result −


(12, 34.56, 'abc', 'xyz')

Lesson :21

Delete Tuple Elements


[Link],ofcourse,noth
ingwrongwithputting together another tuple with the undesired
elements discarded.
To explicitly remove an entire tuple, just use the del statement. For example –

[Link],thisisbecause
after deltup tuple does not exist any more −
('physics',
'chemistry', 1997,
2000)After
deleting tup :
Traceback (most recent call last):
File "[Link]", line
9, in
<module>print
tup;
NameError: name 'tup' is not defined
Sets– Dictionaries
Set
Sets are used to store multiple items in a single variable.

Set is one of 4 built-in data types in Python used to store collections of data, the
other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

A set is a collection which is unordered, unchangeable*, and unindexed.


ets are written with curly brackets.

ExampleGet your own Python Server


Create a Set:

thisset = {"apple", "banana", "cherry"}


print(thisset)
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.

Unordered
Unordered means that the items in a set do not have a defined order.

Set items can appear in a different order every time you use them, and cannot be
referred to by index or key.

Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set
has been created.

Once a set is created, you cannot change its items, but you can remove items and
add new items.

Duplicates Not Allowed


Sets cannot have two items with the same value.
Example
Duplicate values will be ignored:

thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)

Lesson :22
Python - Dictionary
Each key is separated from its value by a colon (:), the items are
separated by commas, andthe whole thing is enclosed in curly braces.
An empty dictionary without any items iswritten with just two curly
braces, like this: {}.
Keys are unique within a dictionary while values may not be. The
values of a dictionary
canbeofanytype,butthekeysmustbeofanimmutabledatatypesuchasstrin
gs,numbers,or tuples.

Accessing Values in Dictionary


To access dictionary elements, you can use the familiar square
brackets along with the keyto obtain its value. Following is a simple
example −
When the above code is executed, it produces the following result −
dict['Nam
e']:Zaradi
ct['Age']:7
Ifweattempttoaccessadataitemwithakey,whichisnotpartofthedictionary
,wegetan error as follows −

When the above code is executed, it produces the following result −


dict['Alice']:
Traceback (most recent call last):
File "[Link]", line 4,
in
<module>print"dic
t['Alice']:",dict['Ali
ce'];
KeyError: 'Alice'
Updating Dictionary
Youcanupdateadictionarybyaddinganewentryorakey-
valuepair,modifyinganexisting entry, or deleting an existing entry as
shown below in the simple example −

When the above code is executed, it produces the following result −


dict['Age']:8
dict['School']:DPS School

Delete Dictionary Elements


Youcaneitherremoveindividualdictionaryelementsorcleartheentirecont
entsofadictionary. You can also delete entire dictionary in a single
operation.
Toexplicitlyremoveanentiredictionary,[Link]
ngisasimpleexample −

[Link]
afterdeldict dictionary does not exist any more −
dict['Age']:
Traceback (most recent call last):
File "[Link]", line
8, in
<module>print
"dict['Age']: ",
dict['Age'];
TypeError: 'type' object is unsubscriptable
Note − del() method is discussed in subsequent section.

Properties of Dictionary Keys

Dictionary values have no restrictions. They can be any arbitrary


Python object, eitherstandard objects or user-defined objects.
However, same is not true for the keys.
There are two important points to remember about dictionary keys −
[Link] than one entry per key not allowed. Which means no
duplicate key is
[Link],thelasta
[Link] −

When the above code is executed, it produces the following result −


dict['Name']:Manni
[Link],numbersortup
lesasdictionary keys but something like ['key'] is not allowed.
Following is a simple example −
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "[Link]", line
3, in
<module>dict={['
Name']:'Zara','Age
':7};
TypeError: unhashable type: 'list'

Dictionary values have no restrictions. They can be any arbitrary Python object,
eitherstandard objects or user-defined objects. However, same is not true for the
keys.
There are two important points to remember about dictionary keys −
[Link] than one entry per key not allowed. Which means no
duplicate key is
[Link],thelasta
[Link] −

When the above code is executed, it produces the following result −


dict['Name']:Manni
[Link],numbersortup
lesasdictionary keys but something like ['key'] is not allowed.
Following is a simple example −
When the above code is executed, it produces the following result −
Traceback (most recent call last):
File "[Link]", line
3, in
<module>dict={['
Name']:'Zara','Age
':7};

You might also like