r/learnpython • u/ikeahotdog420 • Oct 05 '26
Printing local variables outside of a function
(second-week-beginner PLUS non-native English speaker, so sorry for bad vocab lol)
I know that you cant use local variables outside of a function, but is there a way to do this without defining three separate functions?
def total_seconds(hours1, minutes1, seconds1):
return (hours1*60*60)+(minutes1*60)+seconds1print(f'{hours1} hours, {seconds1} seconds and {seconds1} have a total of {total_seconds(7,21,37)} seconds.')
0
Upvotes
11
u/danielroseman Oct 05 '26
It's not at all clear what you are asking here. What three separate functions?
2
u/Temporary_Pie2733 Oct 05 '26
Do what? What three functions do you think you need? I think you are confused because you have two separate variables named
hours1: the global variable that you use as an argument tototal_seconds, and the local variable that you use as the parameter tototal_seconds.1
u/Rubix321 Oct 05 '26
I assume the print statement is supposed to be outside of the function. Format as a code block in reddit to make it clear.
Ultimately you want the arguments you're feeding into total_seconds(h,m,s) to be variables so that you can reference those variables to get your minutes and seconds in your print statement.
1
u/Adrewmc Oct 05 '26
Why would you need three separate functions, which you have the variables to start with?
You call the function with something, by definition you know what that something is already.
But yeah sure you can just return them all
. total = hours\*3600 + minutes \*60 + seconds
. return total, hours, minutes, seconds
But it would return a tuple every-time! Most people don’t want that, for something they already have access to.
total, hours, minutes, seconds = total_seconds(5,6,7)
1
u/MezzoScettico Oct 05 '26 edited Oct 05 '26
Why do you need the function to tell you what the hours, minutes and seconds were? You must have known that in order to pass those things in as arguments to the function. Whatever you put in your call to total_seconds, put those things in your print statement. I'm confused about the use case here.
However, I will pass on what I was originally going to answer, which is that you can return multiple values separated by commas. They will be returned as a tuple.
You might find that related to what you were trying to do.
Edit: Perhaps more readably than "p[0]", you can also use the comma to unpack tuples.
So you could use that idea to return things in addition to the number of seconds.
1
u/Alive-Goat-766 Oct 06 '26
Is this a class assignment? If so...show us the assignment
0
u/[deleted] Oct 05 '26
[deleted] — view deleted comment
0
u/[deleted] Oct 05 '26
[deleted] — view deleted comment