-3

Am trying to write one factorial program in python, in which if I am giving input values as starting value of 1 and count 5 , it should give 1,2,6,24,120 .. but am facing logic error while executing could some help me where am doing the mistake

def getting_input():
while True:
    try:
        x=int(input("Enter the value:"))
        return x
    except Exception as e:
        print(f"error :{e}")
        continue

class factorial:
def __init__(self):
    self.x = getting_input()
    self.y = getting_input()
def fact(self):
    for i in range(self.x,self.y):
        c=list()
        self.result=1
    while i==0 or i==1:
        return 1
    else:
        return i * fact(i-1)
        self.result=fact(self)
        c.append(self.result)
    d={'factorial': c}
    print(d)
obj=factorial()
obj.fact()

Output:

Enter the value:1
Enter the value:5
Traceback (most recent call last):
 File "C:/Users/Desktop/TOM/f.py", line 27, in <module>
 obj.fact()
File "C:/Users/Desktop/TOM/f.py", line 21, in fact
return i * fact(i-1)
NameError: name 'fact' is not defined

Attachments area

2
  • 2
    Please indent your code well as like you tried it. To call fact method inside the class you may do self.fact() Commented Sep 6, 2020 at 12:37
  • Does this answer your question? Why is instance variable not getting recognized Commented Sep 6, 2020 at 12:41

1 Answer 1

0

You get NameError: name 'fact' is not defined as you should use self. before calling to a method of the class.

This is a mitigation for the code:

  1. Calculate factorial for x with recursion
  2. Calculate factorial from x to y iteratively
def getting_input():
    while True:
        try:
            x=int(input("Enter the value:"))
            return x
        except Exception as e:
            print(f"error :{e}")
            continue

class factorial:
    def __init__(self):
        self.x = getting_input()
        self.y = getting_input()
    def rec_factorial_calculation(self, i):
        if i==0 or i==1:
            return 1
        else:
            return i * self.rec_factorial_calculation(i-1)
    def fact(self):
        last_factorial = self.rec_factorial_calculation(self.x)
        c = [last_factorial]
        for i in range(self.x+1, self.y + 1):
            last_factorial *= i
            c.append(last_factorial)
        d = {'factorial': c}
        print(d)

obj=factorial()
obj.fact()

Output:

Enter the value:1
Enter the value:5
{'factorial': [1, 2, 6, 24, 120]}
Sign up to request clarification or add additional context in comments.

1 Comment

Welcome @SivaguruNathan :) You can mark as solved now

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.