UID0
UID0

Reputation: 5

Python: Defined new function but it does not print the result

Python beginner, trying to:

My code looks like this:

number1 = raw_input("Insert number1 = ")
print number1

number2 = raw_input("Insert number2 = ")
print number2

def sumfunction (number1, number2):
   print "Were summing number1 and number2 %d + %d" % (number1, number2)
   return number1 + number2
   print()

I would like something like print sumfunction, or something that will print the result of the function. Currently my code only returns the number1 and number2...

edit: edit in syntax

Upvotes: 0

Views: 453

Answers (3)

code_dredd
code_dredd

Reputation: 6085

Let's go over this step by step.

We can start by change your function to:

def add(number1, number2):
    print "We're summing number1 and number2 %d + %d = %d" % (number1, number2, number1 + number2)

Notice that in this version, you're actually adding the numbers and don't exit prematurely. The numbers must get converted from strings to integers before this function is invoked, and we do that in a moment. In your version, you just return a result but don't get to print.

In addition, you need to invoke your function so that it will do its work, i.e., add(number1, number2)

If we refactor your script a bit, you can get the following:

def add(number1, number2):
    "Only adds the two arguments together and returns the result"
    return number1 + number2

# convert inputs from strings to integers
number1 = int(raw_input("Insert number1 = "))
print number1

# convert inputs from strings to integers
number2 = int(raw_input("Insert number2 = "))
print number2

result = add(number1, number2)
print "The result of %d + %d = %d" % (number1, number2, add(number1, number2))

Notice how the inputs are also converted from strings into actual integers now, so that they get added, instead of concatenated. That is, "2" + "2" = "22" while 2 + 2 = 4.

It's also good practice to wrap your code with the following check:

if __name__ == '__main__':
    # your main code here

So the above can be refactored to:

def add(number1, number2):
    "Only adds the two arguments together and returns the result"
    return number1 + number2

if __name__ == '__main__':
    number1 = int(raw_input("Insert number1 = "))
    print number1

    number2 = int(raw_input("Insert number2 = "))
    print number2

    result = add(number1, number2)
    print "The result of %d + %d = %d" % (number1, number2, add(number1, number2))

This allows the main part of your code to be executed only when the script is invoked directly, but not when it gets imported from another Python script as a module. This check is recommended because in Python, every file is considered a module, i.e. it's legal to say from <yourfile> import add, and you don't want the code that actually tests your add implementation to execute in that case.

Notice also that we've removed the print statements from your add function. This is to make sure your function is doing one and only one thing, i.e. adding the arguments. This makes your function more general and it's easier to re-use your code in other parts, including those where callers don't really want to print anything immediately while calculating something.

This is known as the Single-Responsibility-Principle. Following this principle will allow you to do improve and do better on software design/implementation in the long-term.

I would like something like print sumfunction, or something that will print the result of the function.

Now you can just do the following:

x = 5
y = 10
print add(x, y)

Upvotes: 1

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137398

Change your code to use a main function. It will help you understand the code flow better:

def sumfunction(n1, n2):
   print "Were summing %d + %d" % (n1,   n2)
   return n1 + n2

def input_int(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError:
            print "Invalid input! Please try again."

def main():
    number1 = input_int("Insert number1 = ")
    print number1

    number2 = input_int("Insert number2 = ")
    print number2

    result = sumfunction(number1, number2)
    print "Result: %d" % result

if __name__ == '__main__':
    main()

This is the standard way to write Python scripts. See, when the script runs, it actually executes everything along the way. So we put the __name__ check at the end, to say "okay, the script is loaded, now actually start running it at this predefined point (main)".

I've changed your variable names so you can understand that they are scoped to the function in which they are declared.

I'm also showing how main gets the return value from sumfunction, and stores it to a variable (just like you did with raw_input). Then, I print that variable.

Finally, I've written a function called input_int. As DeepSpace's answer indicated, raw_input returns a string, but you want to work with integers. Do do this, you need to call int on the string returned by raw_input. The problem with this is, it can raise a ValueError exception, if the user enters an invalid integer, like "snake". That's why I catch the error, and ask the user to try again.

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81604

  1. Anything after return statements is not going to be executed.

  2. You defined the function. Now all you need to do is to call it...

    sumfunction(number1, number2)
    
  3. Your function would still not work as you expect it. Since raw_input returns a string, your function will return the numbers concatenated (for the numbers 1 and 2 it would return the string '12' instead of the number 3). You should convert each number to an int (or float):

    number1 = int(raw_input("Insert number1 = "))
    

Upvotes: 1

Related Questions