Issue
As a Python beginner, I'm facing an issue with the following code intended to convert minutes into hours. I'm encountering a NameError in the code snippet below.
def minutes_to_hours(minutes):
hours = minutes / 60.0
return hours
minutes = int(input("Enter minutes \n"))
minutes_to_hours(minutes)
print(hours)
The code is designed to prompt the user to input minutes and then convert that value into hours. However, when I run the code and input 120, it raises the following error:
Enter minutes
120
Traceback (most recent call last):
File "functions.py", line 11, in <module>
print(hours)
NameError: name 'hours' is not defined
I appreciate any help on what might be causing the error and how to fix it. Thank you!
Solution
"hours" is not defined, because you didn't declare/set "hours" variable!
This is why you getting a NameError because you didn't set the hours value and in minutes_to_hours
If you want to get hours within a def statement, use
def minutes_to_hours(minutes):
global hours
hours = minutes/60.0
#return is not setting a new variable, so this will return None
Correct code:
def minutes_to_hours(minutes):
hours = minutes/60.0
return hours
minutes = int(input("Enter minutes \n"))
hours = minutes_to_hours(minutes)
print(hours)
Answered By - user12066865
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.