Python, how to check if a number is odd or even
A number is even when divided by 2 the remainder is 0. Think 2, 4, 10, 200.000.
Odd numbers generate a remainder of 1: 1, 3, 5, 15…
You can check if a number is even or odd with an if
conditional:
num = 3
if (num % 2) == 0:
print('even')
else:
print('odd')
If you have an array of numbers and want to get the ones even or odd, you can use filter()
with a lambda function:
numbers = [1, 2, 3]
even = filter(lambda n: n % 2 == 0, numbers)
odd = filter(lambda n: n % 2 == 1, numbers)
print(list(even)) # [2]
print(list(odd)) # [1,3]
→ Get my Python Handbook
→ Get my Python Handbook
→ I wrote 17 books to help you become a better developer:
- C Handbook
- Command Line Handbook
- CSS Handbook
- Express Handbook
- Git Cheat Sheet
- Go Handbook
- HTML Handbook
- JS Handbook
- Laravel Handbook
- Next.js Handbook
- Node.js Handbook
- PHP Handbook
- Python Handbook
- React Handbook
- SQL Handbook
- Svelte Handbook
- Swift Handbook
Also, JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025