Conditionals in Python3

Conditional statements are part of every programming language. With conditional statements, we can have code that sometimes runs and at other times does not run, depending on the conditions of the program at that time.

If statement:

We will start with the if statement, which will evaluate whether a statement is true or false, and run code only in the case that the statement is true.

Example:

With this code, we have the variable grade and are giving it the integer value of 70. We are then using the if statement to evaluate whether or not the variable grade is greater than or equal ( >= ) to 65. If it does meet this condition, we are telling the program to print out the string Passing Grade.

Else Statement

It is likely that we will want the program to do something even when an if statement evaluates to false. To do this, we will add an else statement to the grade condition above that is constructed like this:

Since the grade variable above has the value of 60, the if statement evaluates as false, so the program will not print out Passing Grade. The else statement that follows tells the program to print out the other else option, as you can see in the following:

Elif statement

In many cases, we will want a program that evaluates more than two possible outcomes. For this, we will use an elif statement, which is written in Python as elif. The elif or else if statement looks like the if statement and will evaluate another condition.

Let me show you an example for a bank account program:

  • The balance is below 0
  • The balance is equal to 0
  • The balance is above 0

The elif statement, more or less, just adds another option to your condition.

Kommentar hinterlassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

WordPress.com-Logo

Du kommentierst mit Deinem WordPress.com-Konto. Abmelden /  Ändern )

Google Foto

Du kommentierst mit Deinem Google-Konto. Abmelden /  Ändern )

Twitter-Bild

Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )

Facebook-Foto

Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s

Erstelle deine Website auf WordPress.com
Jetzt starten
%d Bloggern gefällt das: