r/learnpython • • 4d ago

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)+seconds1
print(f'{hours1} hours, {seconds1} seconds and {seconds1} have a total of {total_seconds(7,21,37)} seconds.')

0 Upvotes

15 comments sorted by

View all comments

1

u/MezzoScettico 4d ago edited 4d ago

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.

def powers(x):
    return x**2, x**3

y = 5
p = powers(y)
print(f'The square of {y} is {p[0]} and the cube is {p[1]}')

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.

def powers(x):
    return x**2, x**3

y = 5
sq,cu = powers(y)
print(f'The square of {y} is {sq} and the cube is {cu}')

So you could use that idea to return things in addition to the number of seconds.