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

Break, Continue, Functions, Recursion

The document discusses Python functions and how to define, call and use them. Key points covered include using break and continue statements to control loop flow, defining functions with parameters and return values, using default arguments, recursion by functions calling themselves, and the importance of indentation in Python.

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Break, Continue, Functions, Recursion

The document discusses Python functions and how to define, call and use them. Key points covered include using break and continue statements to control loop flow, defining functions with parameters and return values, using default arguments, recursion by functions calling themselves, and the importance of indentation in Python.

Uploaded by

Aamna Raza
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Using break and continue statements in Python

Programming
Python Programming
Use of break and continue

break and continue statements can alter the flow of a normal loop.

Loops iterate over a block of code until the test expression is false, but sometimes
we wish to terminate the current iteration or even the whole loop without
checking test expression.

The break and continue statements are used in these cases.


break statement
The break statement terminates the loop containing it. Control of the program flows
to the statement immediately after the body of the loop.

If the break statement is inside a nested loop (loop inside another loop), the break
statement will terminate the innermost loop.
Flowchart of break
The working of break statement in for loop and while loop is shown below.
Example:
# Use of break statement inside the loop
for val in "string":
if val == "i":
break
print(val)

print("The end")

Output
s
t
r
The end
Continue statement

The continue statement is used to skip the rest of the code inside a loop for the
current iteration only. Loop does not terminate but continues on with the next
iteration.
Flowchart of continue
The working of continue statement in for and while loop is shown below.
Example:
# Program to show the use of continue statement inside loops
for val in "string":
if val == "i":
continue
print(val)
print("The end")

Output
s
t
r
n
g
The end
pass Statement

The pass statement acts as a placeholder and usually used when there is no need of
code but a statement is still required to make a code syntactically correct.
For example we want to declare a function in our code but we want to implement
that function in future, which means we are not yet ready to write the body of the
function.
In this case we cannot leave the body of function empty as this would raise error
because it is syntactically incorrect, in such cases we can use pass statement which
does nothing but makes the code syntactically correct.
Pass statement vs comment

You may be wondering that a python comment works similar to the pass statement as it
does nothing so we can use comment in place of pass statement. Well, it is not the case,
a comment is not a placeholder and it is completely ignored by the Python interpreter
while on the other hand pass is not ignored by interpreter, it says the interpreter to do
nothing.
Example
If the number is even we are doing nothing and if it is odd then we are displaying the
number.

for num in [20, 11, 9, 66, 4, 89, 44]:


if num%2 == 0:
pass
else:
print(num)
Output:
11
9
89
Other examples:
A function that does nothing(yet), may be implemented in future.

def f(arg):
pass # a function that does nothing (yet)
Functions

A function is a group of related statements that performs a specific task.

Functions help break our program into smaller and modular chunks. As our program
grows larger and larger, functions make it more organized and manageable.

Furthermore, it avoids repetition and makes the code reusable.


Syntax of Function
def function_name(function_parameters):
function_body # Set of Python statements
return # optional return statement

Above shown is a function definition that consists of the following components.


• Keyword def that marks the start of the function header.
• A function name to uniquely identify the function. Function naming follows the same rules
of writing identifiers in Python.
• Parameters (arguments) through which we pass values to a function. They are optional.
• A colon (:) to mark the end of the function header.
• One or more valid python statements that make up the function body. An optional return
statement to return a value from the function.
Calling the function:

# when function doesn't return anything


function_name(parameters)

OR

# when function returns something


# variable is to store the returned value
variable = function_name(parameters)
Significance of Indentation (Space)

Python follows a particular style of indentation to define the code, since Python
functions don't have any explicit begin or end like curly braces to indicate the start
and stop for the function, they have to rely on this indentation.
Here we take a simple example with "print" command. When we write "print"
function right below the def func 1 (): It will show an "indentation error: expected an
indented block".
Now, when you add the indent (space) in front of "print" function, it should print as
expected.
Example:

def greet():
"""This function displays 'Hello World!'""“ #docstring
print('Hello World!')

greet()

Output
Hello World!
By default, all the functions return None if the return statement does not exist.

Example: Calling User-defined Function


val = greet()
print(val)

Output
None
Example:
Here we have a function add() that adds two numbers passed to it as parameters.
Later after function declaration we are calling the function twice in our program to
perform the addition.

def add(num1, num2):


return num1 + num2

sum1 = add(100, 200)


sum2 = add(8, 9)
print(sum1)
print(sum2)
Output:
300
17
Default arguments in Function

Now that we know how to declare and call a function, lets see how can we use the default
arguments.
By using default arguments we can avoid the errors that may arise while calling a function
without passing all the parameters. Lets take an example to understand this:

In this example we have provided the default argument for the second parameter, this
default argument would be used when we do not provide the second parameter while
calling this function.
# default argument for second parameter
def add(num1, num2=1):
return num1 + num2
sum1 = add(100, 200)
sum2 = add(8) # used default argument for
second param
sum3 = add(100) # used default argument for
second param
print(sum1)
print(sum2)
print(sum3)

Output:
300
9
101
Recursion
A function is said to be a recursive if it calls itself. For example, lets say we have a
function abc() and in the body of abc() there is a call to the abc().
# Example of recursion in Python to
# find the factorial of a given number
def factorial(num):
if num == 1:
return 1
else:
return (num * factorial(num - 1))
num = 5
print("Factorial of", num, "is: ", factorial(num))
Output:

Factorial of 5 is: 120


THANK YOU

You might also like