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?

Zero Piraeus
  • 56,143
  • 27
  • 150
  • 160

2 Answers2

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.

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
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.

Dillon
  • 106
  • 5