1-11 FYI: declaring multiple variables in a single line


#1

Hey guys,

After researching, I found a one-line way to declare all variables within the function:

pyg= 'ay'
original= raw_input('Enter a word:')

if len(original) > 0 and original.isalpha(): 
    word= original.lower(); first= word[0]; new_word= word[1:len(word)]+ first+ pyg
    print new_word
else: print 'empty'

Also, note that else: does not require an indented next line. Feel free to try it out. It also works for Python 3.x (you'll have to use the print(object) and input(), naturally). Hope it helps.


#2

While that is acceptable it makes it harder to read, if you want a short function then you can do something like this,

MY CODE:

def pig_translator():
    original = raw_input('Enter a word:').lower()
    if original and original.isalpha():
        return original[1:] + original[0] + 'ay'
    else:
        return 'empty'

#3

No need to set variables every time we def function... Awesome! Thank you for sharing :smile:


#4

i tried that and it keeps showing that it did not get printed. why?


#5

@acholakelvin

Just change the return to print or do print(pig_latin()) .


#6

Check proper indentation, syntax and such. If you're doing it in Python shell, check what version it is (Python 3.x print command is different to that of Python 2x.)