0% found this document useful (0 votes)
9 views26 pages

Understanding Control Flow in Programming

This document covers control flow statements in programming, including conditional and looping statements, as well as jump statements. It explains the use of if-else, switch-case, for, while, and do-while loops, along with their syntax and examples. Additionally, it discusses function definitions, calling functions, variable scope, and lambda functions in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views26 pages

Understanding Control Flow in Programming

This document covers control flow statements in programming, including conditional and looping statements, as well as jump statements. It explains the use of if-else, switch-case, for, while, and do-while loops, along with their syntax and examples. Additionally, it discusses function definitions, calling functions, variable scope, and lambda functions in Python.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Unit - II

2.1 Control Flow Statements: Conditional Flow statements; Loop


Control Statements; Nested control Flow; continue and break
statements, continue, Pass and exit.
Control flow refers to the order in which statements within a
program execute. While programs typically follow a sequential
flow from top to bottom, there are scenarios where we need more
flexibility. This article provides a clear understanding about
everything you need to know about Control Flow Statements.

Types of Control Flow statements in Programming:


Control Flow Control Description
Statements Flow
Type Statement

Executes a block of code if a


specified condition is true, and
if-else
another block if the condition is
Conditional false.
Statements
Evaluates a variable or expression
switch-case and executes code based on
matching cases.

Executes a block of code a


Looping specified number of times,
for
Statements typically iterating over a range of
values.
Control Flow Control Description
Statements Flow
Type Statement

Executes a block of code as long


while
as a specified condition is true.

Executes a block of code once and


do-while then repeats the execution as long
as a specified condition is true.

Terminates the loop or switch


statement and transfers control to
break
the statement immediately
following the loop or switch.

Skips the current iteration of a


continue loop and continues with the next
iteration.
Jump
Statements Exits a function and returns a
return
value to the caller.

Transfers control to a labeled


statement within the same
function. (Note: goto is generally
goto
discouraged due to its potential for
creating unreadable and error-
prone code.)

Conditional Statements in Programming:


Conditional statements in programming are used to execute certain
blocks of code based on specified conditions. They are fundamental
to decision-making in programs. Here are some common types of
conditional statements:

1. If Statement in Programming:

The if statement is used to execute a block of code if a specified


condition is true.
a=5
if a == 5:
print("a is equal to 5")
Output
a is equal to 5

2. if-else Statement in Programming:

The if-else statement is used to execute one block of code if a


specified condition is true, and another block of code if the condition
is false.

a = 10
if a == 5:
print("a is equal to 5")
else:
print("a is not equal to 5")

Output
a is not equal to 5

Looping Statements in Programming:


Looping statements, also known as iteration or repetition statements,
are used in programming to repeatedly execute a block of code. They
are essential for performing tasks such as iterating over elements in a
list, reading data from a file, or executing a set of instructions a
specific number of times. Here are some common types of looping
statements:

1. For Loop in Programming:

The for loop is used to iterate over a sequence (e.g., a list, tuple,
string, or range) and execute a block of code for each item in the
sequence.

for i in range(5):
print(i)

Output
0
1
2
3
4

2. While Loop in Programming:

The while loop is used to repeatedly execute a block of code as long


as a specified condition is true.

count = 0
while count < 5:
print(count)
count += 1

Output
0
1
2
3
4

3. Nested Loops in Programming:

Loops can be nested within one another to perform more complex


iterations. For example, a for loop can be nested inside
another for loop to create a two-dimensional iteration.

for i in range(2):
for j in range(2):
print(f"i={i} j={j}")

Output
i=0 j=0
i=0 j=1
i=1 j=0
i=1 j=1
Each programming language may have its own syntax and specific
variations of these looping statements.
Jump Statements in Programming:
Jump statements in programming are used to change the flow of
control within a program. They allow the programmer to transfer
program control to different parts of the code based on certain
conditions or requirements. Here are common types of jump
statements:

1. Break Statement in Programming:

The break statement is primarily used to exit from loops


prematurely. When encountered inside a loop, it terminates the loop's
execution and transfers control to the statement immediately
following the loop.

for i in range(10):
if i == 5:
break
print(f"{i} ", end="")

Output
01234

2. Continue Statement in Programming:

The continue statement is used to skip the current iteration of a loop


and proceed to the next iteration.

for i in range(10):
if i % 2 == 1:
continue
print(f"{i} ", end="")

Output
02468

3. Return Statement in Programming:


The return statement is used to exit a function and optionally return a
value to the caller.

def isEven(N):
return N % 2 == 0

N=5
if isEven(N):
print("N is even")
else:
print("N is odd")

Output
N is odd

2.2 Functions: Built-In Functions, Function Definition and call;


Scope and Lifetime of Variables,
Default Parameters, Command Line Arguments; Lambda Functions;
Assert statement; ImportingUser defined module.

Python has a set of built-in functions.

Function Description

abs() Returns the absolute value of a number

all() Returns True if all items in an iterable object are true

any() Returns True if any item in an iterable object is true


ascii() Returns a readable version of an object. Replaces none-ascii characters
with escape character

bin() Returns the binary version of a number

bool() Returns the boolean value of the specified object

bytearray() Returns an array of bytes

bytes() Returns a bytes object

callable() Returns True if the specified object is callable, otherwise False

chr() Returns a character from the specified Unicode code.

classmethod() Converts a method into a class method

compile() Returns the specified source as an object, ready to be executed

complex() Returns a complex number

delattr() Deletes the specified attribute (property or method) from the specified
object

dict() Returns a dictionary (Array)

dir() Returns a list of the specified object's properties and methods

divmod() Returns the quotient and the remainder when argument1 is divided by
argument2
enumerate() Takes a collection (e.g. a tuple) and returns it as an enumerate object

eval() Evaluates and executes an expression

exec() Executes the specified code (or object)

filter() Use a filter function to exclude items in an iterable object

float() Returns a floating point number

format() Formats a specified value

frozenset() Returns a frozenset object

getattr() Returns the value of the specified attribute (property or method)

globals() Returns the current global symbol table as a dictionary

hasattr() Returns True if the specified object has the specified attribute
(property/method)

hash() Returns the hash value of a specified object

help() Executes the built-in help system

hex() Converts a number into a hexadecimal value

id() Returns the id of an object

input() Allowing user input


int() Returns an integer number

isinstance() Returns True if a specified object is an instance of a specified object

issubclass() Returns True if a specified class is a subclass of a specified object

iter() Returns an iterator object

len() Returns the length of an object

list() Returns a list

locals() Returns an updated dictionary of the current local symbol table

map() Returns the specified iterator with the specified function applied to each
item

In Python, defining and calling functions is simple and may greatly


improve the readability and reusability of our code. In this article, we
will explore How we can define and call a function.
Example:

# Defining a function
def fun():
print("Welcome to GFG")

# calling a function
fun()
Let's understand defining and calling a function in detail:

Defining a Function
By using the word def keyword followed by the function's name and
parentheses () we can define a function. If the function takes any
arguments, they are included inside the parentheses. The code inside
a function must be indented after the colon to indicate it belongs to
that function.

Syntax of defining a function:

def function_name(parameters):
# Code to be executed
return value
 function_name: The name of your function.
 parameters: Optional. A list of parameters (input values) for the
function.
 return: Optional. The return statement is used to send a result
back from the function.
Example:

def fun():
print("Welcome to GFG")

# Defining a function with parameters


def greet(name, age):
print(name, age)
Explanation:
 fun(): A simple function that prints "Welcome to GFG" when
called, without any parameters.
 greet(name, age): A function with two parameters (name and
age) that prints the values passed to it when called.

Calling a Function
To call a function in Python, we definitely type the name of the
function observed via parentheses (). If the function takes any
arguments, they may be covered within the parentheses . Below is
the example for calling def function Python.
Syntax of Calling a function:

function_name(arguments)
Example:

def fun():
print("Welcome to GFG")
#calling a function
fun()

# Defining a function with parameters


def greet(name, age):
print(name, age)

#calling a function by passing arguments


greet("Alice",21)

Output
Welcome to GFG
Alice 21
Explanation:
 Calling fun(): The function fun() is called without any arguments,
and it prints "Welcome to GFG".
 Calling greet("Alice", 21): The function greet() is called with the
arguments "Alice" and 21, which are printed as "Alice 21"
Python Scope variable
The location where we can find a variable and also access it if
required is called the scope of a variable.

Python Local variable


Local variables are those that are initialized within a function and are
unique to that function. It cannot be accessed outside of the function.
Let's look at how to make a local variable.

def f():

# local variable
s = "I love Geeksforgeeks"
print(s)

# Driver code
f()
Output
I love Geeksforgeeks
If we will try to use this local variable outside the function then let’s
see what will happen.

def f():

# local variable
s = "I love Geeksforgeeks"
print("Inside Function:", s)

# Driver code
f()
print(s)
Output:
NameError: name 's' is not defined

Python Global variables

Global variables are the ones that are defined and declared outside
any function and are not specified to any function. They can be used
by any part of the program.
Example:

# This function uses global variable s


def f():
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks
Global and Local Variables with the Same Name
Now suppose a variable with the same name is defined inside the
scope of the function as well then it will print the value given inside
the function only and not the global value.

# This function has a variable with


# name same as s.
def f():
s = "Me too."
print(s)

# Global scope
s = "I love Geeksforgeeks"
f()
print(s)
Output:
Me too.
I love Geeksforgeeks
The variable s is defined as the string “I love Sahyog”, before we
call the function f(). The only statement in f() is the print(s)
statement. As there are no locals, the value from the global s will be
used.
The question is, what will happen if we change the value of s inside
of the function f()? Will it affect the global s as well? We test it in
the following piece of code:

def f():
print(s)

# This program will NOT show error


# if we comment below line.
s = "Me too."

print(s)

# Global scope
s = "I love Sahayog"
f()
print(s)
Output:
Traceback (most recent call last):
File "/home/[Link]", line 13, in
f()
File "/home/[Link]", line 3, in f
print(s)
UnboundLocalError: local variable 's' referenced before assignment

To make the above program work, we need to use global keyword.


We only need to use global keyword in a function if we want to do
assignments / change them. global is not needed for printing and
accessing. Why? Python “assumes” that we want a local variable due
to the assignment to s inside of f(), so the first print statement throws
this error message. Any variable which is changed or created inside
of a function is local, if it hasn’t been declared as a global variable.
To tell Python, that we want to use the global variable, we have to
use the keyword global, as can be seen in the following

Example:

# This function modifies global variable 's'


def f():
global s
print(s)
s = "Look for Geeksforgeeks Python Section"
print(s)

# Global Scope
s = "Python is great !"
f()
print(s)
Output:
Python is great!
Look for Geeksforgeeks Python Section
Look for Geeksforgeeks Python Section

Python Lambda
ambda Functions are anonymous functions means that the function is
without a name. As we already know def keyword is used to define a
normal function in Python. Similarly, lambda keyword is used to
define an anonymous function in Python.
Example: In the example, we defined a lambda function (upper) to
convert a string to its upper case using upper().

s1 = 'GeeksforGeeks'
s2 = lambda func: [Link]()
print(s2(s1))

Output
GEEKSFORGEEKS
Explanation: s2 is a lambda function that takes a string and returns
it in uppercase. Applying it to 'GeeksforGeeks' gives the result.

Syntax

lambda arguments : expression


 lambda: The keyword to define the function.
 arguments: A comma-separated list of input parameters (like in a
regular function).
 expression: A single expression that is evaluated and returned.
Use Cases of Lambda Functions
Let's see some of the practical uses of the Python lambda function.

1. Using with Condition Checking

A lambda function can include conditions using if statements.


Example 1: Here, the lambda function uses nested if-else logic to
classify numbers as Positive, Negative or Zero.

n = lambda x: "Positive" if x > 0 else "Negative" if x < 0 else "Zero"


print(n(5))
print(n(-3))
print(n(0))

Output
Positive
Negative
Zero
Explanation:
 The lambda function takes x as input.
 It uses nested if-else statements to return "Positive," "Negative,"
or "Zero."
Example 2: This lambda checks divisibility by 2 and returns "Even"
or "Odd" accordingly.

check = lambda x: "Even" if x % 2 == 0 else "Odd"


print(check(4))
print(check(7))

Output
Even
Odd
Explanation:
 The lambda checks if a number is divisible by 2 (x % 2 == 0).
 Returns "Even" for true and "Odd" otherwise.
 This approach is useful for labeling or categorizing values based
on simple conditions.

2. Using with List Comprehension

Combining lambda with list comprehensions enables us to apply


transformations to data in a concise way.
Example: This code creates a list of lambda functions, each
multiplying its input by 10 and then executes them one by one.

li = [lambda arg=x: arg * 10 for x in range(1, 5)]


for i in li:
print(i())

Output
10
20
30
40

Explanation:
 The lambda function multiplies each element by 10.
 The list comprehension iterates through li and applies the lambda
to each element.
 This is ideal for applying transformations to datasets in data
preprocessing or manipulation tasks.

3. Using for Returning Multiple Results

Lambda functions do not allow multiple statements, however, we


can create two lambda functions and then call the other lambda
function as a parameter to the first function.
Example: The lambda calculates both sum and product of two
numbers and returns them as a tuple.

calc = lambda x, y: (x + y, x * y)
res = calc(3, 4)
print(res)

Output
(7, 12)
Explanation:
 The lambda function performs both addition and multiplication
and returns a tuple with both results.
 This is useful for scenarios where multiple calculations need to be
performed and returned together.

4. Using with filter()

The filter() function in Python takes in a function and a list as


arguments. This offers an elegant way to filter out all the elements of
a sequence "sequence", for which the function returns True.
Example: Here, the lambda is used as a filtering condition to keep
only even numbers from the list.

n = [1, 2, 3, 4, 5, 6]
even = filter(lambda x: x % 2 == 0, n)
print(list(even))

Output
[2, 4, 6]
Explanation:
 The lambda function checks if a number is even (x % 2 == 0).
 filter() applies this condition to each element in nums.

5. Using with map()

The map() function in Python takes in a function and a list as an


argument. The function is called with a lambda function and a new
list is returned which contains all the lambda-modified items
returned by that function for each item.
Example: This code doubles each element of the list using a lambda
function and returns a new list.

a = [1, 2, 3, 4]
b = map(lambda x: x * 2, a)
print(list(b))

Output
[2, 4, 6, 8]
Explanation:
 The lambda function doubles each number.
 map() iterates through a and applies the transformation.

6. Using with reduce()


The reduce() function in Python takes in a function and a list as an
argument. The function is called with a lambda function and an
iterable and a new reduced result is returned. This performs a
repetitive operation over the pairs of the iterable. The reduce()
function belongs to the functools module.
Example: Here, the lambda multiplies two numbers at a time and
reduce() applies this across the whole list to calculate the product.

from functools import reduce


a = [1, 2, 3, 4]
b = reduce(lambda x, y: x * y, a)
print(b)

Output
24
Explanation:
 The lambda multiplies two numbers at a time.
 reduce() applies this operation across the list.

Python Assert
Python’s assert statement allows you to write sanity checks in your
code. These checks are known as assertions, and you can use them to
test if certain assumptions remain true while you’re developing your
code. If any of your assertions turn false, it indicates a bug by raising
an AssertionError.

Assertions are a convenient tool for documenting, debugging,


and testing code during development. Once you’ve debugged and
tested your code with the help of assertions, then you can turn them
off to optimize the code for production. You disable assertions by
running Python in optimized mode with the -O or -OO options, or by
setting the PYTHONOPTIMIZE environment variable.

The Syntax of the assert Statement


An assert statement consists of the assert keyword, the expression or
condition to test, and an optional message. The condition is supposed
to always be true. If the assertion condition is true, then nothing
happens, and your program continues its normal execution. On the
other hand, if the condition becomes false, then assert halts the
program by raising an AssertionError.

In Python, assert is a simple statement with the following syntax:

assert expression[, assertion_message]


Here, expression can be any valid Python expression or object, which
is then tested for truthiness. If expression is false, then the statement
throws an AssertionError. The assertion_message parameter is
optional but encouraged. It can hold a string describing the issue that
the statement is supposed to catch.

Here’s how this statement works in practice:

>>> number = 42>>> assert number > 0


>>> number = -42>>> assert number > 0Traceback (most recent call
last): ...AssertionError
With a truthy expression, the assertion succeeds, and nothing
happens. In that case, your program continues its normal execution. In
contrast, a falsy expression makes the assertion fail, raising
an AssertionError and breaking the program’s execution.

To make your assert statements clear to other developers, you should


add a descriptive assertion message:

>>> number = 42>>> assert number > 0, f"number greater than 0


expected, got: {number}"
>>> number = -42>>> assert number > 0, f"number greater than 0
expected, got: {number}"Traceback (most recent call
last): ...AssertionError: number greater than 0 expected, got: -42
The message in this assertion clearly states which condition should be
true and what is making that condition fail. Note that
the assertion_message argument to assert is optional. However, it can
help you better understand the condition under test and figure out the
problem that you’re facing.
So, whenever you use assert, it’s a good idea to use a descriptive
assertion message for the traceback of the AssertionError exception.

An important point regarding the assert syntax is that this


statement doesn’t require a pair of parentheses to group the
expression and the optional message. In Python, assert is a statement
instead of a function. Using a pair of parentheses can lead to
unexpected behaviors.

Python Module is a file that contains built-in functions,


classes,its and variables. There are many Python modules, each
with its specific work.
In this article, we will cover all about Python modules, such as How
to create our own simple module, Import Python modules, From
statements in Python, we can use the alias to rename the module, etc.
What is Python Module
A Python module is a file containing Python definitions and
statements. A module can define functions, classes, and variables. A
module can also include runnable code.
Grouping related code into a module makes the code easier to
understand and use. It also makes the code logically organized.
Create a Python Module
To create a Python module, write the desired code and save that in a
file with .py extension. Let's understand it better with an example:
Example:
Let's create a simple [Link] in which we define two functions,
one add and another subtract.

# A simple module, [Link]


def add(x, y):
return (x+y)

def subtract(x, y):


return (x-y)
Import module in Python
We can import the functions, and classes defined in a module to
another module using the import statement in some other Python
source file.
When the interpreter encounters an import statement, it imports the
module if the module is present in the search path.
Note: A search path is a list of directories that the interpreter
searches for importing a module.
For example, to import the module [Link], we need to put the
following command at the top of the script.

Syntax to Import Module in Python

import module
Note: This does not import the functions or classes directly instead
imports the module only. To access the functions inside the module
the dot(.) operator is used.
Importing modules in Python Example
Now, we are importing the calc that we created earlier to perform add
operation.
# importing module [Link] calc
print([Link](10, 2))
Output:
12
Python Import From Module
Python's from statement lets you import specific attributes from a
module without importing the module as a whole.

Import Specific Attributes from a Python module

Here, we are importing specific sqrt and factorial attributes from the
math module.

# importing sqrt() and factorial from the


# module math
from math import sqrt, factorial

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Output:
4.0
720
Import all Names
The * symbol used with the import statement is used to import all the
names from a module to a current namespace.
Syntax:
from module_name import *

What does import * do in Python?

The use of * has its advantages and disadvantages. If you know exactly
what you will be needing from the module, it is not recommended to
use *, else do so.

# importing sqrt() and factorial from the


# module math
from math import *

# if we simply do "import math", then


# [Link](16) and [Link]()
# are required.
print(sqrt(16))
print(factorial(6))
Output
4.0
720
Locating Python Modules
Whenever a module is imported in Python the interpreter looks for
several locations. First, it will check for the built-in module, if not
found then it looks for a list of directories defined in the [Link].
Python interpreter searches for the module in the following manner -
 First, it searches for the module in the current directory.
 If the module isn’t found in the current directory, Python then
searches each directory in the shell variable PYTHONPATH. The
PYTHONPATH is an environment variable, consisting of a list of
directories.
 If that also fails python checks the installation-dependent list of
directories configured at the time Python is installed.

Directories List for Modules

Here, [Link] is a built-in variable within the sys module. It contains


a list of directories that the interpreter will search for the required
module.

# importing sys module


import sys

# importing [Link]
print([Link])
Output:

You might also like