If statements

You might like to see an example with if statement to understand it better. Try to guess the output, and after that try to run the code.

my_money = 10 # 10 dollars
bonsai_tree_price = 8
if my_money - bonsai_tree_price >= 0:
	print("buy bonsai")
else:
	print('I need more money')

The output is “buy bonsai” because you have more money ($10) than the bonsai price ($8).

Notice that the strings sent in the print functions are marked in a different way: the first is marked using " (double quotes) and the second using ' (single quote). These are 2 different notations with the same result. The closing quote must be the same as the beginning quote.

Before the print functions there is a blank space which sould be kept. To write it, press on Tab key from your keyboard. An alternative is to write 4 spaces. As you can see, python has an indented syntax. Blocks of code should be indented. You’ll get used to it in a short time.

The general syntax of the if-statement (the simplified version):

if {condition}:
	{block of code to execute if the condition was true}
else:
	{block of code to execute if the condition was false}

Blocks of code

A block of code is used to mark more lines of code which are to be executed sequentially. In the most cases, all of these lines are executed.

Usage example:

seller = 5
my_money = 10 # 10 dollars
bonsai_tree_price = 8
if my_money - bonsai_tree_price >= 0:
	print("buy bonsai")
	seller = seller + bonsai_tree_price
	my_money = my_money - bonsai_tree_price 
else:
	print('I need more money')

The first 3 lines after the line with an if are grouped in a block.