Python Conditions and If statements with Examples – Programming Code Examples
General Python

Python Conditions and If statements with Examples2 min read

Conditions are an essential concept in programming.

For example, a variable is positive, another action if this variable is negative, or a third action if the variable is nothing.




As a good example is better than several lines of explanation, here is a clear example of a condition taken in its simplest form.

Python supports the usual logical conditions from mathematics:

  • Equals: a == b
  • Not Equals: a != b
  • Less than: a < b
  • Less than or equal to: a <= b
  • Greater than: a > b
  • Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in “if statements” and loops.

An “if statement” is written by using the if keyword.

Let’s detail this code, line by line:
1. The first line is a comment describing that this is the first test of condition. It is ignored by the interpreter and is only used to inform you about the code that will follow.
2. You should understand this line without any help. We just affect the value 5 to variable a.
3. Here is our conditional test. It consists, in order:
of the keyword if ;
of the condition proper, a> 0, which is easy to read (a list of operators authorized for comparison will be presented below);
the colon,:, which ends the condition and is essential:
Python will look for a syntax error if you omit it.

 

Example:

 

In this example we use two variables, a and b, which are used as part of the if statement to test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33, and so we print to screen that “b is greater than a”.

if, elif,else

The first form of condition that we have just seen is practical but quite incomplete. Consider, for example, a variable a of integer type. We want to do an action if this variable is positive and a di erent action if it is negative. It is possible to obtain this result with the simple form of a condition:

Example:

In this example a is greater than b, so the first condition is not true, also the elif condition is not true, so we go to the else condition and print to screen that “a is greater than b”.

 

Leave a Comment