I am trying to break up some code into smaller subprograms within the same file to make it more modular. This is the code I would like to break up:
def time():
print("This program calculates the number of seconds in a given length of
time.\n")
second = 1
minute = second * 60
hour = minute * 60
day = hour * 24
week = day * 7
number1 = (eval(input("Enter a number of weeks: ")))
calc1 = number1 * week
number2 = (eval(input("Enter a number of days: ")))
calc2 = number2 * day
number3 = (eval(input("Enter a number of hours: ")))
calc3 = number3 * hour
number4 = (eval(input("Enter a number of minutes: ")))
calc4 = number4 * minute
number5 = (eval(input("Enter a number of seconds: ")))
calc5 = number5 * second
sum1 = (calc1 + calc2 + calc3 +calc4 + calc5)
print("\nIn", number1, "week(s),", number2, "day(s),", number3, "hour(s),",
number4, "minute(s), and", number5, "second(s), there are", sum1,
"second(s).")
It works the way I want it to when it's all together, but I'd like to break it up somewhere along the lines of this:
def count():
print("This program calculates the number of seconds in a given length of
time.\n")
second = 1
minute = second * 60
hour = minute * 60
day = hour * 24
week = day * 7
def number():
number1 = (eval(input("Enter a number of weeks: ")))
calc1 = number1 * week
number2 = (eval(input("Enter a number of days: ")))
calc2 = number2 * day
number3 = (eval(input("Enter a number of hours: ")))
calc3 = number3 * hour
number4 = (eval(input("Enter a number of minutes: ")))
calc4 = number4 * minute
number5 = (eval(input("Enter a number of seconds: ")))
calc5 = number5 * second
sum1 = (calc1 + calc2 + calc3 +calc4 + calc5)
def time():
print("This program calculates the number of seconds in a given length of
time.")
count()
number()
print("In,", number1, "weeks,", number2, "days,", number3, "hours,",
number4, "minutes, and", number5, "seconds, there are", sum1,
"seconds.")
time()
The goal is to run time() and have it call count() and number(), so the code for time() isn't as long. (I know the original code isn't that long, but I'm trying to learn how all this works.)
I've had success calling functions within a file before, but only when it was to print a string, and no math was involved. I've tried playing around with parameters and return and googling and even some gnashing of teeth, but to no avail. I keep ending up with errors like this:
Traceback (most recent call last):
File "<pyshell#525>", line 1, in <module>
time()
File "<pyshell#524>", line 4, in time
number()
File "<pyshell#522>", line 3, in number
calc1 = number1 * week
NameError: name 'week' is not defined
I'm new to programming so I'm sure I'm missing something annoyingly simple, but I haven't been able to figure it out on my own and would appreciate any help.