Domanda

I have just started learning Python. The problem I am facing is: whenever I use raw_input() outside a function it works fine, but whenever I use raw_input function inside a function like this it gives me an error.

def getinput(cost):
cost=raw_input('Enter a number ')

it gives me an Indentation error

È stato utile?

Soluzione

This error has nothing to do with raw_input. You may, however, want to read about indentation in Python. Many other languages use curly braces such as { and } to show the beginning and the end of a program, or keywords like begin and end. In Python, in contrast, you have to indent the code, like this:

def getinput(cost): 
    cost = raw_input('Enter a number ')

So if you do it without indentation, e.g.

def getinput(cost): 
cost = raw_input('Enter a number ')

...Python would give you an error.

Altri suggerimenti

In Python, "whitespace" makes a difference. The level of indentation is important, and your code will error if you don't indent appropriately. You can read more about Python Whitespace here, but I'll give you a summary.

In Python, when you run your program, it gets passed through what is called an Interpreter, which converts it from the code you can understand into the code that your computer can understand. For Python, this interpreter needs your code to be indented, so it knows how to convert it. Every time you do an if, else, for function or class (among others), you need to increase your indentation.

def getinput(cost):
    cost = raw_input('Enter a number')

The above should work, while the following will not:

def getinput(cost):
cost = raw_input('Enter a number')

Notice how the first example isn't indented. Good luck with learning Python!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top