我创建了一个简单的代码段,如果数字大于/小于0,则向上和向下计数并显示单词Blastoff。定义函数后,我希望在选择数字但唯一的输出时调用它我收到的是函数ID,就好像它是重复的一样。
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
def countup(n):
if n >= 0:
print('Blastoff!')
else:
print(n)
countup(n+1)
n = int(input('Pick a number from -10 to 10\n'))
if n > 0:
print(countdown)
elif n < 0:
print(countup)
elif n == 0:
print(countup)
这是我运行代码后收到的结果:
Pick a number from -10 to 10
-10
<function countdown at 0x030DA390>
我希望它改为运行计数功能。
我缺少什么?有什么想法吗? 干杯。
答案 0 :(得分:0)
这里的问题是缺少参数。
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
def countup(n):
if n >=0:
print('Blastoff!')
else:
print(n)
countup(n+1)
n = int(input('Pick a number from -10 to 10\n'))
if n > 0:
print(countdown(n))
elif n < 0:
print(countup(n))
elif n == 0:
print(countup(n))
答案 1 :(得分:0)
问题是您没有将argument
传递给方法:
print(countdown)
print(countup)
请注意,应该这样做:
print(countdown(n))
print(countup(n))
还设置了代码格式:
def countdown(n):
if n <= 0:
print('Blastoff!')
else:
print(n)
countdown(n-1)
def countup(n):
if n >= 0:
print('Blastoff!')
exit()
else:
print(n)
countup(n+1)
def user_num(n):
if n > 0:
print(countdown(n))
elif n < 0:
print(countup(n))
elif n == 0:
print(countup(n))
if __name__ == '__main__':
n = int(input('Pick a number from -10 to 10\n'))
user_num(n)
输出:
Pick a number from -10 to 10
-10
-10
-9
-8
-7
-6
-5
-4
-3
-2
-1
Blastoff!
Process finished with exit code 0