Conditionals

If/else statements are used to execute different blocks of code based on a condition.

age = 90

if age > 50:
    print("You can't go on the rollercoaster!")
else:
    print("You can ride the rollercoaster@")


You can't go on the rollercoaster!

In python, I set the value of the variable age to 90 and used an if-else conditional to determine if a person can ride a rollercoaster based on their age, so if they are less than 50 years old. If they are lower than 50 years then they can ride the rollercoaster, other wize they cant.

%%js
let age = 90;

// Conditional statement
if (age > 50) {
    console.log("You cant go on the rollercoaster!");
} else {
    console.log("You can go on the rollercoaster!");
}

<IPython.core.display.Javascript object>

In javascript, I set the value of the variable age to 90 and used an if-else conditional to determine if a person can ride a rollercoaster based on their age, so if they are less than 50 years old. If they are lower than 50 years then they can ride the rollercoaster, other wize they cant.

# Get user input for a boolean value
likes_coffee = input("Do you like coffee? (yes/no): ").strip().lower() == 'yes'

# Conditional check using the boolean variable
if likes_coffee:
    print("Great! You love coffee.")
else:
    print("You don't like coffee.")

This Python, I used an input to prompts the user for input and checks whether they like coffee based on their response, based on their response a different statement will be printed, so if they idd like coffee, it would print ‘Great! You love coffee.’

%%js
// Get user input for a boolean value
let likesCoffee = prompt("Do you like coffee? (yes/no)").toLowerCase() === 'yes';

// Conditional check using the boolean variable
if (likesCoffee) {
    console.log("Great! You love coffee.");
} else {
    console.log("You don't like coffee.");
}


<IPython.core.display.Javascript object>

In javascript, I used an input to prompts the user for input and checks whether they like coffee based on their response, based on their response a different statement will be printed, so if they did like coffee, it would print ‘Great! You love coffee.’

# Import the random library
import random

# Simulate rolling a die
dice_roll = random.randint(1, 6)  # Generate a random number between 1 and 6

print(f"You rolled a {dice_roll}.")

# Conditional based on the dice roll
if dice_roll >= 4:
    print("You rolled a high number!")
else:
    print("You rolled a low number.")

The python code is used to roll a die by generating a random number between 1 and 6, then prints the result of the roll, then by using an if else statement, it gives feedback on whether the rolled number is considered “high” (4, 5, or 6) or “low” (1, 2, or 3).

// Generate a random number between 1 and 6 using Math
let diceRoll = Math.floor(Math.random() * 6) + 1;

console.log(`You rolled a ${diceRoll}.`);

// Conditional based on the dice roll
if (diceRoll >= 4) {
    console.log("You rolled a high number!");
} else {
    console.log("You rolled a low number.");
}

The python code is used to roll a die by generating a random number between 1 and 6, then prints the result of the roll, then by using an if else statement, it gives feedback on whether the rolled number is considered “high” (4, 5, or 6) or “low” (1, 2, or 3).But in python randomizing the number is more complex than for javascript, the Math.random gives any number between 0-1 including decimals, then the math.floor rounds the number without any decimals.

# Input age and whether the child has a ball
age = int(input("Enter your age: "))
has_ball = input("Do you have a ball? (yes/no): ").strip().lower()

# Check if the child can join the game based on age and ball ownership
if age >= 5:
    if has_ball == "yes":
        # Determine play group based on age
        group = "younger kids" if age < 8 else "older kids"
        print(f"Great! You can play with the {group}.")
    else:
        print("You need a ball to join the game.")
else:
    print("Sorry, you can't join the game yet. You must be at least 5 years old.")

Using python, I used the code to determine whether a child can join a game based on their age and whether they have a ball. In the input function I used .stip() to make sure there arent any extra spaces, and used the .lower() function to convert all text to lowercase.

# Define a function to ask a question
def ask_question(question, options, correct_answer):
    print(question)
    for i, option in enumerate(options, 1):
        print(f"{i}. {option}")
    
    # Get the user's answer
    answer = int(input("Enter the number of your answer: "))
    
    # Check if the answer is correct
    if options[answer - 1].lower() == correct_answer.lower():
        print("Correct!\n")
        return True
    else:
        print(f"Wrong! The correct answer was '{correct_answer}'.\n")
        return False

# List of questions, options, and correct answers
questions = [
    {
        "question": "What is the capital of France?",
        "options": ["Berlin", "Madrid", "Paris", "Rome"],
        "correct_answer": "Paris"
    },
    {
        "question": "Which planet is known as the Red Planet?",
        "options": ["Earth", "Mars", "Jupiter", "Venus"],
        "correct_answer": "Mars"
    },
    {
        "question": "Which month of the year is National Ice Cream Month?",
        "options": ["June", "July", "August", "May"],
        "correct_answer": "July"
    },
    {
        "question": "What is the largest ocean on Earth?",
        "options": ["Atlantic Ocean", "Indian Ocean", "Pacific Ocean", "Southern Ocean"],
        "correct_answer": "Pacific Ocean"
    },
    {
        "question": "In which year did World War II end?",
        "options": ["1945", "1939", "1942", "1948"],
        "correct_answer": "1945"
    }
]

# Main game function
def quiz_game():
    score = 0
    total_questions = len(questions)
    
    print("Welcome to the General Knowledge Quiz!")
    print("Answer the following 5 questions:\n")
    
    # Loop through each question and ask it
    for q in questions:
        if ask_question(q["question"], q["options"], q["correct_answer"]):
            score += 1

    # Final score
    print(f"Quiz over! Your final score is {score}/{total_questions}.")

# Run the quiz game
if __name__ == "__main__":
    quiz_game()

<IPython.core.display.Javascript object>

This Python program implements a simple quiz game where users answer multiple-choice questions, and the program checks if their answers are correct. The ask_question presents the user with a question and displays possible answer choices, collects the user’s answer, and checks if it’s correct. Then I made a dictionary called questions where each dictionary represents a question, its options, and the correct answer. The quiz_game runs the entire quiz game by asking each question and keeping track of the user’s score, for example it starts the score off at 0 and adds a point if they got the question correct.