Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Round Numbers (Solution)

00:00 To solve this exercise, we need to first ask the user to enter a number by calling the input() function with a prompt message. As you remember, input() always returns a string value, which must be converted to a number before we can do anything useful with it—that is, in the mathematical domain.

00:19 Let’s assume that our user will enter a valid number, which could be either an integer or a floating-point number, so we’ll wrap the resulting value with a call to float().

00:31 Now we can store this number in a variable, for example, called num. I’m going to save the file now and reload it in the Python shell on the left.

00:41 It asks me to enter a number, so I’ll provide the sample value of 5.432 from the exercise instructions. This defines our num variable, which is of type float.

00:55 Our goal is to round the number to two decimal places. Previously, we’ve only formatted the number without changing the number itself. To obtain a new rounded value, we can pass it to the built-in round() function, which truncates the fractional part, leaving only the whole number in front of the decimal point.

01:15 By specifying an optional second argument to the function, we can request how many decimal digits we want to retain. In this case, I want exactly two digits.

01:26 We can now go back to the script and print the output message with the rounded number using an f-string literal.

01:44 Let’s save it and run it again. It’s always a good idea to verify if your program really does what it’s supposed to do. Okay, this is working fine. Let’s try something else. This time I’m going to type a different number, 1.789, which should give me a number rounded up.

02:05 Great. In the next lesson, you’ll tackle a similar exercise, but you’ll practice using a different function.

Become a Member to join the conversation.