0
If statement
>>>x=4 >>>x+=5 >>>if x>4 Print("true") If I run this the console say "indentation error" Can't anyone tell me about this I'm new to phython
5 Respostas
+ 8
Writing your code in the interactive mode, although doable, is really cumbersome and might not bring the experience result you expect. You should use a proper IDE for writing your code in Python.
Unlike other languages, Python uses indentation as (sole) syntax rule. Whenever you have a code block, it has to be indented properly, otherwise the code will not run. It is wise to choose one indentation step (PEP8 convention mentions 4 spaces) and stick with it.
+ 2
I'm assuming your code doesn't have the arrows. One of Python's syntax rules is that if blocks have to be indented at least 1 space consistently which means you have to put at least one space before the print code so Python knows it's part of the if block like this...
if x > 4:
print("true")
But since it's only one line you could also do it on one line...
if x > 4: print("true")
You can make it even shorter by doing this because Python prints true or false for you...
print(x > 4)
+ 1
in Python, to include the code 'inside' the if statement so that it only executes when the condition is true, you need to indent the lines:
if x>4:
print ("true") //inside the if
x = 5 // outside the if
You must be consistent with the indentation otherwise it will complain.
Other languages use braces like this
if (x > 4) {
// code
}
Here the indentation is optional, but customary to do as it makes the code more readable. Python latched onto this and thought, hey we don't need the braces, we indent anyway so let's make it part of the language
+ 1
I will not be tired of saying the following. READ THE ERRORS. If there is not any syntax error the error will guide you.
0
but in the variable they say spaces are not allowed then what about that ???🤔🤔