Home > Mobile >  Why I have to assign a variable in this for loop?
Why I have to assign a variable in this for loop?

Time:07-06

Hi today i wanted to iterate with 'for' function and get the error message:

Traceback (most recent call last):
  File "range().py", line 26, in <module>
    div(numbers)
  File "range().py", line 19, in div
    if numbers[i] % 5 == 0:
TypeError: not all arguments converted during string formatting

but really dont know why this is happening. I tried to debug this but unfortunately i don't find the answear why this error message occurs.

Good code:

    for i in range(len(numbers)):
        num = numbers[i]
        if num % 3 == 0:
            numbers[i] = "div3"
        if num % 5 == 0:
            numbers[i] = "div5"
        if num % 3 == 0 and num % 5 == 0:
            numbers[i] = "div35"

Error code (my code):

    for i in range(len(numbers)):
        if numbers[i] % 3 == 0:
            numbers[i] = "div3"
        if numbers[i] % 5 == 0:
            numbers[i] = "div5"
        if numbers[i] % 3 == 0 and numbers[i] % 5 == 0:
            numbers[i] = "div35"

Why when we assign the numbers[i] to a variable 'num' the error don't come up?

CodePudding user response:

The problem is for example for number "3"

    if numbers[i] % 3 == 0:
        numbers[i] = "div3"

so: numbers[i] = "div3" then:

    if numbers[i] % 5 == 0:

wich in code try:

    if "div3" % 5 == 0:

Wich either try to do % operation for string, or try string divide by 5....wich both wont work.

Would Suggest do the If statements in reverse order with elseif

CodePudding user response:

It means numbers[i] is containing string value. to Overcome this issue you can use else if conditions. You need also rearrange conditions.

For Example:-

for i in range(len(numbers)):
    num = numbers[i]
    if num % 3 == 0 and num % 5 == 0:
        numbers[i] = "div35"
    elif num % 3 == 0:
        numbers[i] = "div3"
    elif num % 5 == 0:
        numbers[i] = "div5"
  • Related