Problem-2, Week-3 Assignment

In Question-6, Iam getting different values of v2-v1 when iam using local variable and global variable in question-4. Here is my code:

#2 Recursive Function of factorial

def fact(n):
    if(n==1):
        return(1)
    elif(n>1):
        return n * fact(n-1)    

#3

def ratio(x,n):
    return(x**n/fact(n))
print(ratio(6,3))

#4

def ratio_sum(x,N):
    F = 0
    for i in range(1,N+1):
        F = F + ratio(x,i)
    return(F+1)
print(ratio_sum(2,3))    

#6

p = float(input("Enter the value of p = "))
q = float(input("Enter the value of q = "))
v1 = ratio_sum(x = p,N = 100) * ratio_sum(x = q, N = 100)
v2 = ratio_sum(x = p+q, N = 100)
print(v1,v2, v2-v1)

Now in #4 when i will use global variable, result of #6 will get changed
here is the code:
#4

F = 0
def ratio_sum(x,N):
    global F
    for i in range(1,N+1):
        F = F + ratio(x,i)
    return(F+1)
print(ratio_sum(2,3))  

Now the result of #6 will get changed. Why this is so?

@hardikatri2, Welcome!

I did not get your question. Can you explain this, please?

This is because when you make an assignment to a variable in a scope, that variable becomes local to that scope and shadows any similarly named variable in the outer scope. Since the last statement in ratio_sum assigns a new value to F , the compiler recognizes it as a local variable, then you don’t have to reassign the value of F outside ratio_sum.
you can use this one:-

global F
def ratio_sum(x,N):
    F=0
    for i in range(1,N+1):
        F = F + ratio(x,i)
    return(F+1)
print(ratio_sum(2,3))  

Hey I was trying to write the code for the x^n/n! part.
After writing the factorial program and then using it in the above program it shows factorial is not defined.
Please have a look in the image attached below.https://colab.research.google.com/drive/1Dfqn7lhb2gZGipiRhqsCAg83emUVR7zB?authuser=2#scrollTo=9eWhkXJl55HI

I guess you either had the spelling wrong in function definition, or you missed to run the cell in which function is defined.

Hey thanks @ishvinder it worked.

1 Like

You would have written factorial function… Execute that function first and then execute this code… this should solve the issue…:slightly_smiling_face: :slightly_smiling_face:

Generally this happens when you reconnect and the previous code is not executed