-1

I am a beginner who started Python a few days ago. I'm writing a code to study and to get a Factorial. I want to write a code to terminate the program when a negative number is entered (without the break statement), but the code below has not progressed for several hours. I hope you can help me! This code works, but the condition I want to satisfy is not to use break, but to exit the program if a negative number is entered

Code >>

def factorial(n):
    if n == 1:
        return 1
    return n * factorial(n - 1)

while True:
    num = int(input("Enter a number: "))
    if num < 0:
        continue
    print(str(num) + "! =", factorial(num))
Don
  • 16,928
  • 12
  • 63
  • 101
S. User
  • 3
  • 2

1 Answers1

0

Maybe:

num = <any positive number>
while num >= 0:
    ...
Don
  • 16,928
  • 12
  • 63
  • 101
  • got error Traceback (most recent call last): File "python", line 8, in File "python", line 5, in factorial File "python", line 5, in factorial File "python", line 5, in factorial [Previous line repeated 992 more times] File "python", line 3, in factorial RecursionError: maximum recursion depth exceeded in comparison – S. User Sep 06 '17 at 10:33
  • This is an issue on your `factorial` function, probably when n = 0 – Don Sep 06 '17 at 10:53
  • Thank you! By the way, can I leave the continue statement still? – S. User Sep 06 '17 at 11:24
  • @S.User You have to: otherwise it will compute factorial also for that negative number – Don Sep 06 '17 at 11:47