For x in range(y) does not return right

Asked

Viewed 70 times

0

I have a problem with a def x() in python. the problem is "inside" it. Even if I put it right, it returns Isis, no matter.

I’ve tried everything but I can’t figure out why he doesn’t return right.

Here comes the code.

def filters(a, b, c):
    for a in range(1, 1):
    d = "video"
    else:
    d = ""

    for b in range(1, 1):
    e = "&lclk=short"
    else:
    e = ""

    for c in range(1, 1):
    f = "&lclk=hd"
    else:
    f = ""

    i = ("&filters=%s%s%s" % (e, d, f))
    return i

Even if I put Filters(1, 1, 1) it returns only the "elses". Why will it be? Ah detail that if I try to if inside def it speaks "syntax error" :/ ( is python 2.7 )

  • Gives syntax error because of identation perhaps. What is the reason for using the else in the for?

  • Hmm I never thought I’d take it out.

  • Without Else, he ignores whether the variable is in the range (1, 1). I was hasty, sorry.

1 answer

2


He will always enter the else because you don’t have any break.

The Else for for for works as follows, if the condition you want is satisfied, leave with the break, otherwise it will perform the else, whereas the for did not meet your expectations.

In addition, I believe that the else, in that case, be unnecessary, since you only want to repeat an assignment once...

What it looks like you want are ifs and not Fors, I’ll put the code I imagine you want:

def filters(a, b, c):
   if a in range(1, 2):
        d = "video"
   else:
        d = ""

   if b in range(1, 2):
        e = "&lclk=short"
   else:
        e = ""

   if c in range(1, 2):
        f = "&lclk=hd"
   else:
        f = ""

   i = ("&filters=%s%s%s" % (e, d, f))
   return i

I imagine that’s what you want to do. In case you just want a fixed value (and not a list, as in the case of range), replace by the following code:

def filters(a, b, c):
   if a == 1:
        d = "video"
   else:
        d = ""

   if b == 1:
        e = "&lclk=short"
   else:
        e = ""

   if c == 1:
        f = "&lclk=hd"
   else:
        f = ""

   i = ("&filters=%s%s%s" % (e, d, f))
   return i
  • When I use break, it ignores whether the variable is in the range :/ .

  • It’s because you want ifs, no?

  • if(a = 1): Syntaxerror: invalid syntax :/

  • What I want is like a configuration, that with the right parameters comes back something, maybe def isn’t right for this.

  • In the if, the ideal would be to use the ==. If you want fixed values, you can replace the ranges, I thought you were just giving an example...

  • Wow, if x in range() worked! I didn’t know you could do this :p was worth the answer! " typing and learning" hehe.

  • Using only if, it ignores the if or syntax error if it is not " == ".

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.