Thinking in Python 🐍
Think Python Exercises
Operations
These are some of the operations you can perform in Python.
2+3 #addition
2-3 #Subtraction
2*3 #Multiplication
2/3 #Division
2**3 #Exponentiation
2//3 #Floor Division
2%3 #Modulus2
Value types
In python there are different types of values, such as integers, floats, and strings.
type(42) # Integer
type(3.14) # Float
type("Hello") # String
type(True) # Boolean
type([1, 2, 3]) # List
type((1, 2, 3)) # Tuple
type({1, 2, 3}) # Set
type({"key": "value"}) # Dictionarydict
Rounding of numbers
Sometimes the python rounds up and sometimes down
round(40.5) # Rounds to 41
round(41.5) # Rounds to 42
round(42.5) # Rounds to 4342
It turns out that Python uses “round half to even” strategy, also known as “bankers’ rounding”. This means that when the number is exactly halfway between two integers, it rounds to the nearest even integer.
Arithmetic operations
The following questions give you a chance to practice writing arithmetic expressions.
- How many seconds are there in 42 minutes 42 seconds?
- How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.
- If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace in seconds per mile?
- What is your average pace in minutes and seconds per mile?
- What is your average speed in miles per hour?
# 1. Seconds in 42 minutes 42 seconds
seconds_in_42_minutes_42_seconds = 42 * 60 + 42
seconds_in_42_minutes_42_seconds
# 2. Miles in 10 kilometers
miles_in_10_kilometers = 10 / 1.61
miles_in_10_kilometers
# 3. Average pace in seconds per mile
average_pace_seconds_per_mile = (42 * 60 + 42) / miles_in_10_kilometers
average_pace_seconds_per_mile
# 4. Average pace in minutes and seconds per mile
average_pace_minutes = average_pace_seconds_per_mile // 60
average_pace_seconds = average_pace_seconds_per_mile % 60
average_pace_minutes, average_pace_seconds
# 5. Average speed in miles per hour
average_speed_miles_per_hour = miles_in_10_kilometers / ((42 * 60 + 42) / 3600)
average_speed_miles_per_hour8.727653570337614