Fall 2024 - P1
Big Idea 3 | .1 | .2 | .3 | .4 | .5 | .6 | .7 | .8 | .10 |
3.6 Mastering Conditionals - Control Program Flow with IF, ELSE, and More
Student led teaching on Conditionals. Learn how conditionals control the flow of a program by executing specific blocks of code under certain conditions.
Conditionals
- Affect the sequential flow of control by executing different statements based on the value of a Boolean expression.
IF (condition)
{
}
The code in
IF (condition)
{
The code in the first
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);
}