Functions and Shared Objects
Lesson 22 of 48 in Coddy's Python for Rust Developers course.
Python def introduces a function, with parameters named in parentheses and an indented body. Use return explicitly: a final expression alone is discarded and falling through returns None. Rust functions declare parameter types and can return a tail expression without a semicolon. Python arguments bind local names to passed objects. Rebinding a parameter does not rebind the caller's name, but mutating a passed list changes that object for every alias. There is no explicit &mut marker.
Rust excerpt inside main
fn twice(value: i32) -> i32 { value * 2 }
println!("{}", twice(4));Python
def twice(value):
return value * 2
print(twice(4))Porting trap
Translating a Rust function that accepts &mut Vec<_> requires documenting mutation, because Python call syntax does not advertise exclusive mutable access.
Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.
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 Rust Developers
1From Rust to Python
Run Your First Python ProgramMacros to printBindings, mut, and ShadowingIntegers and Floor DivisionIndentation and ScopeRecap: Rewrite a Receipt4Iteration and Transformations
Borrowed Iteration to forEntries and enumeratewhile, break, and continueIterators and ComprehensionsRecap: Build a Ranking2Values and Decisions
Option and NoneEquality and Object IdentityTruth Tests and FallbacksIf Expressions and elifRecap: Eligibility Rules5Functions and Closures
Functions and Shared ObjectsNamed Arguments and DefaultsPacking Calls and OptionsClosures and Capture TimingRecap: Refactor a Pricing Tool3Ownership and Collections
Vec to listTuples and DestructuringHashMap to dictClone and Shallow CopiesRecap: Clean an Inventory6Errors and Modules
Text Input and FormattingResult, Exceptions, and withModules and the Main GuardHints Without Borrow CheckingRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler