Rahul Ghosh
Rahul Ghosh

Reputation: 21

Basics of defining procedures in Python?

Hey Guys I am pretty new to Python and I am learning this programming language. I am using the Python IDE (GUI) for running all my codes. I have covered till the topic of defining custom procedures. However upon execution it is not giving any output.

Here is my code below. I want to define a procedure for adding two numbers then print the result for any two numbers that I enter.

def sum(a,b):
    print "The Sum Program"
    c = sum(10,14)
    print "If a is "+a+" and b is "+b++ then sum of the them is "+c

What do you think I am doing wrong here?

Upvotes: 1

Views: 29946

Answers (3)

RocketDonkey
RocketDonkey

Reputation: 37269

One thing you may want to try is calling your function something else (since sum is a built-in Python function, as you seem to know since you're using it as well :) ). You could do something like this:

def my_sum(a, b):
    return a + b

print 'The Sum Program'
a = 10
b = 14
c = my_sum(a, b)
print ('If a is ' + str(a) + 
       ' and b is ' + str(b) + 
       ' then the sum of them is ' + str(c))

Note the str()'s - this is used to cast the integers as strings so that they may be joined into the overall string. There are some more elegant ways to do this, but one step at a time :)

Upvotes: 2

f00id
f00id

Reputation: 113

def sum(a, b):
   print "The Sum Program"
   c = a + b
   print "If a is " + str(a) + " and b is " + str(b) + " then the sum of them is " + str(c)

# call it somewhere else with parameters:
sum(10, 14)

You should split IO from computations though.

I recommend Wikibooks on Python. But there are several tutorials out there covering the basics and more.

Upvotes: 0

Cat
Cat

Reputation: 67522

You have created an infinite loop here; within the sum method you call the sum method always.

What you should do is move your print statements outside the sum method. What goes in the sum method is a return statement that returns your sum.

So, your whole program should look like this (EDIT: Added str() calls, thanks @DSM):

# The procedure declaration
def sum(a,b):
    return a+b

# Your output code
print "The Sum Program"
a = 10
b = 14
c = sum(a, b)
print "If a is "+str(a)+" and b is "+str(b)+" then sum of the them is "+str(c)

Upvotes: 6

Related Questions