Recap: Data Types, Operators and Formatted Output

35 min read Python Recap and Nested Decisions

This is a free course. Log in to run the code exercises and track your progress.

Recap: Data Types, Operators and Formatted Output

In Class 9 you met the basic data types (int, float, str, bool), input() with int()/float(), and the arithmetic, relational and logical operators. One more tool makes output tidy: the f-string.

Put f before the quotes and write any expression inside { }. Add :.2f to show a float with two decimals.

name = "Kabir"
weight, height = 50, 1.6
bmi = weight / height ** 2
print(f"{name}'s BMI is {bmi:.1f}")   # Kabir's BMI is 19.5

Remember the precedence rules: height ** 2 is worked out before the division, so no brackets are needed here. round(x, 2) also rounds a number to two decimal places, but an f-string is the usual way to display a fixed number of decimals.

Python exercise

Read a weight in kg and a height in metres from one line and print BMI = followed by the Body Mass Index (weight ÷ height²) with one decimal.

weight, height = map(float, input().split())
bmi = weight / height  # height must be squared
print(f"BMI = {bmi:.1f}")

Log in to edit and run this code.