0

I declared variable t1 outside the function but was able to use it without using global keyword but for counta and counto I have to use global why? While using counta and counto without global I'm getting the error : local variable 'counta' referenced before assignment

def countApplesAndOranges(s, t, a, b, apples, oranges):
    counta=0
    counto=0
    for x in range(len(apples)):
        app=a+apples[x]
    
        if app in range(s,t1):
            #global counta
            counta+=1
    for y in range(len(oranges)):
        org=b+oranges[y]
        if org in range (s,t1):
            #global count
            counto+=1
    print(counta,counto, sep="\n")
        

if __name__ == '__main__':
    first_multiple_input = list(map(int,input().rstrip().split()))

    s = first_multiple_input[0]

    t = first_multiple_input[1]

    second_multiple_input = input().rstrip().split()

    a = int(second_multiple_input[0])

    b = int(second_multiple_input[1])

    third_multiple_input = input().rstrip().split()

    m = int(third_multiple_input[0])

    n = int(third_multiple_input[1])

    apples = list(map(int, input().rstrip().split()))

    oranges = list(map(int, input().rstrip().split()))


    from datetime import datetime
    start_time = datetime.now()
    t1=t+1

    countApplesAndOranges(s, t, a, b, apples, oranges)

    end_time=datetime.now()
    duration='Duration:{}'
    print(duration.format(end_time-start_time))
  • 1
    You don't need `global` if you're only reading the variable. Variables become local if you assign them. – Barmar Jun 16 '22 at 19:03
  • Note: almost every time you *call a function* in Python, you are using a global variable. In this code, `countApplesAndOranges` is a global variable, whose value is the function. The `global` keyword is not required because we only use the variable, we do not reassign to it. – Karl Knechtel Jun 16 '22 at 19:06

0 Answers0