SlideShare a Scribd company logo
1
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
2
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Booleans & Comparisons
In Python, there are two Boolean values: True and False. They can be created
by comparing values, for instances by using the equal operator ==.
Another comparison operator, the not equal operator (!=), evaluates to True if
the items being compares aren’t equal, and False if they are.
Compares both Numbers as well as Strings.
Python also has operators that determine whether the given number (integer
or float) is greater than or smaller than another. These are < and >
respectively.
Also we have, >= Greater than or Equal & <= Smaller than or Equal. Except
they return True when comparing equal numbers.
>>> value = True
>>> value
True
>>> 5 == 15
False
>>> "Hello" == "Hello"
True
>>> "Hi" == "hi"
False
>>> 1 != 1
False
>>> "cat" != "mat"
True
3
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Greater than and smaller than operators are also used to compare Strings
lexicographically.
>>> 9 > 4
True
>>> 8 < 8
False
>>> 4 <= 7
True
>>> 8 >= 8.0
True
4
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
if Statements
You can use if statements to run code if a certain condition holds.
If an expression evaluates to True, some statements are carried out.
Otherwise, they aren’t carried out.
Python uses indentation (white space at the beginning of a line) to delimit
blocks of code. Other languages, such as C, use curly braces to accomplish this,
but in Python indentation is mandatory; programs won’t work without it.
Notice the colon at the end of the expression in the if statement.
As the program contains multiple lines of code, you should create it as a
separate file and run it.
To perform more complex checks, if statements can be nested, one inside the
other.
Where inner if statement will be a part of outer if statement. This is used to
see whether multiple conditions are satisfied.
Output:
if expression:
statements
no = 24
if no > 18:
print("Greater than 18")
if no <= 50:
print("Between 18 & 50")
Greater than 18
Between 18 & 50
5
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
else Statements
An else statement follows an if statement & contains code that is called when
the if statement evaluates to False.
Output:
You can chain if and else statements to determine which option in a series of
possibilities is true.
X = 4
if x == 8:
print(“Yes”)
else:
print(“No”)
>>>
No
>>>
6
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
elif Statements
The elif (short of else if) statement is a shortcut to use when chaining if and
else statements. A series of if elif statements can have a final else block, which
is called if none of the if or elif expression is True.
Output:
num = 24
if num == 5:
print("Number is 5")
elif num == 11:
print("Number is 11")
elif num == 24:
print("Number is 24")
else:
print("Number isn't 5,11 or 24")
>>>
Number is 24
>>>
7
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Boolean Logic
Python’s Boolean operators are and, or and not.
The and operator takes two arguments, and evaluates as True if, and only if,
both of its arguments are True. Otherwise, it evaluates to False.
Python uses words for its Boolean operators, whereas most other languages
use symbols such as &&, || an !.
Similarly, Boolean or operator takes two arguments. It evaluates to True if
either (or both) of its arguments are True, and False if both arguments are
False.
The result of not True is False, and not False goes to True.
>>> 1 == 1 and 2 == 2
True
>>> 1 == 1 and 2 == 3
False
>>> 1 != 1 and 2 == 2
False
>>> 4 < 2 and 2 > 6
False
>>> not 1 == 1
False
>>> not 7 > 9
True
8
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Operator Precedence
Operator Precedence is a very important concept in programming. It is an
extension of the mathematical idea of order of operation.
(multiplication being performed before addition etc.) to include other
operators, such as those in Boolean logic.
The below code shows that == has a higher precedence than or.
>>> False == False or True
True
>>> False == (False or True)
False
>>> (False == False) or True
True
9
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
List of Python’s operators, from highest precedence to lowest.
** Exponentiation (raise to the power)
~ + - Complement, unary plus and minus
(method names for the last two are +@ and -@)
* / % // Multiply, divide, modulo and floor division
+ - Addition and Subtraction
>> << Right and Left bitwise shift
& Bitwise ‘AND’
^ | Bitwise exclusive ‘OR’ and regular ‘OR’
<= == => Comparison operators
< > == != Equality Operators
= %= /= //= -= += *= **= Assignment Operators
is is not Identity operators
in not in Membership Operators
not or and Logical operators
Operator | Description
10
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
while Loop
An if statement is run once if its condition evaluates to True, and never if it
evaluates to False.
A while statement is similar, except that it can be run more than once. The
statements inside it are repeatedly executed, as long as the condition holds.
Once it evaluates to False, the next section of code is executed.
Program:
Output:
The infinite loop is a special kind of while loop, it never stops running. Its
condition always remains True.
This program would indefinitely print “In the loop”.
i = 1
while i <= 5:
print(i)
i+=1
print("Finished !")
1
2
3
4
5
Finished !
while 1 == 1:
print(“In the loop”)
11
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
You can stop the program’s execution by using the Ctrl-C shortcut or by closing
the program.
 break
To end a while loop prematurely, the break statement can be used.
When encountered inside a loop, the break statement causes the loop to finish
immediately.
Program:
Output:
i = 0
while 1 == 1:
print(i)
i+=1
if i >= 5:
print("Breaking")
break
print("Finished")
0
1
2
3
4
Breaking
Finished
12
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
 Continue
Another statement that can be used within loops is continue.
Unlike break, continue jumps back to the top of the loop, rather than stopping
it.
Program:
Output:
i=0
while True:
i+=1
if i == 2:
print("Skipping 2")
continue
if i == 5:
print("Breaking")
break
print(i)
print("Finished")
1
Skipping 2
3
4
Breaking
Finished
13
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Lists:
Lists are another type of object in Python. They are used to store an indexed
list of items.
A list is created using square brackets with commas separating items.
The certain item in the list can be accessed by using its index in square
brackets.
Program:
Output:
The first list item’s index is 0, rather than 1, as might be expected.
An empty list can be created with an empty pair of square brackets.
It is perfectly valid to write comma after last item of the list, and it is
encouraged in some cases.
words = ["I","Love","Python"]
print(words[0])
print(words[1])
print(words[2])
I
Love
Python
empty_list = []
14
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Typically, a list will contain items of a single item type, but it is also possible to
include several different types.
Lists can also be nested within other lists.
Program:
Output:
Lists of lists are often used to represent 2D grids, as Python lacks the
multidimensional arrays that would be used for this in other languages.
number = 33
things = ["String",0,[11,22,number],3.14]
print(things[0])
print(things[1])
print(things[2])
print(things[2][2])
String
0
[11, 22, 33]
33
15
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Indexing out of the bounds of possible list values causes an IndexError.
Some types, such as strings, can be indexed like lists. Indexing strings behaves
as though you are indexing a list containing each character in the string.
For other types, such as integers, indexing them isn’t possible, and it causes a
TypeError.
Program:
Output:
Output:
str = “Hello World!”
print(str[6])
>>>
W
>>>
16
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
List Operations
The items at a certain index in a list can be reassigned.
Example:
Output:
Lists can be added and multiplied in the same way as strings.
Program:
Output:
Lists and strings are similar in many ways – strings can be thought of as lists of
characters that can’t be changed.
>>>
[24,24,55,24,24]
>>>
nums = [24,24,24,24,24]
nums[2] = 55
print(nums)
nums = [1,2,3]
print(nums + [4,5,6])
print(nums *3)
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
17
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
To check if an item is in a list, the in operator can be used. It returns True if the
item occurs one or more times in the list, and False if it doesn’t.
Program:
Output:
The in operator is also used to determine whether or not a string is a
substring of another string.
words = ["Donut","Eclair","Froyo","Gingerbread"]
print("Donut" in words)
print("Froyo" in words)
print("Lolipop" in words)
>>>
True
True
False
>>>
18
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
To check if an item is not in a list, you can use the not operator in one of the
following ways:
Program:
Output:
>>>
True
True
False
False
>>>
nums = [11,22,33]
print(not 44 in nums)
print(44 not in nums)
print(not 22 in nums)
print(22 not in nums)
19
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
List Functions
Another way of altering lists is using the append method. This adds an item to
the end of an existing list.
Program:
Output:
The dot before append is there because it is a method of the list class.
To get the number of items in a list, you can use the len function.
Program:
Output:
Unlike append, len is a normal function, rather than a method. This means it
is written before the list it is being called on, without a dot.
nums = [1,2,3]
nums.append(4)
print(nums)
>>>
[1, 2, 3, 4]
>>>
nums=[1,2,3,4,5]
print(len(nums))
>>>
5
>>>
20
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
The insert method is similar to append, except that it allows you to insert a
new item at any position in the list, as opposed to just at the end.
Program:
Output:
The index method finds the first occurrence of a list item and returns its index.
If the item isn’t in the list, it raises a ValueError.
Program:
Output:
words = ["Python","Fun"]
index = 1
words.insert(index,"is")
print(words)
2
0
ValueError: 'z' is not in list
>>>
>>>
['Python', 'is', 'Fun']
>>>
letters = ['a','e','i','o','u']
print(letters.index('i'))
print(letters.index('a'))
print(letters.index('z'))
21
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
There are a few more useful functions and methods for lists.
max(list): Returns the list item with the maximum value.
min(list): Returns the list item with the minimum value.
list.count(obj): Returns a count of how many times an item occurs in a list.
list.remove(obj): Removes an object from a list.
List.reverse(): Reverse objects in a list.
22
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Range
The range function creates a sequential list of numbers.
The code below generates a list containing all of the integers, up to 10.
Example:
Output:
The call to list is necessary because range by itself creates a range object, and
this must be converted to a list if you want to use it as one.
If range is called with one argument, it produces an object with values from 0
to that argument. If it is called with two arguments, it produces values from
the first to the second.
Program:
Output:
>>> numbers = list(range(10))
>>> print(numbers)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>>
[3, 4, 5, 6, 7]
True
>>>
numbers = list(range(3,8))
print(numbers)
print(range(20) == range(0,20))
23
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
range can have a third argument, which determines the interval of the
sequence produced. This third argument must be an integer.
Example:
Output:
[5, 7, 9, 11, 13, 15, 17, 19]
>>> numbers = list(range(5,20,2))
>>> print(numbers)
24
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Loops
Sometimes, you need to perform code on each item in a list. This is called
iteration, and it can be accomplished with a while loop and a counter variable.
Program:
Output:
The example above iterates through all items in the list, accesses them using
their indices, and prints them with exclamation marks.
words = ["Python","Programming","Is","Fun"]
counter = 0
max_index = len(words) - 1
while counter <= max_index:
word = words[counter]
print(word + "!")
counter = counter + 1
>>>
Python!
Programming!
Is!
Fun!
>>>
25
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
Iterating through a list using a while loop requires quite a lot of code, so
Python provides the for loop as a shortcut that accomplishes the same thing.
The same code from the previous example can be written with a for loop, as
follows:
Program:
Output:
The for loop in Python is like the foreach loop in other languages.
words = ["Python","Programming","Is","Fun"]
for word in words:
print(word + "!")
>>>
Python!
Programming!
Is!
Fun!
>>>
26
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
The for loop is commonly used to repeat some code a certain number of times.
This is done by combining for loops with range objects.
Program:
Output:
You don’t need to call list on the range object when it is used in a for loop,
because it isn’t being indexed, so a list isn’t required.
for i in range(5):
print("Python!")
>>>
Python!
Python!
Python!
Python!
Python!
>>>
27
CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
You were reading:
1. Basic Concepts In Python
2.Control Structures In Python
 Booleans & Comparisons
 if Statements
 else Statements
 elif Statements
 Boolean Logic
 Operator Precedence
 while Loop
 Lists
 List Operations
 List Functions
 Range
 Loops
3.Functions & Modules In Python
4.Exceptions & Files In Python
5.More Types In Python
6.Functional Programming with Python
7.Object-Oriented Programming with Python
8.Regular Expressions In Python
9.Pythonicness & Packaging

More Related Content

What's hot (20)

Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
Strings
StringsStrings
Strings
Mitali Chugh
 
stack & queue
stack & queuestack & queue
stack & queue
manju rani
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
sumitbardhan
 
Strings in python
Strings in pythonStrings in python
Strings in python
Prabhakaran V M
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Dictionaries in Python
Dictionaries in PythonDictionaries in Python
Dictionaries in Python
baabtra.com - No. 1 supplier of quality freshers
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
Python Data-Types
Python Data-TypesPython Data-Types
Python Data-Types
Akhil Kaushik
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
Python set
Python setPython set
Python set
Mohammed Sikander
 
Python programming : List and tuples
Python programming : List and tuplesPython programming : List and tuples
Python programming : List and tuples
Emertxe Information Technologies Pvt Ltd
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
Kuppusamy P
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
Emertxe Information Technologies Pvt Ltd
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
Tirthika Bandi
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
eShikshak
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
eShikshak
 
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
358 33 powerpoint-slides_4-introduction-data-structures_chapter-4
sumitbardhan
 
Arrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | EdurekaArrays In Python | Python Array Operations | Edureka
Arrays In Python | Python Array Operations | Edureka
Edureka!
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
Megha V
 
Conditional and control statement
Conditional and control statementConditional and control statement
Conditional and control statement
narmadhakin
 
Data types in python
Data types in pythonData types in python
Data types in python
RaginiJain21
 
Python Dictionaries and Sets
Python Dictionaries and SetsPython Dictionaries and Sets
Python Dictionaries and Sets
Nicole Ryan
 
File Handling Python
File Handling PythonFile Handling Python
File Handling Python
Akhil Kaushik
 
String Manipulation in Python
String Manipulation in PythonString Manipulation in Python
String Manipulation in Python
Pooja B S
 
Symbol table in compiler Design
Symbol table in compiler DesignSymbol table in compiler Design
Symbol table in compiler Design
Kuppusamy P
 
Circular link list.ppt
Circular link list.pptCircular link list.ppt
Circular link list.ppt
Tirthika Bandi
 
Applications of stack
Applications of stackApplications of stack
Applications of stack
eShikshak
 

Similar to Control Structures in Python (20)

Python Control structures
Python Control structuresPython Control structures
Python Control structures
Siddique Ibrahim
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
Python notes for students to learn and develop
Python notes for students to learn and developPython notes for students to learn and develop
Python notes for students to learn and develop
kavithaadhilakshmi
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 
Python-review1 for begineers to code.ppt
Python-review1 for begineers to code.pptPython-review1 for begineers to code.ppt
Python-review1 for begineers to code.ppt
freyjadexon608
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
snowflakebatch
 
Lewis_Cocking_AP_Decision_Making_For_Coding
Lewis_Cocking_AP_Decision_Making_For_CodingLewis_Cocking_AP_Decision_Making_For_Coding
Lewis_Cocking_AP_Decision_Making_For_Coding
GeorgeTsak
 
Control structures pyhton
Control structures  pyhtonControl structures  pyhton
Control structures pyhton
Prakash Jayaraman
 
Control statements in c
Control statements in cControl statements in c
Control statements in c
Sathish Narayanan
 
Learn more about the concepts of Data Types in Python
Learn more about the concepts of Data Types in PythonLearn more about the concepts of Data Types in Python
Learn more about the concepts of Data Types in Python
PrathamKandari
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
jaba kumar
 
Unit - 2 CAP.pptx
Unit - 2 CAP.pptxUnit - 2 CAP.pptx
Unit - 2 CAP.pptx
malekaanjum1
 
Python_Module_2.pdf
Python_Module_2.pdfPython_Module_2.pdf
Python_Module_2.pdf
R.K.College of engg & Tech
 
The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3
Binay Kumar Ray
 
Control statments in c
Control statments in cControl statments in c
Control statments in c
CGC Technical campus,Mohali
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
Java unit 3
Java unit 3Java unit 3
Java unit 3
Shipra Swati
 
Conditional Statements
Conditional StatementsConditional Statements
Conditional Statements
MuhammadBakri13
 
M C6java5
M C6java5M C6java5
M C6java5
mbruggen
 
FLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHONFLOW OF CONTROL-INTRO PYTHON
FLOW OF CONTROL-INTRO PYTHON
vikram mahendra
 
Python notes for students to learn and develop
Python notes for students to learn and developPython notes for students to learn and develop
Python notes for students to learn and develop
kavithaadhilakshmi
 
Python-review1.pdf
Python-review1.pdfPython-review1.pdf
Python-review1.pdf
paijitk
 
Python-review1 for begineers to code.ppt
Python-review1 for begineers to code.pptPython-review1 for begineers to code.ppt
Python-review1 for begineers to code.ppt
freyjadexon608
 
Chapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptxChapter 2-Python and control flow statement.pptx
Chapter 2-Python and control flow statement.pptx
atharvdeshpande20
 
Lewis_Cocking_AP_Decision_Making_For_Coding
Lewis_Cocking_AP_Decision_Making_For_CodingLewis_Cocking_AP_Decision_Making_For_Coding
Lewis_Cocking_AP_Decision_Making_For_Coding
GeorgeTsak
 
Learn more about the concepts of Data Types in Python
Learn more about the concepts of Data Types in PythonLearn more about the concepts of Data Types in Python
Learn more about the concepts of Data Types in Python
PrathamKandari
 
Python-review1.ppt
Python-review1.pptPython-review1.ppt
Python-review1.ppt
jaba kumar
 
The Awesome Python Class Part-3
The Awesome Python Class Part-3The Awesome Python Class Part-3
The Awesome Python Class Part-3
Binay Kumar Ray
 
Looping Statements and Control Statements in Python
Looping Statements and Control Statements in PythonLooping Statements and Control Statements in Python
Looping Statements and Control Statements in Python
PriyankaC44
 
Ad

Recently uploaded (20)

Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
Gibson "Secrets to Changing Behaviour in Scholarly Communication: A 2025 NISO...
National Information Standards Organization (NISO)
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad LevelLDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDM & Mia eStudios
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
TV Shows and web-series quiz | QUIZ CLUB OF PSGCAS | 13TH MARCH 2025
Quiz Club of PSG College of Arts & Science
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Optimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptxOptimization technique in pharmaceutical product development.pptx
Optimization technique in pharmaceutical product development.pptx
UrmiPrajapati3
 
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdfForestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
Forestry Model Exit Exam_2025_Wollega University, Gimbi Campus.pdf
ChalaKelbessa
 
What are the benefits that dance brings?
What are the benefits that dance brings?What are the benefits that dance brings?
What are the benefits that dance brings?
memi27
 
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
THERAPEUTIC COMMUNICATION included definition, characteristics, nurse patient...
parmarjuli1412
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
How to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRMHow to Create a Stage or a Pipeline in Odoo 18 CRM
How to Create a Stage or a Pipeline in Odoo 18 CRM
Celine George
 
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17Different pricelists for different shops in odoo Point of Sale in Odoo 17
Different pricelists for different shops in odoo Point of Sale in Odoo 17
Celine George
 
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad LevelLDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDMMIA Reiki Yoga S8 Free Workshop Grad Level
LDM & Mia eStudios
 
"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx"Hymenoptera: A Diverse and Fascinating Order".pptx
"Hymenoptera: A Diverse and Fascinating Order".pptx
Arshad Shaikh
 
State institute of educational technology
State institute of educational technologyState institute of educational technology
State institute of educational technology
vp5806484
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Final Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptxFinal Sketch Designs for poster production.pptx
Final Sketch Designs for poster production.pptx
bobby205207
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Fatman Book HD Pdf by aayush songare.pdf
Fatman Book  HD Pdf by aayush songare.pdfFatman Book  HD Pdf by aayush songare.pdf
Fatman Book HD Pdf by aayush songare.pdf
Aayush Songare
 
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
IDSP(INTEGRATED DISEASE SURVEILLANCE PROGRAMME...
SweetytamannaMohapat
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...Stewart Butler - OECD - How to design and deliver higher technical education ...
Stewart Butler - OECD - How to design and deliver higher technical education ...
EduSkills OECD
 
LDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad UpdatesLDMMIA Reiki Yoga Next Week Grad Updates
LDMMIA Reiki Yoga Next Week Grad Updates
LDM & Mia eStudios
 
Ad

Control Structures in Python

  • 1. 1 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM
  • 2. 2 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Booleans & Comparisons In Python, there are two Boolean values: True and False. They can be created by comparing values, for instances by using the equal operator ==. Another comparison operator, the not equal operator (!=), evaluates to True if the items being compares aren’t equal, and False if they are. Compares both Numbers as well as Strings. Python also has operators that determine whether the given number (integer or float) is greater than or smaller than another. These are < and > respectively. Also we have, >= Greater than or Equal & <= Smaller than or Equal. Except they return True when comparing equal numbers. >>> value = True >>> value True >>> 5 == 15 False >>> "Hello" == "Hello" True >>> "Hi" == "hi" False >>> 1 != 1 False >>> "cat" != "mat" True
  • 3. 3 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Greater than and smaller than operators are also used to compare Strings lexicographically. >>> 9 > 4 True >>> 8 < 8 False >>> 4 <= 7 True >>> 8 >= 8.0 True
  • 4. 4 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM if Statements You can use if statements to run code if a certain condition holds. If an expression evaluates to True, some statements are carried out. Otherwise, they aren’t carried out. Python uses indentation (white space at the beginning of a line) to delimit blocks of code. Other languages, such as C, use curly braces to accomplish this, but in Python indentation is mandatory; programs won’t work without it. Notice the colon at the end of the expression in the if statement. As the program contains multiple lines of code, you should create it as a separate file and run it. To perform more complex checks, if statements can be nested, one inside the other. Where inner if statement will be a part of outer if statement. This is used to see whether multiple conditions are satisfied. Output: if expression: statements no = 24 if no > 18: print("Greater than 18") if no <= 50: print("Between 18 & 50") Greater than 18 Between 18 & 50
  • 5. 5 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM else Statements An else statement follows an if statement & contains code that is called when the if statement evaluates to False. Output: You can chain if and else statements to determine which option in a series of possibilities is true. X = 4 if x == 8: print(“Yes”) else: print(“No”) >>> No >>>
  • 6. 6 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM elif Statements The elif (short of else if) statement is a shortcut to use when chaining if and else statements. A series of if elif statements can have a final else block, which is called if none of the if or elif expression is True. Output: num = 24 if num == 5: print("Number is 5") elif num == 11: print("Number is 11") elif num == 24: print("Number is 24") else: print("Number isn't 5,11 or 24") >>> Number is 24 >>>
  • 7. 7 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Boolean Logic Python’s Boolean operators are and, or and not. The and operator takes two arguments, and evaluates as True if, and only if, both of its arguments are True. Otherwise, it evaluates to False. Python uses words for its Boolean operators, whereas most other languages use symbols such as &&, || an !. Similarly, Boolean or operator takes two arguments. It evaluates to True if either (or both) of its arguments are True, and False if both arguments are False. The result of not True is False, and not False goes to True. >>> 1 == 1 and 2 == 2 True >>> 1 == 1 and 2 == 3 False >>> 1 != 1 and 2 == 2 False >>> 4 < 2 and 2 > 6 False >>> not 1 == 1 False >>> not 7 > 9 True
  • 8. 8 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Operator Precedence Operator Precedence is a very important concept in programming. It is an extension of the mathematical idea of order of operation. (multiplication being performed before addition etc.) to include other operators, such as those in Boolean logic. The below code shows that == has a higher precedence than or. >>> False == False or True True >>> False == (False or True) False >>> (False == False) or True True
  • 9. 9 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM List of Python’s operators, from highest precedence to lowest. ** Exponentiation (raise to the power) ~ + - Complement, unary plus and minus (method names for the last two are +@ and -@) * / % // Multiply, divide, modulo and floor division + - Addition and Subtraction >> << Right and Left bitwise shift & Bitwise ‘AND’ ^ | Bitwise exclusive ‘OR’ and regular ‘OR’ <= == => Comparison operators < > == != Equality Operators = %= /= //= -= += *= **= Assignment Operators is is not Identity operators in not in Membership Operators not or and Logical operators Operator | Description
  • 10. 10 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM while Loop An if statement is run once if its condition evaluates to True, and never if it evaluates to False. A while statement is similar, except that it can be run more than once. The statements inside it are repeatedly executed, as long as the condition holds. Once it evaluates to False, the next section of code is executed. Program: Output: The infinite loop is a special kind of while loop, it never stops running. Its condition always remains True. This program would indefinitely print “In the loop”. i = 1 while i <= 5: print(i) i+=1 print("Finished !") 1 2 3 4 5 Finished ! while 1 == 1: print(“In the loop”)
  • 11. 11 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM You can stop the program’s execution by using the Ctrl-C shortcut or by closing the program.  break To end a while loop prematurely, the break statement can be used. When encountered inside a loop, the break statement causes the loop to finish immediately. Program: Output: i = 0 while 1 == 1: print(i) i+=1 if i >= 5: print("Breaking") break print("Finished") 0 1 2 3 4 Breaking Finished
  • 12. 12 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM  Continue Another statement that can be used within loops is continue. Unlike break, continue jumps back to the top of the loop, rather than stopping it. Program: Output: i=0 while True: i+=1 if i == 2: print("Skipping 2") continue if i == 5: print("Breaking") break print(i) print("Finished") 1 Skipping 2 3 4 Breaking Finished
  • 13. 13 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Lists: Lists are another type of object in Python. They are used to store an indexed list of items. A list is created using square brackets with commas separating items. The certain item in the list can be accessed by using its index in square brackets. Program: Output: The first list item’s index is 0, rather than 1, as might be expected. An empty list can be created with an empty pair of square brackets. It is perfectly valid to write comma after last item of the list, and it is encouraged in some cases. words = ["I","Love","Python"] print(words[0]) print(words[1]) print(words[2]) I Love Python empty_list = []
  • 14. 14 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Typically, a list will contain items of a single item type, but it is also possible to include several different types. Lists can also be nested within other lists. Program: Output: Lists of lists are often used to represent 2D grids, as Python lacks the multidimensional arrays that would be used for this in other languages. number = 33 things = ["String",0,[11,22,number],3.14] print(things[0]) print(things[1]) print(things[2]) print(things[2][2]) String 0 [11, 22, 33] 33
  • 15. 15 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Indexing out of the bounds of possible list values causes an IndexError. Some types, such as strings, can be indexed like lists. Indexing strings behaves as though you are indexing a list containing each character in the string. For other types, such as integers, indexing them isn’t possible, and it causes a TypeError. Program: Output: Output: str = “Hello World!” print(str[6]) >>> W >>>
  • 16. 16 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM List Operations The items at a certain index in a list can be reassigned. Example: Output: Lists can be added and multiplied in the same way as strings. Program: Output: Lists and strings are similar in many ways – strings can be thought of as lists of characters that can’t be changed. >>> [24,24,55,24,24] >>> nums = [24,24,24,24,24] nums[2] = 55 print(nums) nums = [1,2,3] print(nums + [4,5,6]) print(nums *3) [1, 2, 3, 4, 5, 6] [1, 2, 3, 1, 2, 3, 1, 2, 3]
  • 17. 17 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM To check if an item is in a list, the in operator can be used. It returns True if the item occurs one or more times in the list, and False if it doesn’t. Program: Output: The in operator is also used to determine whether or not a string is a substring of another string. words = ["Donut","Eclair","Froyo","Gingerbread"] print("Donut" in words) print("Froyo" in words) print("Lolipop" in words) >>> True True False >>>
  • 18. 18 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM To check if an item is not in a list, you can use the not operator in one of the following ways: Program: Output: >>> True True False False >>> nums = [11,22,33] print(not 44 in nums) print(44 not in nums) print(not 22 in nums) print(22 not in nums)
  • 19. 19 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM List Functions Another way of altering lists is using the append method. This adds an item to the end of an existing list. Program: Output: The dot before append is there because it is a method of the list class. To get the number of items in a list, you can use the len function. Program: Output: Unlike append, len is a normal function, rather than a method. This means it is written before the list it is being called on, without a dot. nums = [1,2,3] nums.append(4) print(nums) >>> [1, 2, 3, 4] >>> nums=[1,2,3,4,5] print(len(nums)) >>> 5 >>>
  • 20. 20 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM The insert method is similar to append, except that it allows you to insert a new item at any position in the list, as opposed to just at the end. Program: Output: The index method finds the first occurrence of a list item and returns its index. If the item isn’t in the list, it raises a ValueError. Program: Output: words = ["Python","Fun"] index = 1 words.insert(index,"is") print(words) 2 0 ValueError: 'z' is not in list >>> >>> ['Python', 'is', 'Fun'] >>> letters = ['a','e','i','o','u'] print(letters.index('i')) print(letters.index('a')) print(letters.index('z'))
  • 21. 21 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM There are a few more useful functions and methods for lists. max(list): Returns the list item with the maximum value. min(list): Returns the list item with the minimum value. list.count(obj): Returns a count of how many times an item occurs in a list. list.remove(obj): Removes an object from a list. List.reverse(): Reverse objects in a list.
  • 22. 22 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Range The range function creates a sequential list of numbers. The code below generates a list containing all of the integers, up to 10. Example: Output: The call to list is necessary because range by itself creates a range object, and this must be converted to a list if you want to use it as one. If range is called with one argument, it produces an object with values from 0 to that argument. If it is called with two arguments, it produces values from the first to the second. Program: Output: >>> numbers = list(range(10)) >>> print(numbers) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> [3, 4, 5, 6, 7] True >>> numbers = list(range(3,8)) print(numbers) print(range(20) == range(0,20))
  • 23. 23 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM range can have a third argument, which determines the interval of the sequence produced. This third argument must be an integer. Example: Output: [5, 7, 9, 11, 13, 15, 17, 19] >>> numbers = list(range(5,20,2)) >>> print(numbers)
  • 24. 24 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Loops Sometimes, you need to perform code on each item in a list. This is called iteration, and it can be accomplished with a while loop and a counter variable. Program: Output: The example above iterates through all items in the list, accesses them using their indices, and prints them with exclamation marks. words = ["Python","Programming","Is","Fun"] counter = 0 max_index = len(words) - 1 while counter <= max_index: word = words[counter] print(word + "!") counter = counter + 1 >>> Python! Programming! Is! Fun! >>>
  • 25. 25 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM Iterating through a list using a while loop requires quite a lot of code, so Python provides the for loop as a shortcut that accomplishes the same thing. The same code from the previous example can be written with a for loop, as follows: Program: Output: The for loop in Python is like the foreach loop in other languages. words = ["Python","Programming","Is","Fun"] for word in words: print(word + "!") >>> Python! Programming! Is! Fun! >>>
  • 26. 26 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM The for loop is commonly used to repeat some code a certain number of times. This is done by combining for loops with range objects. Program: Output: You don’t need to call list on the range object when it is used in a for loop, because it isn’t being indexed, so a list isn’t required. for i in range(5): print("Python!") >>> Python! Python! Python! Python! Python! >>>
  • 27. 27 CONTROL STRUCTURES IN PYTHON SUMIT S. SATAM You were reading: 1. Basic Concepts In Python 2.Control Structures In Python  Booleans & Comparisons  if Statements  else Statements  elif Statements  Boolean Logic  Operator Precedence  while Loop  Lists  List Operations  List Functions  Range  Loops 3.Functions & Modules In Python 4.Exceptions & Files In Python 5.More Types In Python 6.Functional Programming with Python 7.Object-Oriented Programming with Python 8.Regular Expressions In Python 9.Pythonicness & Packaging