Skip to the content.

Lessons 3.6 Hacks

3.6

Popcorn Hacks

3.6.1 Conditionals in Python

Hack 1

What would happen if you added more temperature ranges (like ‘warm’ for temperatures between 60 and 79 degrees)? How would you modify the code to implement this feature?”

# Step 1: Add a variable that represents temperature
temperature = 50  # You can change this value to test different conditions

if (72 >= temperature >= 80):
    print("It's a nice warm day out")
if (65>temperature>72):
    print("PEAK TEMP!!!!!!!!")
if (55 >= temperature >= 65):
    print("It's a cool day out")
if (temperature<55):
    print("It's a cold day out")
else:
    print("It's a really hot day out")
It's a cold day out

Instead of just checking for temps above 80, I added ranges for <55, 55-65, 65-72, and 72-80 with different descriptors for all.

3.6.2 Conditionals in JavaScript

Hack 1

How would you change the code to show a message for scores below 60? What would you add?

%%html
<script>
let score = 85;

if (score >= 60) {
    console.log("You passed!");
} else if (0>=score>60){
    console.log("You failed :(")
} else {
    console.log("What did you even do dawg.")
}
</script>

I added a short message for scores under 60 and for negative scores.

Hacks

3.6.3 Conditionals in Python

Hack 1: Odd or Even Checker

Check if a given number is odd or even.

  1. Define a function named check_odd_even that takes one parameter: number.
  2. Use an if statement to check if the number is divisible by 2.
  3. Return “Even” if true; otherwise, return “Odd”.
# sample numbers
number1 = 2
number2 = 7

# define odd/even function
def check_odd_even(number):
    if number % 2 == 0: # checks to see if there is a remainder from division by 2
        return "even"
    else:
        return "odd"

# print results
print(f"{number1} is {check_odd_even(number1)}")
print(f"{number2} is {check_odd_even(number2)}")

2 is even
7 is odd

Alternate hack: Checks the odd/even status of a user-inputted number

# user input
def get_integer():
    try:
        global number3
        number3 = int(input("Please input an integer to test if it is odd or even:"))
    except ValueError:
            print("That is not an integer.")

get_integer()

# define odd/even function
def check_odd_even(number):
    if number % 2 == 0: # checks to see if there is a remainder from division by 2
        return "even"
    else:
        return "odd"

# print results
print(f"{number3} is {check_odd_even(number3)}")
34290480923482 is even

Hack 2: Leap Year Checker

Determine if a given year is a leap year.

  1. Define a function named is_leap_year that takes one parameter: year.
  2. Use an if statement to check if the year is divisible by 4 but not by 100, or divisible by 400.
  3. Return “Leap Year” if true; otherwise, return “Not a Leap Year”.
# test years
year1 = 2000
year2 = 2004

# function to check if a year is a leap year
def is_leap_year(year):
    if year % 400 == 0: # check if divisible by 400
        return "leap year"
    elif year % 100 == 0: # not by 100
        return "not a leap year"
    elif year % 4 == 0: # yes by 4
        return "leap year"
    else:
        return "not a leap year"
    
# print results
print(f"{year1} is a {is_leap_year(year1)}")
print(f"{year2} is a {is_leap_year(year2)}")
         
2000 is a leap year
2004 is a leap year

Alternate hack: Checks a user-inputted year for leap year status

# user input
def get_year():
    try:
        global year3
        year3 = int(input("Please input a year to test if it is a leap year:"))
    except ValueError:
            print("That is not an integer.")

# run above
get_year()

# function to check if a year is a leap year
def is_leap_year(year):
    if year % 400 == 0: # check if divisible by 400
        return "leap year"
    elif year % 100 == 0: # not by 100
        return "not a leap year"
    elif year % 4 == 0: # yes by 4
        return "leap year"
    else:
        return "not a leap year"
    
# print results
print(f"{year3} is {is_leap_year(year3)}")
2006 is not a leap year

Hack 3: Temperature Range Checker

Check if a given temperature is considered cold, warm, or hot.

  1. Define a function named temperature_range that takes one parameter: temperature.
  2. Use if…elif…else statements to categorize the temperature:
    • Return “Cold” for temperatures below 60°F.
    • Return “Warm” for temperatures between 60°F and 80°F.
    • Return “Hot” for temperatures above 85°F.
# test temps
temperature1 = 79
temperature2 = 57

# lay out ranges
def temperature_range(temperature):
    if 60>temperature:
        return "cold"
    elif 60<=temperature<80:
        return "warm"
    elif 80<=temperature: # YES RISHA/VIBHA/AVA/WHOEVER I KNOW THIS IS NOT WHAT THE INSTRUCTIONS SAY
        return "hot"    # BUT YOU LEFT A GAP BETWEEN 80 AND 85 AND IT BOTHERED ME SO BE NICE TO ME PLS
    else:
        return "freezing"
    
# print results
print(f"{temperature1} is {temperature_range(temperature1)}")
print(f"{temperature2} is {temperature_range(temperature2)}")

        
79 is warm
57 is cold

3.6.4 Conditionals in JavaScript

Hack 1: Check Voting Eligibility

Check if a person is eligible to vote based on their age.

  1. Define a function named checkVotingEligibility that takes one parameter called age.
  2. Inside the function, use an if statement to check if the age is 18 or older.
    • Return the message “You are eligible to vote!” if true; otherwise, return “You are not eligible to vote yet.”.
%%html
<script>
// test vars
age1 = 16
age2 = 23
    
function checkVotingEligibility(age){
        if (age>=18){
            return "You are eligible to vote!"
        } else {
            return "You are not eligible to vote yet."
        }
    }

// print results
console.log(`You are ${age1}.`, checkVotingEligibility(age1))
console.log(`You are ${age2}.`, checkVotingEligibility(age2))

</script>

Alternate hack: Check if a person is eligible to vote based on user-inputted age

%%html
<script>
// ask user for age
function getAge() {
    age3 = prompt("Please enter your age:"); // string
    age3 = Number(age3);  // Convert to a number
    // Check if the input isnt int or valid number
    if (!Number.isInteger(age3) || isNaN(age3)) {
        console.log("That is not a valid age.");
    }
}

getAge()

function checkVotingEligibility(age){
    if (age>=18){
        return "You are eligible to vote!"
    } else {
        return "You are not eligible to vote yet."
    }
}

// print results
console.log(`You are ${age3}.`, checkVotingEligibility(age3))

</script>

Hack 2: Grade Calculator

Assign a letter grade based on a numerical score.

  1. Define a function named getGrade that takes one parameter called score.
  2. Use if…else if…else statements to determine the letter grade based on the score:
    • Return “Grade: A” for scores 90 and above.
    • Return “Grade: B” for scores between 80 and 89.
    • Return “Grade: C” for scores between 70 and 79.
    • Return “Grade: F” for scores below 70.
%%html
<script>
// test var
score1 = 93
score2 = 81

// establish ranges
function getGrade(score) {
    if (score >= 90) {
        return "Grade: A";
    } else if (score >= 80 && score < 90) {
        return "Grade: B";
    } else if (score >= 70 && score < 80) {
        return "Grade: C";
    } else {
        return "Grade: F";
    }
}

//print results
console.log(`Score: ${score1}.`, getGrade(score1))
console.log(`Score: ${score2}.`, getGrade(score2))
</script>


<script>
// ask user for score
function getScore() {
    let score3 = prompt("Please enter your score:"); // Get input as a string
    score3 = Number(score3);  // Convert to a number

    // Check if the input is not a valid number or is negative
    if (isNaN(score3) || score3 < 0) {
        console.log("That is not a valid score.");
    }
}

getScore()

function getGrade(score) {
    if (score >= 90) {
        return "Grade: A";
    } else if (score >= 80 && score < 90) {
        return "Grade: B";
    } else if (score >= 70 && score < 80) {
        return "Grade: C";
    } else {
        return "Grade: F";
    }
}

console.log(`Score: ${score3}.`, getGrade(score3))
</script>



#### Hack 3: Temperature Converter

Convert temperatures between Celsius and Fahrenheit.

1. Define a function named convertTemperature that takes two parameters: value (the temperature) and scale (either “C” or “F”).
2. Use an if statement to check the scale:
    - If it’s “C”, convert the temperature to Fahrenheit using the formula (value * 9/5) + 32 and return the result with "°F".
    - If it’s “F”, convert to Celsius using (value - 32) * 5/9 and return the result with "°C".
    - If the scale is neither, return an error message.


```python
%%html
<script>
//test vars
value1 = 89
scale1 = "ºF"
value2 = 23
scale2 = "ºC"


function convertTemperature(value, scale){
    if (scale === "ºC"){
        value = ((value * 9/5) + 32) //convert to f
        scale = "ºF"
    } else if (scale === "ºF") {
        value = ((value - 32) * 5/9) //convert to c
        scale = "ºC"
    } else {
        console.log("Error. Invalid scale")
        return null;
    }
    return `${value.toFixed(2)} ${scale}`; // cut off at 2 decimal points
}

//print statement
console.log(`Original temperature: ${value1}${scale1}. Converted:`, convertTemperature(value1.toFixed(2), scale1))
console.log(`Original temperature: ${value2}${scale2}. Converted:`, convertTemperature(value2.toFixed(2), scale2))


</script>