shivani
shivani

Reputation: 9

Error in finding factorial of 1st n numbers in python

I am new with python and am stuck at an error. I am trying to write a code to find factorial of 1st n numbers and the code is like

n = input ("Enter a number")
num = 1
while n>=0:
    n = num*n
    n = n-1

  print ("factorial of number is:",n)

and the error is

<ipython-input-10-2963b5e3e21e> in <module>()
      1 n = input ("Enter a number")
      2 num = 1
----> 3 while n>=0:
      4     n = num*n
      5     n = n-1

TypeError: '>=' not supported between instances of 'str' and 'int'

please help me to solve this problem.

Upvotes: 1

Views: 60

Answers (2)

Sruthi
Sruthi

Reputation: 3018

The input is read as string, convert it to int

n=int(input ("Enter a number"))

Changes to be made :

  1. Run the loop till 1, not 0
  2. Multiply to store into num every time not n
  3. Print num as answer

Made the changes:

n = int(input ("Enter a number"))
num = 1
while n>0:
    num = num*n
    n = n-1

print ("factorial of number is:",num)

Upvotes: 2

Konstantin
Konstantin

Reputation: 547

You need to redefine you num var, not n.
Here is a code:

n = int(input ('Enter a number\n> '))
num = 1
while n:
    num *= n
    n -= 1

print('factorial of number is:', num)

Upvotes: 0

Related Questions