0

Regardless of what number I put, It keeps telling me that n is an odd number...

def odd_or_even(n):
    if (n % 1) == 0:
        print('{} is an odd number'.format(n))
    else:
        print('{} is an even number'.format(n))

odd_or_even(2)
Chubee
  • 87
  • 1
  • 8
  • 2
    You mean `n % 2`. You will never have a remainder when dividing by 1. – Carcigenicate Oct 01 '20 at 19:25
  • modulo gives you the remainder, you are using 1, and one goes into `n` n times with 0 remainder regardless of the size of `n`. So it will always yield 0 – Chris Doyle Oct 01 '20 at 19:25
  • You also have it backwards. When it `== 0` it's even. – Barmar Oct 01 '20 at 19:25
  • 3
    You are confusing `n % 1` and `n & 1`. The latter would do what you intended. – Frank Yellin Oct 01 '20 at 19:26
  • @FrankYellin That's true, but then you'd have to say != 0 for odd. – Jackson Oct 01 '20 at 19:32
  • @JacksonTaylor. Actually no. For numbers in Python, zero is false and everything else is true. The poster's original code would work just fine just by replacing `%` with `&`. Of course, I agree with you that including `!= 0` makes the code more readable. – Frank Yellin Oct 01 '20 at 19:41
  • 1
    @FrankYellin, If they were to just change the `%` operator to a `&` then it would be swapped. If `n` were 3 then the statement would equate to `False` and it would print it is an even number. So if they would switch their print statements then you could remove the `!= 0`/`== 0` portion. – Jackson Oct 01 '20 at 19:58
  • Ah. I didn't realize that the code was incorrect in that way, too! Thanks. I was just noting that n%2 gives the same answer as n&1. – Frank Yellin Oct 01 '20 at 20:54

2 Answers2

1

You need to take n % 2, every number equals 0 in modulo 1, since for every x you have x = 1*x + 0.

Also the clauses are flipped (odd means that x % 2 == 1, while even means that x % 2 == 0)

lejlot
  • 64,777
  • 8
  • 131
  • 164
1
def odd_or_even(n):
    if (n % 2) == 0:
        print('{} is an even number'.format(n))
    else:
        print('{} is an odd number'.format(n))

odd_or_even(2)

(n % 1) is going to be 0 for any value n. If a number is even, the value of (n % 2) is 0 otherwise its 1.

dishant makwana
  • 1,029
  • 6
  • 13