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]


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com

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]


This content originally appeared on flaviocopes.com and was authored by flaviocopes.com


Print Share Comment Cite Upload Translate Updates
APA

flaviocopes.com | Sciencx (2021-01-23T05:00:00+00:00) Python, how to check if a number is odd or even. Retrieved from https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/

MLA
" » Python, how to check if a number is odd or even." flaviocopes.com | Sciencx - Saturday January 23, 2021, https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/
HARVARD
flaviocopes.com | Sciencx Saturday January 23, 2021 » Python, how to check if a number is odd or even., viewed ,<https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/>
VANCOUVER
flaviocopes.com | Sciencx - » Python, how to check if a number is odd or even. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/
CHICAGO
" » Python, how to check if a number is odd or even." flaviocopes.com | Sciencx - Accessed . https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/
IEEE
" » Python, how to check if a number is odd or even." flaviocopes.com | Sciencx [Online]. Available: https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/. [Accessed: ]
rf:citation
» Python, how to check if a number is odd or even | flaviocopes.com | Sciencx | https://www.scien.cx/2021/01/23/python-how-to-check-if-a-number-is-odd-or-even/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.