0

Please can someone it well for me, i can't understand it very well

# PROBLEM - ADD ROUND """ Write two functions. The first should round an integer up to the next multiple of 10 if the rightmost digit is 5 or greater, else round it down to the previous multiple of 10. The second function should return the sum of the rounded values of two integers. Sample Output: _____________________________________ Input: Output: | _____________________________________| add_round(7, 4) | 10 | add_round(7, 8) | 20 | add_round(14, 16) | 30 | add_round(15, 15) | 40 | ___________________|_________________| """ def add_round(a, b): return round(a) + round(b) def round(num): return num - (num % 10) + 10 if num % 10 >= 5 else num - (num % 10) print(add_round(14, 16))

21st Apr 2022, 7:06 AM
David Mphande
David Mphande - avatar
3 Antworten
+ 1
The trick is in the return statement of def round. If you write it differently it would be: #round up if num % 10 >= 5: return num - (num % 10) + 10 #round down else: return num - (num % 10) For example 14 % 10 will be 4, so it will do the else branch: 14 - 4 = 10 16 will do the if branch, because 16 % 10 = 6 so: 16 - 6 + 10 = 20
21st Apr 2022, 7:25 AM
Paul
Paul - avatar
+ 3
return num - (num % 10) + 10 if num % 10 >= 5 else num - (num % 10) Can be thought as: if num % 10 >= 5: return num - (num % 10) + 10 else: return num - (num % 10) (num % 10) returns the ones digit so 4 of 14 or 7 of 7. num - (num % 10) rounds down. num - (num % 10) + 10 rounds up.
21st Apr 2022, 7:20 AM
John Wells
John Wells - avatar
+ 1
def round(num) basically says return this if condition is true else return this
21st Apr 2022, 7:22 AM
Raul Ramirez
Raul Ramirez - avatar