How to Check if a Number is Odd or Even in Python
In Python, you can easily check whether a number is odd or even by using the modulus operator (%). A number is considered even if it produces a remainder of 0 when divided by 2. On the other hand, if a number produces a remainder of 1 when divided by 2, it is considered odd.
To check if a number is even or odd using an if
conditional, you can follow these steps:
1 | num = 3 |
In the code snippet above, we assign the value 3 to the variable num
. Using the modulus operator, we calculate the remainder of num
divided by 2. If the remainder is equal to 0, we print “even.” Otherwise, we print “odd.”
If you have an array of numbers and you want to filter out the even or odd numbers, you can use the filter()
function in combination with a lambda function. Here’s an example:
1 | numbers = [1, 2, 3] |
In the code above, we have an array called numbers
containing the values [1, 2, 3]. Using the filter()
function along with lambda functions, we create two separate filtered lists: even
which contains the even numbers and odd
which contains the odd numbers. Finally, we convert the filtered lists into regular lists using the list()
function and print the results.
In conclusion, checking whether a number is odd or even in Python is straightforward. Using the modulus operator (%), you can easily determine the remainder of a number when divided by 2 and decide if it’s odd or even.
tags: [“Python”, “number”, “odd”, “even”]