0

Learning python on Codeacademy. This is a simple program for Pig Latin Translator. As the title says, depending on prior inputs(which are intentionally entered incorrect), the function is returning different(first) value instead of latest value as cleared by if else. I tried to put return inside else but as seen in #Reference the local variable isn't returned. Please help.

def string_check():
    name = raw_input("Enter a word")
    if len(name) == 0 or name.isalpha() == False:
        print "Enter a valid word"
        string_check()
    else:
        print name
    return name

print 'Welcome to the Pig Latin Translator!'

# Start coding here!
original = string_check()
print ("Original variable is " +original)
ans = original[1:len(original)] + original[0] + "ay"
print ("Pig Latin word is %s"% (ans))

# Reference
omega = 3
if omega == 3:
    print "Obvious"
    beta = 5
    print beta
print beta

OUTPUT

1: When I entered a blank as first input

Welcome to the Pig Latin Translator!
Enter a word 
Enter a valid word
Enter a word 123
Enter a valid word
Enter a word 123gas
Enter a valid word
Enter a word gas
gas
Original variable is 
Traceback (most recent call last):
File "python", line 15, in <module>
IndexError: string index out of range

2: When I entered first input as 123

Welcome to the Pig Latin Translator!
Enter a word 123
Enter a valid word
Enter a word 
Enter a valid word
Enter a word 123gas
Enter a valid word
Enter a word 
Enter a valid word
Enter a word gas
gas
Original variable is 123
Pig Latin word is 231ay
Obvious
5 
5
None

3. When I enter correct input directly

Welcome to the Pig Latin Translator!
Enter a word gas
gas
Original variable has gas
Pig Latin word is asgay
Obvious
5
5
None
NiharGht
  • 151
  • 5
  • 10
  • Possible duplicate: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – DeepSpace Jul 15 '17 at 08:05

1 Answers1

0

Inside the string_check function you call itself on line 4. The returned result (name) is not captured however. One solution is to replace string_check() on line 4 with name = string_check().

jmd_dk
  • 12,125
  • 9
  • 63
  • 94