KEMBAR78
Python Flow Control & use of functions.pptx
Flow Control
By:
Vilas Machhi
If statements
• Python supports the usual logical conditions from mathematics:
– Equals: a == b
– Not Equals: a != b
– Less than: a < b
– Less than or equal to: a <= b
– Greater than: a > b
– Greater than or equal to: a >= b
• These conditions can be used in several ways, most commonly in "if
statements" and loops.
Example
• If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
b is greater than a
Indentation
• Python relies on indentation (whitespace at the beginning
of a line) to define scope in the code. Other programming
languages often use curly-brackets for this purpose.
Example
• If statement, without indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error
Elif statement
• The elif keyword is pythons way of saying "if the previous
conditions were not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal") Output:
a and b are equal
Else
• The else keyword catches anything
which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
• You can also have an else without
the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a")
Output:
b is not greater than a
Output:
a is greater than b
Short Hand If
• If you have only one statement to execute, you can put it on the same line as
the if statement.
Example
• One line if statement:
if a > b: print("a is greater than b")
Short Hand If ... Else
• If you have only one statement to execute, one for if, and one for else, you
can put it all on the same line:
Example
• One line if else statement:
a = 2
b = 330
print("A") if a > b else print("B")
This technique is known as Ternary Operators, or Conditional Expressions.
Output:
B
• You can also have multiple else statements on the same line:
Example
• One line if else statement, with 3 conditions:
a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")
And
• The and keyword is a logical operator, and is used to combine conditional
statements:
Example
• Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Output:
=
Output:
Both conditions are True
Or
• The or keyword is a logical operator, and is used to combine conditional statements:
Example
• Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Nested If
• You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
Output:
At least one of the conditions is True
Output:
Above ten,
and also above 20!
The pass Statement
• if statements cannot be empty, but if you for some reason
have an if statement with no content, put in the pass
statement to avoid getting an error.
Example
a = 33
b = 200
if b > a:
pass
While Loops
• Python has two primitive loop commands:
– while loops
– for loops
The while Loop
• With the while loop we can execute a set of statements as long as a
condition is true.
Example
• Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
• Note: remember to increment i, or else the loop will continue forever.
Output:
1
2
3
4
5
The break Statement
• With the break statement we can stop the loop even if the
while condition is true:
Example
• Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
Output:
1
2
3
The continue Statement
• With the continue statement we can stop the current
iteration, and continue with the next:
Example
• Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
Output:
1
2
4
5
6
The else Statement
• With the else statement we can run a block of code once
when the condition no longer is true:
Example
• Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
Output:
1
2
3
4
5
i is no longer less than 6
For Loops
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).
• This is less like the for keyword in other programming languages, and works
more like an iterator method as found in other object-orientated programming
languages.
• With the for loop we can execute a set of statements, once for each item in a
list, tuple, set etc.
• Even strings are iterable objects, they contain a sequence of characters:
Example
• Loop through the letters in the word "banana":
for x in "banana":
print(x)
Output:
b
a
n
a
n
a
Loop Lists
• You can loop through the list items by using a for loop:
Example
• Print all items in the list, one by one:
thislist = ["apple", "banana", "cherry"]
for x in thislist:
print(x)
Loop Through the Index Numbers
• You can also loop through the list items by referring to their index number.
• Use the range() and len() functions to create a suitable iterable.
Example
• Print all items by referring to their index number:
thislist = ["apple", "banana", "cherry"]
for i in range(len(thislist)):
print(thislist[i])
The iterable created in the example above is [0, 1, 2]
Output:
apple
banana
cherry
Output:
apple
banana
cherry
List Comprehension
• List comprehension offers a shorter syntax when you want to create a new list based on the
values of an existing list.
• Example: Based on a list of fruits, you want a new list, containing only the fruits with the
letter "a" in the name.
• Without list comprehension you will have to write a for statement with a conditional test
inside:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line of code:
Example
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
Output:
['apple', 'banana', 'mango']
Output:
['apple', 'banana', 'mango']
The Syntax
newlist = [expression for item in iterable if condition == True]
• The return value is a new list, leaving the old list unchanged.
Condition
• The condition is like a filter that only accepts the items that valuate to True.
Example
• Only accept items that are not "apple":
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if x != "apple"]
print(newlist)
The condition if x != "apple" will return True for all elements other than "apple",
making the new list contain all fruits except "apple".
• The condition is optional and can be omitted:
Example
• With no if statement:
newlist = [x for x in fruits]
Output:
['banana', 'cherry', 'kiwi', 'mango']
Iterable
• The iterable can be any iterable object, like a list, tuple, set etc.
Example
• You can use the range() function to create an iterable:
newlist = [x for x in range(10)]
print(newlist)
• Same example, but with a condition:
Example
• Accept only numbers lower than 5:
newlist = [x for x in range(10) if x < 5]
print(newlist)
Expression
• The expression is the current item in the iteration, but it is also the outcome,
which you can manipulate before it ends up like a list item in the new list:
Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Output:
[0, 1, 2, 3, 4]
Example
• Set the values in the new list to upper case:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x.upper() for x in fruits]
print(newlist)
• You can set the outcome to whatever you like:
• Example
• Set all values in the new list to 'hello':
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = ['hello' for x in fruits]
print(newlist)
The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome:
Example
• Return "orange" instead of "banana":
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x if x != "banana" else "orange" for x in fruits]
print(newlist)
The expression in the example above says:
• "Return the item if it is not banana, if it is banana return orange".
Output:
['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO']
Output:
['hello', 'hello', 'hello', 'hello', 'hello']
Output:
['apple', 'orange', 'cherry', 'kiwi', 'mango']
Else in For Loop
• The else keyword in a for loop
specifies a block of code to be
executed when the loop is finished:
Example
• Print all numbers from 0 to 5, and
print a message when the loop has
ended:
for x in range(6):
print(x)
else:
print("Finally finished!")
• Note: The else block will NOT be
executed if the loop is stopped by a
break statement.
Example
• Break the loop when x is 3, and see
what happens with the else block:
for x in range(6):
if x == 3: break
print(x)
else:
print("Finally finished!")
Output:
0
1
2
3
4
5
Finally finished!
Output:
0
1
2
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
• Print each adjective for every fruit:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The pass Statement
• for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]:
pass
Output:
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
Loop Tuples
• You can loop through the tuple items by using a for loop.
Example
• Iterate through the items and print the values:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Output:
apple
banana
cherry
Loop Sets
• You can loop through the set items by using a for loop:
Example
• Loop through the set, and print the values:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Output:
cherry
banana
apple
Loop Dictionaries
• You can loop through a dictionary by
using a for loop.
• When looping through a dictionary, the
return value are the keys of the
dictionary, but there are methods to
return the values as well.
Example
• Print all key names in the dictionary,
one by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)
Example
• Print all values in the dictionary, one
by one:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(thisdict[x])
Output:
brand
model
year
Output:
Ford
Mustang
1964
Example
• You can also use the values()
method to return values of a
dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.values():
print(x)
Example
• You can use the keys()
method to return the keys of a
dictionary:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict.keys():
print(x)
Output:
Ford
Mustang
1964
Output:
brand
model
year
Example
• Loop through both keys and values, by using the items() method:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x, y in thisdict.items():
print(x, y)
Output:
brand Ford
model Mustang
year 1964

Python Flow Control & use of functions.pptx

  • 1.
  • 2.
    If statements • Pythonsupports the usual logical conditions from mathematics: – Equals: a == b – Not Equals: a != b – Less than: a < b – Less than or equal to: a <= b – Greater than: a > b – Greater than or equal to: a >= b • These conditions can be used in several ways, most commonly in "if statements" and loops. Example • If statement: a = 33 b = 200 if b > a: print("b is greater than a") Output: b is greater than a
  • 3.
    Indentation • Python relieson indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. Example • If statement, without indentation (will raise an error): a = 33 b = 200 if b > a: print("b is greater than a") # you will get an error
  • 4.
    Elif statement • Theelif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". Example a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") Output: a and b are equal
  • 5.
    Else • The elsekeyword catches anything which isn't caught by the preceding conditions. Example a = 200 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") • You can also have an else without the elif: Example a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") Output: b is not greater than a Output: a is greater than b
  • 6.
    Short Hand If •If you have only one statement to execute, you can put it on the same line as the if statement. Example • One line if statement: if a > b: print("a is greater than b") Short Hand If ... Else • If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: Example • One line if else statement: a = 2 b = 330 print("A") if a > b else print("B") This technique is known as Ternary Operators, or Conditional Expressions. Output: B
  • 7.
    • You canalso have multiple else statements on the same line: Example • One line if else statement, with 3 conditions: a = 330 b = 330 print("A") if a > b else print("=") if a == b else print("B") And • The and keyword is a logical operator, and is used to combine conditional statements: Example • Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Output: = Output: Both conditions are True
  • 8.
    Or • The orkeyword is a logical operator, and is used to combine conditional statements: Example • Test if a is greater than b, OR if a is greater than c: a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") Nested If • You can have if statements inside if statements, this is called nested if statements. Example x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") Output: At least one of the conditions is True Output: Above ten, and also above 20!
  • 9.
    The pass Statement •if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. Example a = 33 b = 200 if b > a: pass
  • 10.
    While Loops • Pythonhas two primitive loop commands: – while loops – for loops The while Loop • With the while loop we can execute a set of statements as long as a condition is true. Example • Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1 • Note: remember to increment i, or else the loop will continue forever. Output: 1 2 3 4 5
  • 11.
    The break Statement •With the break statement we can stop the loop even if the while condition is true: Example • Exit the loop when i is 3: i = 1 while i < 6: print(i) if i == 3: break i += 1 Output: 1 2 3
  • 12.
    The continue Statement •With the continue statement we can stop the current iteration, and continue with the next: Example • Continue to the next iteration if i is 3: i = 0 while i < 6: i += 1 if i == 3: continue print(i) Output: 1 2 4 5 6
  • 13.
    The else Statement •With the else statement we can run a block of code once when the condition no longer is true: Example • Print a message once the condition is false: i = 1 while i < 6: print(i) i += 1 else: print("i is no longer less than 6") Output: 1 2 3 4 5 i is no longer less than 6
  • 14.
    For Loops • Afor loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). • This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. • With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. • Even strings are iterable objects, they contain a sequence of characters: Example • Loop through the letters in the word "banana": for x in "banana": print(x) Output: b a n a n a
  • 15.
    Loop Lists • Youcan loop through the list items by using a for loop: Example • Print all items in the list, one by one: thislist = ["apple", "banana", "cherry"] for x in thislist: print(x) Loop Through the Index Numbers • You can also loop through the list items by referring to their index number. • Use the range() and len() functions to create a suitable iterable. Example • Print all items by referring to their index number: thislist = ["apple", "banana", "cherry"] for i in range(len(thislist)): print(thislist[i]) The iterable created in the example above is [0, 1, 2] Output: apple banana cherry Output: apple banana cherry
  • 16.
    List Comprehension • Listcomprehension offers a shorter syntax when you want to create a new list based on the values of an existing list. • Example: Based on a list of fruits, you want a new list, containing only the fruits with the letter "a" in the name. • Without list comprehension you will have to write a for statement with a conditional test inside: Example fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [] for x in fruits: if "a" in x: newlist.append(x) print(newlist) With list comprehension you can do all that with only one line of code: Example fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if "a" in x] print(newlist) Output: ['apple', 'banana', 'mango'] Output: ['apple', 'banana', 'mango']
  • 17.
    The Syntax newlist =[expression for item in iterable if condition == True] • The return value is a new list, leaving the old list unchanged. Condition • The condition is like a filter that only accepts the items that valuate to True. Example • Only accept items that are not "apple": fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x for x in fruits if x != "apple"] print(newlist) The condition if x != "apple" will return True for all elements other than "apple", making the new list contain all fruits except "apple". • The condition is optional and can be omitted: Example • With no if statement: newlist = [x for x in fruits] Output: ['banana', 'cherry', 'kiwi', 'mango']
  • 18.
    Iterable • The iterablecan be any iterable object, like a list, tuple, set etc. Example • You can use the range() function to create an iterable: newlist = [x for x in range(10)] print(newlist) • Same example, but with a condition: Example • Accept only numbers lower than 5: newlist = [x for x in range(10) if x < 5] print(newlist) Expression • The expression is the current item in the iteration, but it is also the outcome, which you can manipulate before it ends up like a list item in the new list: Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] Output: [0, 1, 2, 3, 4]
  • 19.
    Example • Set thevalues in the new list to upper case: fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x.upper() for x in fruits] print(newlist) • You can set the outcome to whatever you like: • Example • Set all values in the new list to 'hello': fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = ['hello' for x in fruits] print(newlist) The expression can also contain conditions, not like a filter, but as a way to manipulate the outcome: Example • Return "orange" instead of "banana": fruits = ["apple", "banana", "cherry", "kiwi", "mango"] newlist = [x if x != "banana" else "orange" for x in fruits] print(newlist) The expression in the example above says: • "Return the item if it is not banana, if it is banana return orange". Output: ['APPLE', 'BANANA', 'CHERRY', 'KIWI', 'MANGO'] Output: ['hello', 'hello', 'hello', 'hello', 'hello'] Output: ['apple', 'orange', 'cherry', 'kiwi', 'mango']
  • 20.
    Else in ForLoop • The else keyword in a for loop specifies a block of code to be executed when the loop is finished: Example • Print all numbers from 0 to 5, and print a message when the loop has ended: for x in range(6): print(x) else: print("Finally finished!") • Note: The else block will NOT be executed if the loop is stopped by a break statement. Example • Break the loop when x is 3, and see what happens with the else block: for x in range(6): if x == 3: break print(x) else: print("Finally finished!") Output: 0 1 2 3 4 5 Finally finished! Output: 0 1 2
  • 21.
    Nested Loops • Anested loop is a loop inside a loop. • The "inner loop" will be executed one time for each iteration of the "outer loop": Example • Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) The pass Statement • for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. Example for x in [0, 1, 2]: pass Output: red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry
  • 22.
    Loop Tuples • Youcan loop through the tuple items by using a for loop. Example • Iterate through the items and print the values: thistuple = ("apple", "banana", "cherry") for x in thistuple: print(x) Output: apple banana cherry
  • 23.
    Loop Sets • Youcan loop through the set items by using a for loop: Example • Loop through the set, and print the values: thisset = {"apple", "banana", "cherry"} for x in thisset: print(x) Output: cherry banana apple
  • 24.
    Loop Dictionaries • Youcan loop through a dictionary by using a for loop. • When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well. Example • Print all key names in the dictionary, one by one: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(x) Example • Print all values in the dictionary, one by one: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict: print(thisdict[x]) Output: brand model year Output: Ford Mustang 1964
  • 25.
    Example • You canalso use the values() method to return values of a dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict.values(): print(x) Example • You can use the keys() method to return the keys of a dictionary: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x in thisdict.keys(): print(x) Output: Ford Mustang 1964 Output: brand model year
  • 26.
    Example • Loop throughboth keys and values, by using the items() method: thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964 } for x, y in thisdict.items(): print(x, y) Output: brand Ford model Mustang year 1964