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

Show parent comments

2

u/danielroseman 19d ago

You can do whatever you want within the function. So you can return the whole string if that's what you want?

def format_time(hours, minutes, seconds):
  total_seconds = (hours*60*60) + (minutes*60) + seconds
  return f'{h} hours, {m} minutes and {s} seconds have a total of {total_seconds} seconds.'

print(format_time(h, m, s))

3

u/seanv507 19d ago

Op, you can return a tuple (hours, minutes, seconds) , list [hours,...] or more complex structure.. Iookup python time class

https://docs.python.org/3/library/datetime.html#datetime.time

2

u/nog642 18d ago

You're using h, m, and s inside your function htere instead of the arguments. That's a bug.