Conditionals

  • Affect the sequential flow of control by executing different statements based on the value of a Boolean expression. IF (condition) { }

The code in is executed if the Boolean expression condition evaluates to true; no action is taken if condition evaluates to false.

IF (condition) { } ELSE { }

The code in the first is executed if the Boolean expression condition evaluates to true; otherwise, the code in is executed. Example: Calculate the sum of 2 numbers. If the sum is greater than 10, display 10; otherwise, display the sum. num1 = INPUT num2 = INPUT sum = num1 + num2 IF (sum > 10) { DISPLAY (10) } ELSE { DISPLAY (sum) }

Example

  • Add a variable that represents an age.

  • Add an ‘if’ and ‘print’ function that says “You are an adult” if your age is greater than or equal to 18.

  • Make a function that prints “You are a minor” with the else function.


age = input("age: ")
if int(age) >= 18:
    print("Adult")
else:
    print("Minor")

JavaScript

This is the JS equivalent of the code

let age = prompt("Enter your age:");
if (parseInt(age) >= 18) {
    console.log("Adult");
} else {
    console.log("Minor");
}

Example

  • Make a variable called ‘is_raining’ and set it to ‘True”.

  • Make an if statement that prints “Bring an umbrella!” if it is true

  • Make an else statement that says “The weather is clear”.


is_raining = False
if is_raining:
    print("Bring a umbrella")
else:
    print("The weather is clear")

JavaScript

This is the JS equivalent of the code

let isRaining = false;
if (isRaining) {
    console.log("Bring an umbrella");
} else {
    console.log("The weather is clear");
}

Example

  • Make a function to randomize numbers between 0 and 100 to be assigned to variables a and b using random.randint

  • Print the values of the variables

  • Print the relationship of the variables; a is more than, same as, or less than b


import random


a = random.randint(0,100)
b = random.randint(0,100)
print(a, b)

if a > b:
    print( str(a) + " > " + str(b) )
elif a < b: 
    print( str(a) + " < " + str(b) )
else:
    print( str(a) + " = " + str(b) )


JavaScript

This is the JS equivalent of the code

let a = Math.floor(Math.random() * 101); // Random number between 0 and 100
let b = Math.floor(Math.random() * 101);

console.log(a, b);

if (a > b) {
    console.log(a + " > " + b);
} else if (a < b) {
    console.log(a + " < " + b);
} else {
    console.log(a + " = " + b);
}