0

I am running Python 3.6.4 and having trouble with the randint function. In trying to create a simple piece of code to create a random number and for each number, print a different response. My current code reads as follows:

from random import *

test = randint(0, 3)
if test == 0:
        print("Zero")
        if test == 1:
            print("Number One")
            if test == 2:
                print("Number Two")
                if test == 3:
                    print("Number Three")

The only problem is, It will only print something if the randint creates the number zero. So it has a one in 4 chance of printing "Zero", the rest print nothing.

I'm obviously being an idiot and missing something really simple but...

1
  • Check your indentation. Each if should be at the same level, not nested. Commented Feb 9, 2018 at 19:34

3 Answers 3

2
from random import *

test = randint(0, 3)
if test == 0:
        print("Zero")
elif test == 1:
          print("Number One")
elif test == 2:
          print("Number Two")
elif test == 3:
          print("Number Three")

All of your if statements were nested, so if the number wasn't 0 they would never be reached!

Also, while it's not necessary, you can change the subsequent if statements to elif statements. Your code will check each of your if statements, even if you meet the first condition. Using elif will make the code stop checking after/if it meets any of the conditions!

Sign up to request clarification or add additional context in comments.

Comments

0

The problem is if 0 isnt drawn, none of the rest of the code will run; including the other checks. Think about it:

test = randint(0, 3)
#Everything under this, including the other checks
#  will only run if test == 0. 
if test == 0:
    print("Zero") 

    if test == 1:
        print("Number One")

You need to use an elif:

if test == 0:
    print("Zero") 

elif test == 1: # This is checked if the first check fails
    print("Number One")

Comments

0

Yuu want to remove those extra indents and have ALL the if statements at the same indentation level. It would also be nice to use "elif" rather than if.

if test == 0:
    print(0)
elif test == 2:
    print(2)
......
......
else:
    print("junk")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.