简体   繁体   中英

printing a positive or a negative integer, using user input()

I'm trying to use a recursive function to get the users input and print the correct values. the countup function will be executed only if the value of n is negative, the recursive function will then print values staring from the value of n to -1 until reaches 0. the value of n should be given by the user! whichever number the user inputs the program should either call the countup for negative or countdown for positive.

def countdown(n):
     n = int(input('enter number: '))

    if n <= 0:
         print('ok')
    else:
         print(n)
          countdown(n-1)



def countup(n):
    countdown(n)
   if a >= 0:
       print('double ok')
   else:
       print('enter number: ')
           newnumb = input()
           new_int = int(newnumb)
                countup(new_int)


 print(countdown())
 countup()

IIUC, you're trying to create a function that counts from a positive to zero, or from a negative to zero, based on input. If that's what you're looking for, this should do:

def countdown(n):
    for i in range(n+1):
        print(n-i)

def countup(n):
    for i in reversed(range(n,1)):
        print(n-i)


def countit():
    n = int(input('enter number: '))
    if n<=0:
        countup(n)
    else:
        countdown(n)

countit()

Using a function that encompasses both functions works best.

Here's a recursive option:

def count(n):
    print n
    if n<0:
        count(n+1)
    elif n>0:
        count(n-1)

n = int(input('enter number: '))
count(n)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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