3

I made a basic randomized program on my Raspberry Pi, and it goes somewhat like this.

import random
print ("Welcome to the PC Expo's new game, PC Dispenser, what will you win?")
WinorLose = random.randint(1, 1000)
if WinorLose <100:
    print ("You won a Nintendo Wii.")
elif WinorLose >200:
    print ("You won a Sony PSP.")
elif WinorLose > 300:
    print ("You won a Nintendo Wii U.")
elif WinorLose > 400:
    print ("You won a Sony PS Vita.")
else:
    print ("Not your lucky day, Try again.")

print ("Thank you for the visit.")

if you cannot tell what it does, it has a chance of giving you a virtual PSP, Wii U, and so on. But all it is doing is printing rather "You win a Sony PSP", or "Not your lucky day, Try again." What is wrong? Any fixes?

2 Answers 2

6

Put the largest number first:

WinorLose = random.randint(1, 1000)
print(WinorLose)
if WinorLose > 400:
    print ("You won a Sony PS Vita.")
elif WinorLose > 300:
    print ("You won a Nintendo Wii U.")
elif WinorLose > 200:
    print ("You won a Sony PSP.")
elif WinorLose < 100:
    print ("You won a Nintendo Wii.")   
else:
    print ("Not your lucky day, Try again.")

if WinorLose is > 400 then it is also > 100 so you would always print the first statement.

You might also want to use an upper and lower bound:

if 400 <= WinorLose < 500:
    print ("You won a Sony PS Vita.")
elif 300 <= WinorLose < 400:
    print("You won a Nintendo Wii U.")
elif 200 <= WinorLose < 300:
    print ("You won a Sony PSP.")
elif  WinorLose < 200:
    print ("You won a Nintendo Wii.")    
else:
    print ("Not your lucky day, Try again.")

Using if 400 <= WinorLose < 500 etc.. would work in any order as we are setting a range with a lower and upper bound so unless WinorLose is in that range the statement would not evaluate to True.

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

Comments

0

I know there's an answer above but I guess it didn't explain why yours didn't work, so I'll point it out to you so you can avoid it next time.

Lets consider where the problem occurs.

elif WinorLose > 200:

This will be true for any numbers greater than 200 so 201..1000 in your case; therefore the if statement has been completed because a condition has been met. This will also be the same for other conditions that followed in your code.

Hope this explains why yours didn't work as expected.

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.