Functions and Shared Objects
Lesson 22 of 48 in Coddy's Python for C++ Developers course.
Define a Python function with def, a parameter list, and a colon. No return type is required. return sends a value to the caller; reaching the end returns None. C++ by-value vector parameters copy the vector, while a Python parameter is a local name bound to the passed object. Mutating a passed list can affect the caller; rebinding the parameter cannot rebind the caller name. This is neither a C++ vector value copy nor a C++ reference to the caller variable.
C++17 excerpt: inside main
Standard-library headers are supplied in the runnable companion program.
auto twice = [](int value) { return value * 2; };
std::cout << twice(4) << '\n';Python
def twice(value):
return value * 2
print(twice(4))Porting trap
Printing a result is not returning it. The challenge driver needs a return value and owns its own output.
Implement the task below in its editable Python modules. The locked driver.py supplies execution and checks. Keep the specified imports and 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 C++ Developers
1From C++ to Python
Run Your First Python ProgramStreams to printNames, auto, and constDivision and Integer RangeBlocks and Name ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Range Loops and RebindingEntries and enumerateLoop Control Without ++Algorithms and ComprehensionsRecap: Build a Ranking2Values and Decisions
None, nullptr, and boolValues, Addresses, IdentityTruth Tests and OperandsBranches and Value SelectionRecap: Eligibility Rules5Functions, Calls, and Closures
Functions and Shared ObjectsDefaults and Named ArgumentsPacking and Unpacking CallsClosures and Capture TimingRecap: Refactor a Pricing Tool3STL Habits and Python Objects
From vector to listTuples and Structured BindingsMaps, Keys, and OrderingValue Copies and Shared ListsRecap: Clean an Inventory6Errors, Resources, and Modules
Text Input and Exact OutputExceptions and RAIIModules Instead of HeadersHints Are Not Static TypesRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler