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 a number as input from the user (float).
- Takes the number of decimal places to round to (integer).
- Outputs the rounded number.
Cheat sheet
The round() function rounds numbers to the nearest value:
round(number, ndigits)number: The value to roundndigits: Decimal places to keep (optional)
print(round(4.567)) # 5
print(round(4.567, 2)) # 4.57
print(round(456.78, -1)) # 460Python rounds halfway cases to the nearest even number (banker's rounding):
print(round(2.5)) # 2 (rounds down — 2 is even)
print(round(3.5)) # 4 (rounds up — 4 is even)Try it yourself
# Write code hereThis 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