我试图将一些代码分解为同一文件中的较小子程序,以使其更加模块化。这是我想要分解的代码:
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).")
当它全部在一起时,它的工作方式与我想要的方式相同,但我想在某个方面将其分解:
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()
目标是运行time()并调用count()和number(),因此time()的代码不会那么长。 (我知道原始代码不长,但我正在努力学习这一切是如何工作的。)
之前我已成功调用文件中的函数,但只有在打印字符串时才会成功,并且不涉及数学。我试过玩参数,回归和谷歌搜索甚至咬牙切齿,但无济于事。我最终会遇到这样的错误:
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
我是编程的新手,所以我确信我错过了一些非常简单的东西,但是我无法自己解决这个问题并希望得到任何帮助。
答案 0 :(得分:1)
因此,您需要了解的最重要的事情是范围。在函数内声明变量时,只能在该函数中使用该变量。因此,例如,当您在count函数内部声明一周时,您只能访问变量&#34; week&#34;当你在函数内部时。
如果要从程序内的任何位置访问变量,则需要全局声明它。这是代码的工作版本,其中时间变量是全局声明的。
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 = (int(input("Enter a number of weeks: ")))
calc1 = number1 * week
number2 = (int(input("Enter a number of days: ")))
calc2 = number2 * day
number3 = (int(input("Enter a number of hours: ")))
calc3 = number3 * hour
number4 = (int(input("Enter a number of minutes: ")))
calc4 = number4 * minute
number5 = (int(input("Enter a number of seconds: ")))
calc5 = number5 * second
sum1 = (calc1 + calc2 + calc3 +calc4 + calc5)
print("In,", number1, "weeks,", number2, "days,", number3, "hours,",
number4, "minutes, and", number5, "seconds, there are", sum1,
"seconds.")
def time():
print("This program calculates the number of seconds in a given length of time.")
number()
time()
您需要小心全局变量,因为如果使用太多变量,可能会遇到问题。在尝试编写更复杂的程序之前,我建议阅读this article,它可以很好地解释范围和名称空间在python中的工作方式。
答案 1 :(得分:1)
问题:...在同一个文件中,使其更加模块化
您根本不需要def count()
。
所有values
都是常数,因此应该这样定义
无需一遍又一遍地计算values
。
您可以使其更加模块化,例如:
SECONDS = {'s':1, 'm': 1*60, 'h':60*60, 'd':60*60*24, 'w': 60*60*24*7}
def get_input():
result = {'sum1':0}
for cat in ['weeks', 'days', 'hours', 'minutes', 'seconds']:
value = int( input( "Enter a number of {}: ".format(cat) ))
result[cat] = value
result['sum1'] += SECONDS[ cat[:1] ] * value
return result
def time():
result = get_input()
print("\nIn, {weeks}, week(s), {days}, day(s), {hours}, hour(s),"
" {minutes}, minute(s), and, {seconds} second(s), "
"there are, {sum1} second(s)."\
.format(**result))
if __name__ == '__main__':
print("This program calculates the number of seconds in a given length of time.\n")
time()
通常使用 __main__
入口点是很常见的。
这使您能够从其他python脚本调用def get_input()
。
使用Python测试:3.4.2和2.7.9
答案 2 :(得分:0)
您可以让count
返回dict
,例如:
def count():
times = {'second': 1}
times['minute'] = times['second'] * 60
times['hour'] = times['minute'] * 60
times['day'] = times['hour'] * 24
times['week'] = times['day'] * 7
return times
然后,您可以在count
中致电time
并将其传递给number
:
def time():
...
times = count()
values = number(times)
def number(times):
values = {}
number1 = int(input("Enter a number of weeks: "))
calc1 = number1 * times['week']
values.update({'number1': number1, 'calc1': calc1})
...
sum1 = calc1 + calc2 + calc3 + calc4 + calc5
values['sum1'] = sum1
return values
然后您可以使用从数字返回的字母来填充time