Menu Close

Articles

Python: decisions

Making decisions

The most common and maybe the most important statement you need to learn is the decision statement. This is represented in Python using the if  keyword followed by a conditional expression then followed by “:” like in example below:

This is also called multi-deck decision statement because there are several blocks that can be executed in different cases. The default case do not have a condition and will execute if no other case condition is satisfied.

Running program

If you save this code as a file: decision.py and run you will have:

>f:\GitHub\sandbox\snippets>python decision.py

>f:\GitHub\sandbox\snippets>python decision.py

>f:\GitHub\sandbox\snippets>python decision.py

Indentation

Python is using mandatory indentation of 4 spaces.  To exit from decision statement you can start a new statement at the beginning of next row. This will allow the interpretor to distinguish between a blok of code amd other statements.

Conditions

The decision statement is using one or several conditions. A condition is a logical expression or a Boolean expression that returns True or False. In Python an expression that do not return 0 or “” or None it is considered True. You can use decisions to check if an object is initialized or a number has value not equal to 0.

Examples:

Will print:

Notice I’m using assignment statement (single equal) “=” to make a new variable x having initial value == 0.

Logical True and False

Logical values in Python are True = 1 and False ==0. These values are constant and can be used in conditions to make decisions. You can compare a value with a logical constant or assign a value to a variable.

yes

Relation Operators:

To compare numbers we use relation operators:

  • Is equal:   1 == 1
  • Is not equal:  1 != 2
  • Greater then: 2 > 1
  • Less then:  1 < 2
  • Greater then or equal to: 2 >= 2
  • Less the or equal to:  0 <= 1

Logical Operators:

To make other decisions we use keywords:

  • or
  • and
  • not

For example:

 

….

Read next: Repetition