1.1. Exercises

Quick Questions with Conditionals

time = 150

if time  < 120:
    speed = 'Fast'
elif time < 180:
    speed = 'Average'
else:
    speed = 'Slow'
speed
price = 150

if price > 50:
    expensive = 'moderately'
elif price > 100:
    expensive = 'valuable'
else:
    expensive = 'affordable'
expensive

Will it Run with Conditionals

if price > 100
    expensive = 'valuable'
else
    expensive = 'affordable'
expensive
if price > 50:
expensive = 'moderately'
elif price > 100:
expensive = 'valuable'
else:
expensive = 'affordable'
expensive
if price > 50:
    expensive = 'moderately'
expensive

Coding questions

Instructions:
Running a coding exercise for the first time could take a bit of time for everything to load. Be patient, it could take a few minutes.

When you see ____ in a coding exercise, replace it with what you assume to be the correct code. Run it and see if you obtain the desired output. Submit your code to validate if you were correct.

Make sure you remove the hash (#) symbol in the coding portions of this question. We have commented them so that the line won’t execute and you can test your code after each step.

Creating Conditional Statements

Let’s practice making decisions with conditional statements. We are going to the gym and our exercise plan takes different amounts of reps. let’s make conditional statements that depend on the name of the exercises.

Tasks:

  • Make if, elif, and else statements for the following conditions:
    • if the exercise value is lunges, set an object value named reps to 20.
    • if the exercise value is squats, set reps to 25
    • if the exercise value is burpees, set reps to 15
    • If the exercise value is anything else, set reps to 10.
  • Display the value of reps.
Hint 1
  • Are you using double equal signs (==) to make a conditional statement?
  • Are you using a single if statement and 2 elif statements?
Fully worked solution:


Creating an Inline if/else Statement

Let’s try to make inline conditional statements using if and else. the variable cups_of_tea is the number of cups of tea Ben drank last week.

Tasks:

  • Make an inline if/else statement that satisfies the following conditions:
    • if the data type of cups_of_tea is of type list, then set and object named tea_amount to the sum of the elements.
    • if the data type is anything else, set tea_amount to the string 'cannot sum'.
  • Display the result of tea_amount.
Hint 1
  • To check the data type of cups_of_tea, you can use type(cups_of_tea) == list.
  • Are you using sum() to sum up the elements in a list?
Fully worked solution: