Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

I want to write a program that can calculate the factorial of a number. Can I use if-else statements? Something like this:

num = ...

factorial = 1

if num < 0:

   print("must be positive")

elif num == 0:

   print("factorial = 1")

else:

   for i in range(1,num + 1):

       factorial = factorial*i

   print(num, factorial)

And also I want to use the while loop. How can I use that?

1 Answer

0 votes
by (108k points)

You can use the below code for calculating the factorial of the number:

while num > 1:

    factorial = factorial * num

    num = num - 1

If you are a beginner and want to know more about Python, then do refer to the Python certification course.

Related questions

0 votes
1 answer
asked Feb 9, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Nov 18, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Nov 18, 2020 in Python by ashely (50.2k points)
0 votes
1 answer
asked Sep 23, 2019 in Python by Sammy (47.6k points)

Browse Categories

...