TypeError: 'int' object is not subscriptable

Hello,

why in the following code, line 14 (the first line of print), I’m getting the TypeError from the title:

users_starting_number = input("Vas pocetni broj: ")
users_ending_number = input("Vas zavrsni broj: ")
our_range = range(int(users_starting_number), int(users_ending_number))
if int(users_starting_number) >= int(users_ending_number):
    print("Vas range nije ispravan.")
even_numbers = 0
odd_numbers = 0
for number in our_range:
    if int(number) % 2 == 0:
        even_numbers += 1
    if int(number) % 2 == 1:
        odd_numbers += 1

print(f"U range-u koji ste naveli, imate ukupno {(even_numbers)} parnih brojeva i {(odd_numbers)} neparnih brojeva."
      f"Prva dva broja koja su parna su brojevi {even_numbers[0]} i {even_numbers[1]}, "
      f"a poslednja 3 neparna su brojevi {odd_numbers[-1]}, {odd_numbers[-2]} i {odd_numbers[-3]}.")

I also tried to convert even numbers and odd numbers to a string but would still get the same error.

Thank you.

1 Like

Hello, @ai-2090.

It appears from your print statement that you are trying to access lists, but you have assigned integers to your variables instead of lists of integers.

Thank you for your answer sir, it helped me to understand the errors on the next 2 lines where I indeed was trying to access something that is not a list in a way of accessing lists, so I changed my code, added 2 lists I need but am still getting the same error, on the same line? Could you please provide some more help:

users_starting_number = input("Vas pocetni broj: ")
users_ending_number = input("Vas zavrsni broj: ")
our_range = range(int(users_starting_number), int(users_ending_number))
if int(users_starting_number) >= int(users_ending_number):
    print("Vas range nije ispravan.")
even_numbers = 0
odd_numbers = 0
list_of_even_numbers = []
list_of_odd_numbers = []
for number in our_range:
    if int(number) % 2 == 0:
        even_numbers += 1
        list_of_even_numbers.append(number)
    if int(number) % 2 == 1:
        odd_numbers += 1
        list_of_odd_numbers.append(number)

print(f"U range-u koji ste naveli, imate ukupno {even_numbers} parnih brojeva i {odd_numbers} neparnih brojeva."
      f"Prva dva broja koja su parna su brojevi {even_numbers[0]} i {even_numbers[1]}, "
      f"a poslednja 3 neparna su brojevi {odd_numbers[-1]}, {odd_numbers[-2]} i {odd_numbers[-3]}.")

What I want to say in the first line of print statement is that in our_range I have even_numbers number of even numbers and odd_numbers of odd numbers, so in this very place I don’t need a list, which is the case in the following 2 lines.

Thank you very much.

Edit: done, I forgot to put the new lists in a print statement, thank you once more!

1 Like

This topic was automatically closed 18 hours after the last reply. New replies are no longer allowed.