[Tutor] Recursive function

Alan Gauld alan.gauld at btinternet.com
Thu Jul 17 17:10:51 CEST 2008


"vanam" <raghavendra.gv.vanam at gmail.com> wrote

> i am new to programming, i just started writing scripts in python 
> about
> functions.

You need to check the section of your tutorial/book that
discusses loops. That will make your solution much easier.

> characters as input. The problem is i am not getting a runtime 
> error.

Tell us what you are getting (and what you expected), it makes our
job easier if we don't have to guess.

> below is the piece of code:
> #word Hangman
> print "Welcome to the Hangman"
> print
> print
> a = raw_input("enter 1st letter=")
> b = raw_input("enter 2nd letter=")
> c = raw_input("enter 3rd letter=")
> def cmp():

You shouldn't write functions with the same name as builtin
functions. You will not be able to use the builtin one if you do!
cmp() is the builtin Python function for comparing two things.

>    d = (a+b+c);

You could just have read the three letters at once using
raw_input...

>    if (d=='PAN'):
>        print "word" 'd' "is correct"
>    else:
>        print "Try Again"
>        CALL();
> def CALL():
>    cmp();

You don;t need CALL, you could just have called cmp from
inside cmp - this is known as a recursice call and is allowed
in Python. It can be used to create a loop effect here as you
do but it has a limited number of repetitions and is best not
used for that purpose. Instead use the built in looping
constructs in Python "for" or "while"

In your case you probabnly want something like:

d = ""
while d != "PAN":
    # code inserted here
print "Word", d, "is correct"   # only prints when d == PAN

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list