Why Is My Lottery Code Not Working in Python?

0
4
Asked By CuriousCoder42 On

Hey folks! I'm just starting out with coding and I'm stumped with a piece of Python code I wrote. I'm trying to create a lottery where I can input my numbers and check against some winning numbers. However, no matter what winning numbers I input, it keeps telling me 'You lost!'. Here's the code I've been working on:

winning_numbers = [9,0,1,3,2]
numbers = input("Enter numbers: ")
if numbers == winning_numbers:
print("You won!")
else:
print("You lost!")

Can someone help me figure out what's going wrong?

4 Answers

Answered By CodeGuru007 On

Yeah, you can’t compare a string to a list of integers like that. You’ve gotta split your input and convert those splits into integers. Here’s an example:

numbers = input("Enter numbers: ").split(',')
numbers = [int(num) for num in numbers] # Convert to int

Then you can check if `numbers == winning_numbers`. Good luck!

Answered By PopcornPanda99 On

It looks like the issue is with the input you’re providing. When you use `input()`, it returns a string. So if you enter something like '9,0,1,3,2', that’s not the same as the list of integers you have. You need to parse your input into an actual list of integers before comparing it with `winning_numbers`. Try this:

numbers = [int(x) for x in input("Enter numbers: ").split(',')]

Now you can compare it directly with the `winning_numbers` list!

CuriousCoder42 -

Thanks! I’ll give that a try!

Answered By TechieTurtle On

To add onto that, remember to handle the input correctly. If you expect users to enter the numbers separated by commas (like '9,0,1,3,2'), make sure they do that and split it properly! Here’s how you can parse it:

numbers = [int(x) for x in input().split(',')]

This will create a list of integers from their input. Just make sure you check if there are spaces before/after the numbers!

CuriousCoder42 -

Got it! That makes sense. Thanks!

Answered By SyntaxSultan On

Just as a heads up, `==` might not work as you expect if the order of numbers is different. If you want to check for any matches regardless of order, consider using sets:

if set(numbers) == set(winning_numbers):
print("You won!")

That way, it doesn't matter what order the numbers are in.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.