I’m just diving into Python and already feeling a little lost &
confused! My question is why would I do code A vs code B below. Code A
is what was shown in the course, but Code B seems easier and gives the
same result? So essentially, why put the hours, minutes, seconds =
convert_seconds(x) and then printing that, instead of just going
straight to convert_seconds(x) which returns the same thing (with
I think you’re confusing the return value from the function
convert_seconds) with the printing of the value.
I expect you’re running the code directly in some interactive
environment. For example, here’s me doing the same in the Python
Python 3.10.6 (main, Aug 11 2022, 13:47:18) [Clang 12.0.0
(clang-122.214.171.124)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def convert_seconds(seconds):
... hours = seconds//3600
... minutes = (seconds - hours * 3600)//60
... remaining_seconds = seconds - hours * 3600 - minutes * 60
... return hours, minutes, remaining_seconds
>>> hours, minutes, seconds = convert_seconds(5000)
>>> print (hours, minutes, seconds)
1 23 20
(1, 23, 20)
I don’t see any
>>> prompts in your examples, but in the above, Python
is prompting me for input at the
>>> primary prompt and the
continuation prompt (for more lines of an incomplete thing, like the
At the interactive prompt, if a line of code is an expression and that
expression does not evaluate to
None, Python prints the value for you.
In a script, that doesn’t happen; it is purely a convenience thing to
make the interactive prompt useful.
In a script you’d use this:
hours, minutes, seconds = convert_seconds(5000)
so that you could use the values in
hours etc conveniently for further
work. Because that is an assignment, the interactive mode doesn’t
display anything, and you need a subsequent
print() call to see the
values. Or you could just enter the variable names as expressions to
see their values:
>>> hours, minutes, seconds
(1, 23, 20)
So the short answer is: in a programme you’ve usually store the return
from the function in some variables so that you can use those values
Interctively, do whatever is expedient.
(The part of the course is about returning values, if that matters) (And I hope I did this right so the code looks right!)
The code fences look fine.
Cameron Simpson email@example.com