Functions and Mutable Inputs
Lesson 22 of 48 in Coddy's Python for PHP Developers course.
Python defines functions with def and returns values with return. Falling off the end returns None, comparable to PHP's implicit null result. PHP array parameters normally have value semantics unless declared by reference. Python parameters are local names bound to passed objects: mutating a list can affect its caller, while rebinding the parameter cannot rebind the caller's variable. Printing and returning are separate operations.
PHP 8.3
<?php
function addItem($items) { $items[] = 9; }
$items = [1];
addItem($items);
echo count($items), "\n";Python
def add_item(items):
items.append(9)
items = [1]
add_item(items)
print(len(items))Porting trap
The task driver expects your function's result and handles printing. An echo-style side effect inside the function cannot replace the requested return value.
Complete the task in the editable Python files. Keep the required function and class names; the locked driver.py supplies execution.
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 PHP Developers
1From PHP to Python
Run Your First Python ProgramEcho, Strings, and printVariables Without Dollar SignsDivision and Numeric TextIndentation and SuitesRecap: Rewrite a Receipt4Iteration and Transformations
Foreach and rangeKeys, Items, and enumerateWhile Without IncrementFilters and Sort KeysRecap: Build a Ranking2Values and Decisions
Null, None, and Missing KeysStrict Equality Is Not isThe Zero String TrapElif and Value SelectionRecap: Eligibility Rules5Functions and Closures
Functions and Mutable InputsNamed Calls and Default StateVariadics and Call UnpackingArrow Capture and Late BindingRecap: Refactor a Pricing Tool3Arrays and Python Collections
PHP Arrays and Python ListsDestructuring and TuplesKeys, Null, and getArray Copies and List AliasesRecap: Clean an Inventory6Input, Errors, and Modules
CLI Input and Exact OutputConversion Errors and CleanupImports Instead of requireType Hints Are Not PHP TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler