Nupur Singh
Nupur Singh

Reputation: 1

Indentation error in Python Program

My code is -

def factorial(number):

result = 1

while number > 0:

result = result*number

number = number- 1

return result

in_variable = input("Enter a number to calculate the factorial of")

print factorial(in_variable)

I am getting an indentation error on line :

number = number- 1

My error is: Unexpected indent

Why is that?

Regards,

Nupur

Upvotes: 0

Views: 228

Answers (3)

selcuk yalcin
selcuk yalcin

Reputation: 1

If you are not sure your indention str of int. You can easily check it with type(in_variable) and if it is str, you should change it to int with in_variable = int(input("Enter a number to calculate the factorial of"))

def factorial(number):
result = 1
while number > 0:
    result = result*number
    number = number- 1
return result

in_variable = input("Enter a number to calculate the factorial of")

Upvotes: 0

Oliver W.
Oliver W.

Reputation: 13459

The code you've posted shows no indentation at all. Remember, for Python, indentation matters.

After indenting your code, you are still facing two bugs:

  1. you are using input, which means you are using Python3 OR you should have been using raw_input. See this discussion, which explains the difference very well. If you are using Python3, then it's not correct to use the print statement: you should be using the print function. If you're using Python2, you should be using raw_input.
  2. Your function, factorial, expects a number, yet you are passing it a string (which is the return value of raw_input and input). Convert to int first.

This code is properly indented and works on Python3. Use raw_input rather than input if you're working with Python2.

def factorial(number):
    result = 1
    while number > 0:
        result = result*number
        number = number- 1
    return result

in_variable = input("Enter a number to calculate the factorial of")

print(factorial(int(in_variable)))

Upvotes: 2

Jign
Jign

Reputation: 149

def factorial(number):

    result = 1

    while number > 0:

       result = result * number

       number = number- 1

    return result
in_variable = int(input("Enter a number to calculate the factorial of"))

print(factorial(in_variable))

You need to convert the input from str to int.

Upvotes: 0

Related Questions