Functions and Shared Lists
Lesson 22 of 48 in Coddy's Python for Kotlin Developers course.
Kotlin fun becomes Python def. A block-bodied Python function needs return to send a value back; falling off the end returns None rather than Kotlin Unit. Both languages can mutate a passed mutable list through a parameter. Kotlin parameters cannot be reassigned; Python parameters are ordinary local names and can be rebound, without changing the caller's binding. Printing is separate from returning.
Kotlin
fun addItem(items: MutableList<Int>) { items.add(9) }
fun main() {
val items = mutableListOf(1)
addItem(items)
println(items.size)
}Python
def add_item(items):
items.append(9)
items = [1]
add_item(items)
print(len(items))Porting trap
Do not port a Kotlin expression-bodied function by leaving an unreturned expression inside a Python def. The driver expects the returned value, not incidental stdout.
Complete the task in its editable modules. The locked driver.py supplies execution; keep the required API names.
Challenge
BeginnerImplement split_minutes(total) for a nonnegative integer. Return a tuple (hours, minutes), where minutes is between 0 and 59. Do not read input or print. A locked driver reads one integer, calls your function, unpacks its result, and prints hours minutes.
Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.
Try it yourself
from functions import split_minutes
hours, minutes = split_minutes(int(input()))
print(hours, minutes)
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Kotlin Developers
1From Kotlin to Python
Run Your First Python ProgramPrint and String TemplatesVal, Var, and Python NamesDivision and Integer WidthSuites and Block ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Ranges and Loop BindingsEntries and withIndexUpdates and Loop ControlCollection PipelinesRecap: Build a Ranking2Values and Decisions
Nullable Types and NoneEquality and IdentityBoolean Conditions and orIf Expressions and ElifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ListsDefaults and Named CallsVararg and Keyword PackingClosures and Lambda ResultsRecap: Refactor a Pricing Tool3Collections and Shared State
Read-only Lists and MutationPair and Tuple UnpackingMap Lookup and Missing KeysShallow Copies and SetsRecap: Clean an Inventory6Input, Errors, and Modules
Console Input and FormattingExceptions and Resource ScopeImports and Entry PointsStatic Types and AnnotationsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler