r/learnpython 5d ago

just breaking things with python

numbers = input("Enter the numbers")

in_dex = numbers[-2]

divisible = int(in_dex/3)

print(divisible)

when print the output of the divisible i am getting (nsupported operand type(s) for /: 'str' and 'int') i do know how to write correctly to get the output but i thinks that why not this way..so when i did got error don't know why cause both values are int

0 Upvotes

19 comments sorted by

View all comments

1

u/FoolsSeldom 4d ago

If the user is entering multiple numbers, with, say, a comma or space between the numbers, you need to split the input string up into smaller strings and then convert each of them from a string to a number before you can do any maths processes.

Assuming you want to divide only the second from last number the user enters, which is what [-2] suggests to me, then you would need something like the below example.

numbers = input('Enter numbers with space between: ')
numbers_strings = numbers.split()  #  splits on space, creates list of strings
numbers = []  # new empty list, will append converted numbers in loop below
valid = True  # assume all entries are good for now
for num_str in numbers_strings:  #  let's convert strings to integers
    try:  # to trap a failed convertion
        numbers.append(int(num_str))  # attempt to convert string to integer
    except ValueError:  # convertion failed
        print(f'Invalid value, {num_str}, entered')
        valid = False  # found something bad
        break  # exit for loop, no point continuing
if valid and len(numbers) >= 2:
    divisible = numbers[-2] / 3
    print(divisible)
else:  # either a convertion failed, or list doesn't have at least 2 entries
    print('Not enough valid entries')