Odd or Even with Modulo

Joined
Mar 29, 2023
Messages
14
Reaction score
1
I am a Python3 beginner and have been trying to get the following code to tell me if a number is odd or even without any luck.
Code:
def is_even(num):
    return num % 2 == 0

Could someone please help an old noob and show him how to get some output from the above code.

Many thanks for any help or advice.
 
Joined
Dec 10, 2022
Messages
107
Reaction score
26
Maybe this will help

Python:
def func(num):
    return 'even' if num % 2 == 0 else 'odd'

for i in range(5):
    print(f'{i} is {func(i)}')


Output
Code:
0 is even
1 is odd
2 is even
3 is odd
4 is even
 
Joined
Jul 4, 2023
Messages
507
Reaction score
63
For the record, you named the function "is_even", so you should expect only information whether "is_even" is even and returns true, or "is_even" is not even and returns false.

trying to get the following code to tell me if a number is odd or even

To make the code more unambiguously readable IMO it should be looks like e.g.:
Python:
def is_even(num):
    return num % 2 == 0
  
def is_odd(num):
    return not num % 2 == 0 

for i in range(6):
    if is_even(i):
        print(f'{i} is even')
      
for i in range(6):     
    if is_odd(i):
        print(f'{i} is odd')

why? ...
Function naming conventions
Using proper names for functions in programming is important because:

  1. Readability: Clear names make code easier to understand.
  2. Maintenance: Easier to update and debug.
  3. Collaboration: Helps team members understand and work with the code.
  4. Reusability: Good names make libraries and APIs more intuitive to use.
  5. Documentation: Improves both automated and manual documentation.
  6. Avoiding Confusion: Reduces ambiguity and errors.
Example:

  • def calc(a, b): vs. def calculate_sum(a, b):
The second name is clearer about the function's purpose.

different scenario
Python:
def is_even_odd(num):
    return num % 2 == 0

for i in range(6):
    print('is', i, 'even', str(is_even_odd(i)))

or some very similar what @menator01 written
Python:
def is_even_odd(num):
    return 'even' if num % 2 == 0 else 'odd'

for i in range(6):
    print(i, 'is', is_even_odd(i))
 
Joined
Sep 21, 2022
Messages
188
Reaction score
26
Naming things is the bane of my existence.

Programming books suggest that the best identifier is short and meaningful.

If anyone has a system that makes short AND meaningful identifiers, I'd be very interested in reading it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,053
Messages
2,570,431
Members
47,075
Latest member
TysonV438

Latest Threads

Top