0

I'm tring to get output on this to print the append list till 42 element

code:

my_list = []
while True:
    item = input("Enter an item (or 'q' to quit): ")
    if item == 'q':
        break
    my_list.append(item)
    
for item in my_list[:my_list.index(42)]:
    print(item)

output:

Enter an item (or 'q' to quit): 1
Enter an item (or 'q' to quit): 2
Enter an item (or 'q' to quit): 42
Enter an item (or 'q' to quit): 4
Enter an item (or 'q' to quit): q
Traceback (most recent call last):
  File "main.py", line 9, in <module>
    for item in my_list[:my_list.index(42)]:
ValueError: 42 is not in list

it's working on given list

code:

my_list = [1,2,3,42,4]

for item in my_list[:my_list.index(42)]:
    print(item)

output:

1
2
3

I tried using if statement to find 42 but no luck , Thank you in advance for helping

Clasherkasten
  • 488
  • 3
  • 9
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/questions/20449427/how-can-i-read-inputs-as-numbers) – mkrieger1 Jan 22 '23 at 22:14

1 Answers1

1

When you ask an input to a user, the result returned by Python is a string so 42 doesn't exist in the list but '42'. You have to cast the input as int:

my_list.append(int(item))

Output:

Enter an item (or 'q' to quit): 1
Enter an item (or 'q' to quit): 2
Enter an item (or 'q' to quit): 42
Enter an item (or 'q' to quit): 4
Enter an item (or 'q' to quit): q
1
2

Note: my_list = [1, 2, 3, 42, 4] is not equivalent to my_list = ['1', '2', '3', '42', '4']

Obviously, you have to check the user input before:

# Method 1: Exception
try:
    my_list.append(int(item))
except ValueError:
    print('Input must be a number')

# Method 2: If/Else
if item.isdigit():
    my_list.append(int(item))
else:
    print('Input must be a number')
Corralien
  • 109,409
  • 8
  • 28
  • 52