The if statement
The easiest method for making a decision in Python is by using the if statement. The if statement enables you to select the actions to perform if the evaluated condition is true. The syntax of the if statement is:
if condition: statements
As you can see, the if statement begins with the word if. After the if keyword comes a condition that will be evaluated. The condition must end with a colon (:). After the condition come the statements that will be perfomed if the condition evaluates to true. Note that the text indentation is important in if statements and affects the meaning of code, so make sure to indent the statements.
Consider the following example:
x = 5 if x == 5: print ('Hello world!')
In the example above the value of x is set to 5. The if statement will evaluate whether the x = 5 and print Hello world! if the condition is evaluated to true. Because x indeed is 5, the text Hello world! will be printed.
Here is another example:
x = 5 if x == 6: print ('Hello world!')
In the example above the text will not be printed because x is not equal to 6.
One more example:
myName = 'Mark' if myName == 'Mark': print ('Hi Mark!')
In this case, the text Hi Mark! will be printed because the variable myName indeed holds the string Mark:
>>> Hi Mark! >>>