1

I am learning Python right now. I just wanted to know. Is it possible, if you return 3 values from a function can you store them in 3 separate variables?

def convert_second(seconds):
  hours = seconds // 3600
  minutes = (seconds - hours * 3600) // 60
  remaining_seconds = seconds - hours * 3600 - minutes * 60
  return hours, minutes, remaining_seconds

duration = convert_second(5000)
print(duration)
5
  • 1
    You mean hours, minutes, seconds = convert_second(5000)? Commented May 12, 2021 at 18:14
  • FWIW this function doesn't return 3 values. It returns a single tuple Commented May 12, 2021 at 18:16
  • @DeepSpace the single tuple contains 3 values which can be unpacked as above Commented May 12, 2021 at 18:36
  • 1
    @MuhdMairaj A single tuple is still a single value. The function returns a single value. Commented May 12, 2021 at 18:39
  • @DeepSpace Nevermind, i thought you replied to the first comment in this chain. But i see now that you corrected the question Commented May 12, 2021 at 18:51

2 Answers 2

1

It works like this:

def convert_second(seconds):
  hours = seconds // 3600
  minutes = (seconds - hours * 3600) // 60
  remaining_seconds = seconds - hours * 3600 - minutes * 60
  return hours, minutes, remaining_seconds

hours, minutes, remaining_seconds = convert_second(5000)

print(f"{hours= }",f"{minutes= }",f"{remaining_seconds= }")

prints:

hours= 1 minutes= 23 remaining_seconds= 20
Sign up to request clarification or add additional context in comments.

4 Comments

What is this 'f' called inside the print function?
nice example for unpacking. For someone new to python, also look at returning a dict so you could use a single formatted string "hours= {hours} minutes= {minutes} remaining seconds= {remaining_seconds}".format(convert_second(5000))
the leading "f" means it is a formatted string. My previous comment is the old-school way to make a string and calling the formatting function on it. They are equivalent. f-strings are extremely powerful tools.
Yes, it is an fstring, Read more at realpython.com/python-f-strings
1

Yes, it is possible, just use the code below:

def convert_second(seconds):
  hours = seconds // 3600
  minutes = (seconds - hours * 3600) // 60
  remaining_seconds = seconds - hours * 3600 - minutes * 60
  return hours, minutes, remaining_seconds

duration_hours, duration_minutes, duration_seconds = convert_second(5000)
print(duration_hours, duration_minutes, duration_seconds)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.