UID0 UID0 - 1 year ago 57
Python Question

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

Python beginner, trying to:

  • insert two numbers from keyboard

  • create a sum function of the two

  • print that sum function.

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

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

Answer Source

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:
            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__':

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download