Conditionals

In this section, we'll talk about Conditionals. These will include booleans, and if statements.

Booleans

Booleans are a data type which take on either a True or False value. In Python, any expression we run can be evaluated as True or False. These are important because we often want to know whether we should run a piece of code. 

Expressions

Before we talk about booleans, we need to understand what an expression in Python is. Expressions are representative of a value. They often come equipped with an operator, such as addition, multiplication, etc.​

Example: 2 + 3

Example: 5*14

These examples are math expressions, and they are coupled with an operator, specifically add and multiply. Below are a few common operators and their token in Python.

Booleans

As stated earlier, booleans either hold the value of True or False.

Example: (5+5==11) is False, (5*5>10) is True

Use: Print(5+5==11)

In this example, we printed the boolean value (5+5=11). Since the statement is false, "False" will be printed to the console. Next, we will discuss how these are useful in code.

If, else

If statements are exactly what they sound like. If a statement is true, then we will run a block of code. If the statement is false, we won't run it.

Syntax: 

if(boolean):

     code

else:

     code

If the boolean inside the parenthesis is true, we'll run the code underneath. The else statement will run as long as the boolean is false. Notice that after the if and else statements, the code underneath is indented. In Python, this is necessary for the compiler to understand.

Example:

if(5 + 5 == 10):

     print("great")

else:

     print("uh-oh")

In this example, the boolean in the parenthesis is indeed true, to the program will print "great" to the console. 

 

Exercises:

1. Make an 2 int variables. Print "yes" if the first is larger than the second. 

2. Make 2 String variables. Print "yes" if the second contains the first.