Course Content
Introduction to Python
Introduction to Python
Use of if/else Statements in Python Functions
Everything discussed previously can be encapsulated within a function for enhanced efficiency and reusability.
For example, consider the earlier if
/else
statement used to determine whether a number is odd or even. Initially, that code was limited to a specific, predefined number. Evaluating a different number would require either duplicating the entire conditional block or manually altering the number being tested each time.
A more efficient approach involves defining a function that accepts a number as an input parameter. The conditional logic to check for odd or even numbers can then reside within this function, allowing it to be easily called with any number as an argument. This eliminates the need for redundant code or manual edits each time a new number needs to be evaluated.
# Define a function def is_odd(n): if n % 2 == 0: return "even" else: return "odd" # Testing function print('2 is', is_odd(2)) print('3 is', is_odd(3))
Note
A number is considered even if it can be divided by 2 without leaving a remainder. The
%
operator is used to determine this remainder.
Clearly, the function correctly identifies 2
as even and 3
as odd. This function can be invoked repeatedly with different numbers as needed.
Thanks for your feedback!