'Why am I being asked to defined a variable that already been defined?
I am trying to solve homework problem.
Flesh out the body of the print_seconds function so that it prints the total amount of seconds given the hours, minutes, and seconds function parameters. Remember that there are 3600 seconds in an hour and 60 seconds in a minute.
Here is what I have tried.
def print_seconds(hours, minutes, seconds):
total_seconds = hours * 3600 + minutes * 60 + seconds
print(total_seconds)
print_seconds(1,2,3)
I am getting this error message.
I dont understand why I am getting this error. I defined the variable inside the function.
Solution 1:[1]
You have to indent the 2nd to last line print(total_seconds)
like this, at the moment, it's out of scope.
def print_seconds(hours, minutes, seconds):
total_seconds = hours * 3600 + minutes * 60 + seconds
print(total_seconds)
print_seconds(1,2,3)
Output:
3723
Solution 2:[2]
The reason you are getting an error is because of a scope issue. You need to put the print(total_seconds)
code in the print_seconds()
function, like this:
def print_seconds(hours, minutes, seconds):
total_seconds = hours * 3600 + minutes * 60 + seconds
print(total_seconds)
print_seconds(1,2,3)
Solution 3:[3]
def print_seconds(hours, minutes, seconds):
print(hours * 3600 + minutes * 60 + seconds)
print_seconds(1,2,3)
You can do that like this too without using total_seconds
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | FishingCode |
Solution 2 | |
Solution 3 | Rio Fizen |