-3

I am trying to make a dice game and I want to make it so it will detect if the number on the dice is odd or even. This is what I tried and it didn't work.

from random import randrange

import random

import time

Even = [2, 4, 6]

Odd = [1, 3, 5]

x = random.randint(1, 6)

print("Rolling Dice...")

print("Your number is...." + str(x))

if str(x) == Even:

  print("It is an Even number!")

if str(x) == Odd:

  print("It is an Odd number!")

I need to know how to do the if statments and to make it detect if it's even or odd.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
RichardT
  • 3
  • 2
  • 1
    Possible duplicate of https://stackoverflow.com/questions/21837208/check-if-a-number-is-odd-or-even-in-python – sla3k Nov 20 '18 at 17:33
  • 2
    Just use a modulo 2 `if something % 2 == 0 # this is even` and check for the remainder. Odd numbers will have the remainder 1 and even numbers zero. – Dennis Kuypers Nov 20 '18 at 17:35

3 Answers3

1

For checking number being odd or even, you may not need the Even, Odd lists, you might check out the following code:

from random import randrange

import random

import time

x = random.randint(1, 6)

print("Rolling Dice...")

time.sleep(2)

print("Your number is....{}".format(x))

if x % 2 == 0:

  print("It is an Even number!")

else:

  print("It is an Odd number!")
Preetkaran Singh
  • 502
  • 5
  • 19
0

if x % 2 == 0: print("It is an Even number!") else: print("It is an Odd number!")

Dharmesh Fumakiya
  • 2,276
  • 2
  • 11
  • 17
0

You can do this efficiently if you use the AND/& (rather than the Modulo / % operator as seen here. You can also skip the == 0 and consolidate your printing.

from random import randrange

import random
import time

x = random.randint(1, 6)
print("Rolling Dice...")
time.sleep(2)

print("Your number is....{}\nIt is an {} number!".format(x, "Odd" if x & 1 else "Even"))

If you use that bitwise AND operator (x & 1), your code completes in far less machine cycles as a division does not occur. By removing the check == 0, you are, in theory, not loading the constant value of zero to check if zero. Instead the register flags can be used, this is far faster if cycling thru many numbers to test even or odd. Furthermore, the code can be reduced to a less-readable-but-more-efficient form. If you want this simpler, you can use the longer form:

if x & 1:
    print("It is an Odd number!")
else:
    print("It is an Even number!")
codeaperature
  • 1,089
  • 2
  • 10
  • 25