Home > Net >  How do I call back a function in this code?
How do I call back a function in this code?

Time:10-03

I have a task for my Python Course. I have to write a function that calculates the absolute value and returns the absolute value of a number. I was able to get it to work, but it only works when I add the last line, which isn't supposed to be there. I'm not sure how to call the function without that last bit. Any tips?

def absolute(a):
    a = float(input('Enter a positive or negative number: '))
    if a >= 0:
        print ('The absolute value of', a, 'is:', a)
    if a < 0:
        print('The absolute value of', a, 'is:', a*(-1))
              
print ( 'The absolute value of 1 is', absolute(1) )

CodePudding user response:

The last line of your code is what's actually calling the function. Without it, you've defined a function but aren't using it anywhere. The last line is what's actually using the function.

EDIT: if you are meant to be returning the value, you should include a return statement at the end of the function. Right now you're just printing a statement, which isn't returning anything.

CodePudding user response:

Here is an updated version of your code:

def absolute():
    a = float(input('Enter a positive or negative number: '))
    if a >= 0:
        return ('The absolute value of', a, 'is:', a)
    if a < 0:
        return('The absolute value of', a, 'is:', a*(-1))
              

Output:

enter image description here

CodePudding user response:

Your function is doing unnecessary work by asking for input as well as checking whether it is a positive or negative.

My approach:

def absolute(num):
  if num >= 0:
    return num
  else:
    return num * -1

Define another function that will process number provided by the user:

def process_num():
  a = int(input('Please enter a number: '))
  print(f'The absolute value of {a} is {absolute(a)}')

Then, just call the process_num() to run the function.

Pic:

enter image description here

  • Related