# To say weather number is odd or even

Question:

Current behavior:

Desired behavior

``````code snippet
``````

Hey @sulavsapkota916 welcome to the forums!

Can you please provide a link to the repl? This way it is easier for staff and members of the community to help you!

Also see this guide on how to share your code:

3 Likes

To test whether a number is odd or even, you can use the mathematic â€śmoduloâ€ť (remainder) operation. In python, you can use `if varname%2==0: #Number is even` to test if the number is even.

5 Likes

in python:

``````x = 5
if x % 2:
print("it's odd")
else:
print("it's even")
``````
3 Likes

You can find how many digits are in the number using `len` and then subtract one to get the index of the last digit.

``````number = input("Number? > ")
last = len(number) - 1
``````

and then check if the last digit of the number is 0,2,4,6 or 8

``````if (
number[last] == "0"
or number[last] == "2"
or number[last] == "4"
or number[last] == "6"
or number[last] == "8"
):
print(number, "is even")
else:
print(number, "is odd")
``````
1 Like

This is unorthodox (and also only works on strings) - the most recommended way is to use the modulus operator (which is `%` most of the time) by 2.

``````6 % 2 // 0 - 6 is even
4 % 2 // 0 - 4 is even
9 % 2 // 1 - 9 is odd
``````
5 Likes

True, but that you can just `str()` the number, no?

1 Like

Again, unorthodox. There is no real reason to have to cast it to a string just to see if the number is even if there are better ways that require it to not be a string, but instead just a regular number.

8 Likes

Yes i had another version that first took the number as an int, then cast it as a string to use len. But I just shortened it to this version instead. And I was just offering another method other than using %.

7 posts were split to a new topic: Unusual ways to check whether number is even