0% found this document useful (0 votes)
1 views

Python Function Scope_updated_1610

python function Scope updated
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

Python Function Scope_updated_1610

python function Scope updated
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Control flow in Python

Dr. Udit Nath, Phd


3rd Oct 2024
Understanding Python Block

A Python program is constructed from code blocks. A block is a


piece of Python program text that is executed as a unit. The
following are blocks: a module, a function body, and a class
definition. Each command typed interactively is a block.

In Python, a block is a group of statements that are indented


together. Blocks are used to define the scope of variables and
to control the flow of execution.

2
Control flow – if, else

3
Control Flow – if , else, elif

4
Control Flow – if , else, elif

5
Control Flow – if , else, elif

6
Control Flow – if , else, elif

7
Control Flow – if , else, elif

8
Control Flow – if , else, elif
Python Code

9
Python nonlocal Keyword
Make a function inside a function, which uses the Python Code
variable x as a nonlocal variable:
def myfunc1():
x = "John"
def myfunc2():
nonlocal x
x = "hello"
myfunc2()
return x

print(myfunc1())

10
Python nonlocal Keyword
Python Code - Same example as above, but
Definition and Usage without the nonlocal keyword:

The nonlocal keyword is used to work with variables inside def myfunc1():
nested functions, where the variable should not belong to x = "John"
the inner function. def myfunc2():
x = "hello"
Use the keyword nonlocal to declare that the variable is myfunc2()
not local. return x

print(myfunc1())

11
The Nested if Statement
Python Code :
You can have if statements inside if statements, this is
package main
called a nested if.
import ("fmt")
Syntax:
if condition1 { func main() {
// code to be executed if condition1 is true num := 20
if condition2 { if num >= 10 {
// code to be executed if both condition1 fmt.Println("Num is more than
and condition2 are true 10.")
} if num > 15 {
} fmt.Println("Num is also more
than 15.")
}
} else {
fmt.Println("Num is less than
10.")
}
} 12
Python - function scope
Function scope: Variables that are declared inside a Python Code
function are called local variables and in the function def myfunc1():
scope. Local variables are accessible anywhere inside x = "John"
the function. Block scope: Variable that is declared def myfunc2():
inside a specific block & can't be accessed outside of nonlocal x
that block.: x = "hello"
myfunc2()
return x

print(myfunc1())

13
Control Flow – if , else, elif
Python Code

14
Python - Built-in Functions
Python interpreter has a number of functions and types built into it Python Code ZIP
that are always available. They are listed here in alphabetical order.:

15
Python Built-in Functions Cont…

16
Python Built-in Functions Cont…

17
Python abs() Function
Return the absolute value of a number: Python Code abs ()
x = abs(-7.25)
print (x)

Return the absolute value of


a complex number:

|3+4J| = |a+bi| =𝑎2 + 𝑏2 = 𝑐 2

C = 𝑎2 + 𝑏2 = 32 + 42 =
9 + 16 = √34 =5.830951
18
Python abs() Function
The `zip` function in Python is a built-in Python Code abs ()
function that allows you to aggregate elements x = abs(-7.25)
from multiple iterables into a single iterable. It print (x)
takes two or more iterables as input and
returns an iterator that produces tuples
containing elements from all the input
iterables.

19
Python Lists
Python Code abs ()

List mylist =
["apple", "banana", "cherry"]

▪ Lists are used to store multiple items in a single


variable
▪ Lists are one of 4 built-in data types in Python ▪ Lists are created using square brackets:
used to store collections of data, the other 3
are Tuple, Set, and Dictionary, all with different
qualities and usage.
thislist = ["apple", "banana", "cherry"]
print(thislist)

20
Python Lists
Python Code abs ()

List Items mylist =


["apple", "banana", "cherry"]

▪ List items are ordered, changeable, and allow


duplicate values.
▪ List items are indexed, the first item has index ▪ Lists are created using square brackets:
[0], the second item has index [1] etc.
▪ The list is changeable, meaning that we can
change, add, and remove items in a list after it
has been created
▪ Allow Duplicates
thislist = ["apple", "banana", "cherry"]
▪ Since lists are indexed, lists can have items print(thislist)
with the same value:

thislist =
["apple", "banana", "cherry", "apple", "cherry"]
print(thislist)
21
Python Lists
Python Code abs ()

List Length List Items - Data Types


To determine how many items a list has, use the len()
function: List items can be of any data type:
Print the number of items in the list:

String, int and boolean data types:


thislist = ["apple", "banana", "cherry"]
print(len(thislist))
list1 = ["apple", "banana", "cherry"]
list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

22
Python Tuples
Tuple Items

Tuples are used to store multiple items in a single variable. ▪ Tuple items are ordered, unchangeable,
and allow duplicate values.
Tuple is one of 4 built-in data types in Python used to store
▪ Tuple items are indexed, the first item
collections of data, the other 3 are List, Set, and Dictionary, all
with different qualities and usage.
has index [0], the second item has index
[1] etc.
A tuple is a collection which is ordered and unchangeable. ▪ When we say that tuples are ordered, it
means that the items have a defined
Tuples are written with round brackets. order, and that order will not change.
▪ Tuples are unchangeable, meaning that
we cannot change, add or remove items
Create a Tuple: after the tuple has been created.
thistuple = ("apple", "banana", "cherry") ▪ Since tuples are indexed, they can have
print(thistuple) items with the same value:
Tuples allow duplicate values:
thistuple = ("apple", "banana", "cherry", "apple", "cherry")
print(thistuple)
23
Python Tuples
Tuple Items
Tuple Length
Create Tuple With One Item
To determine how many items a tuple has, use the len() ▪ To create a tuple with only one item, you
function: have to add a comma after the item,
otherwise Python will not recognize it as a
tuple.
Print the number of items in the tuple:
▪ Tuple Items - Data Types
thistuple = ("apple", "banana", "cherry") ▪ Tuple items can be of any data type:
print(len(thistuple)) ▪ String, int and boolean data types:

▪ tuple1 = ("apple", "banana", "cherry")


tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)

24
Python Sets
Sets are written with curly brackets.

Sets are used to store multiple items in a single variable. thisset = {"apple", "banana", "cherry"}
print(thisset)
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,
# Note: the set list is unordered, meaning: the items
all with different qualities and usage.
will appear in a random order.
A set is a collection which is unordered, unchangeable*, and # Refresh this page to see the change in the result.
unindexed.

* Note: Set items are unchangeable, but you can


remove items and add new items. Duplicates Not Allowed
Sets cannot have two items with the same value.
Duplicate values will be ignored:
thisset = {"apple", "banana", "cherry", "apple"}

print(thisset)
25
Python Dictionary
Create and print a dictionary:
Dictionaries are used to store data values in key:value pairs.
thisdict = {
A dictionary is a collection which is ordered*, changeable "brand": "Ford",
and do not allow duplicates. "model": "Mustang",
"year": 1964
As of Python version 3.7, dictionaries are ordered. In
Python 3.6 and earlier, dictionaries are unordered. }
print(thisdict)
Dictionaries are written with curly brackets, and have keys
and values:

duplicate values will overwrite existing values:


thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict) 26
Python abs() Function

You might also like