简体   繁体   English

函数ID使我的条件无法运行

[英]Function id keeps my conditional from running

I created a simple piece of code that counts up and down and display the word Blastoff if the number is bigger/smaller than 0. After defining my function I wanted it to be called when I chose a number but the only output that I receive is the function id as if it was duplicated. 我创建了一个简单的代码,如果数字大于/小于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)

That's the outcome that I receive after I run the code: 那是我运行代码后收到的结果:

Pick a number from -10 to 10
-10
<function countdown at 0x030DA390>

I wanted it to run the countup function instead. 我希望它运行countup函数。

What I'm missing? 我缺少什么? Thoughts? 有什么想法吗? Cheers. 干杯。

The issue here is the missing argument. 这里的问题是缺少论据。

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))

The problem is that you are not passing the argument to the methods: 问题是您没有将argument传递给方法:

print(countdown)
print(countup) 

Notice that it should rather have been: 请注意,它应该是:

print(countdown(n))
print(countup(n))

Formatted the code as well: 格式化代码:

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)

OUTPUT: 输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM