Round Numbers
Part of the Logic & Flow section of Coddy's Python journey — lesson 5 of 78.
The round() function rounds numbers to the nearest value.
round(number, ndigits)number: The value to round.ndigits: Decimal places to keep (optional).
Examples:
print(round(4.567)) # 5
print(round(4.567, 2)) # 4.57
print(round(456.78, -1)) # 460.0Python rounds halfway cases to the nearest even number (banker's rounding):
print(round(2.5)) # 2 (rounds DOWN to even 2)
print(round(3.5)) # 4 (rounds UP to even 4)Challenge
EasyWrite a program that takes two separate inputs from the user and outputs the rounded result:
1. The first input should be a number (float). 2. The second input should be the number of decimal places to round to (integer).
Example:
If the inputs are
1. The first input should be a number (float). 2. The second input should be the number of decimal places to round to (integer).
Example:
If the inputs are
3.14159 and 2, the program should output 3.14.Try it yourself
# Take a float input from the user
# Take an integer input from the user for the number of decimal places
# Print the rounded numberThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter