3.6 Conditionals

An if statement controls the flow of a program by running different code depending on whether a condition is true or false.

An else statement in programming is used to define what should happen when a condition in an if statement is false.

Basic if example…

# Define a variable
x = 10

# Basic if statement
if x > 5:
    print("x is greater than 5")
x is greater than 5

Basic else example…

number = 10

if number > 5:
    print("The number is greater than 5.")
else:
    print("The number is not greater than 5.")
The number is greater than 5.

Example #1

Javascript

%%js

let grade = parseInt(prompt('Enter your grade in the class: '));
if (grade >= 70) {
    console.log('You are passing your class.');
} else {
    console.log('You are failing your class.');
}

Python

grade = 65
if grade>=70:
    print('You are passing your class.')
else:
    print('You are failing your class.')
You are failing your class.
  • This code cell shows a variable named grade which is your grade in a class
  • The grade variable is put through a conditional, which checks its magnitude using bitwise operators.
  • These specific bitwise operators only work with int type variables, so int is necessary.
  • If the first conditional expression returns True, it prints something to the user.
  • If the grade does not meet the first condition, it moves to the final else case, printing a general statement.

Example #2

%%js
let isStudying = true;
if (isStudying) {
    console.log('You will do well on your test.');
} else {
    console.log('You should lock in.');
}
<IPython.core.display.Javascript object>
is_studying = True
if is_studying:
    print('You will do well on you test.')
else:
    print('You should lock in.')
You will do well on you test.
  • This code cell shows the variable is_studying which is holding a boolean value.
  • Next, this variable is put through a conditional
  • When having just the conditional keyword and a variable, it checks if that variable returns a boolean value of True
  • In our situation, the is_studying variable is True
  • The conditional then goes into the directions that it will execute
  • If the is_studying variable was False or any other value, then the conditional would go into the else
  • Once it goes into the else statement, it will execute the directions under it