/

How to Check if a Number is Odd or Even in Python

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
2
3
4
5
num = 3
if (num % 2) == 0:
print('even')
else:
print('odd')

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
2
3
4
5
6
7
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]

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”]