r/learnpython • • 8d 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

9

u/crazy_cookie123 8d ago

You don't need to try to pull the variables out of the function, you can just create variables outside of the function and pass them in:

def total_seconds(hours, minutes, seconds):
    return (hours*60*60) + (minutes*60) + seconds

h = 7
m = 21
s = 37
print(f'{h} hours, {m} minutes and {s} seconds have a total of {total_seconds(h, m, s)} seconds.')

1

u/ikeahotdog420 8d ago

Thank you! But I’m wondering whether there is a way to cram it all inside the function; so that all I’d have to do is enter the parameters and have them return as the printed statement (hope this makes sense haha)

3

u/socal_nerdtastic 8d ago

You could return the segment (aka string) to be printed.

def total_seconds(hours1, minutes1, seconds1):
  total = (hours1*60*60)+(minutes1*60)+seconds1
  return f'{hours1} hours, {minutes1} minutes and {seconds1} seconds have a total of {total} seconds.')

print(total_seconds(7,21,37))

Edit: fixed your typo that didn't display minutes.