0

Following is my code:

def find_first_occurance(s, c, start=0, end=len(s) ):

    while start<end:
          if s[start] ==c: # whether they are the same or not
              return start
          else:
              start+=1
    return -1

print(find_first_occurance("the days make us happy make us wise","s"))

I got an error, name "s" is not defined.
I kind of understand what is going on. While on the other hand, it would be so nice if this feature was allowed in Python, right?

What do you think? Or did I miss something here?

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
study
  • 333
  • 1
  • 5
  • 16
  • `end=len(s)`? Why would that be allowed? – OneCricketeer Mar 05 '17 at 03:42
  • 1
    The default values for optional arguments are evaluated when the function is defined, not every time it’s run (like in JavaScript). See https://stackoverflow.com/questions/1132941/least-astonishment-and-the-mutable-default-argument for a consequence of this. The idiomatic solution is `end=None` and `if end is None: end = len(s)`. – Ry- Mar 05 '17 at 03:42
  • I agree with @Ryan . While in function definition who would be compile know what will be the length which will come in future. means you are getting len of a string before creating that string. – Muhammad Haseeb Khan Mar 05 '17 at 03:43

1 Answers1

0

s is not defined when you define the function, thus the error.

You can try initialize within the function

def find_first_occurance(s, c, start=0, end=None ):
    if end is None:
        end = len(s)
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245