Why is my code always saying I lost even with the winning numbers?

0
1
Asked By CuriousCoder25 On

Hey everyone! I'm just starting out with coding and I've hit a snag on a small project. I'm trying to create a simple lottery-like program where users can input their numbers and see if they match the winning numbers. However, regardless of whether the input matches the winning numbers, I always get the message 'You lost!'. Here's the code I'm working with:

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

Can anyone help me identify what I'm doing wrong?

3 Answers

Answered By TechieTyler On

Yeah, exactly! `input()` converts the user input into a string, so your comparison is failing because you're comparing a string to a list of integers. You could try something like this:

```python
numbers = list(map(int, input("Enter numbers: ").strip().split(",")))
if numbers == winning_numbers:
print("You won!")
else:
print("You lost!")
```

This way your input gets converted to a list of integers, and then you can compare it.

Answered By NumCruncher On

You're on the right track, but don't forget that even if you fix the string issue, comparing lists in Python checks for the exact order and all elements. If the order of numbers doesn't matter for your lottery logic, consider checking membership instead, like this:

```python
if all(num in winning_numbers for num in numbers):
print("You won!")
```

Answered By CodeWizard92 On

The issue is that when you use `input()`, it returns a string, so if you enter something like "9,0,1,3,2", that’s actually a single string rather than a list of integers. You need to split that string into a list and convert the values to integers for the comparison to work. Try using:

```python
parsedInput = [int(x) for x in numbers.strip().split(",")]
```

Then you can compare `parsedInput` with `winning_numbers`. That should solve your problem!

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.