Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Use of if/else Statements in Python Functions | Functions in Python
Introduction to Python
course content

Course Content

Introduction to Python

Introduction to Python

1. First Acquaintance with Python
2. Variables and Types in Python
3. Conditional Statements in Python
4. Other Data Types in Python
5. Loops in Python
6. Functions in Python

book
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.

12345678910
# 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))
copy

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.

Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 6. Chapter 5
We're sorry to hear that something went wrong. What happened?
some-alt