I need help with this code please


#1

this is what it is asking for . but i don’t understand

Set new_word equal to the slice from the 1st index all the way to the end of new_word. Use [1:len(new_word)] to do this.

pyg = ‘ay’
word = ‘phil’
original = raw_input(‘Enter a word:’)
first = word[0]
if len(original) > 0 and original.isalpha() or original.lower():
print original
else:
print ‘empty’


#2

This code is trying to take every character after the first character in the string, and store it in the new word. In Python, this can either be accomplished with:

word[1:]

or

word[1:len(new_word)]

Either of these methods will result in the following:

input: "Hello, World"
result: "ello, World"

In context, it is necessary to store every character after the first one in a separate string from the first one, so the first character may be added to the end according to the rules of Pig Latin.

Applying this to piglatin…

pyg = 'ay' #piglatin suffix
original = raw_input('Enter a word: ') #Input... Legacy Python
word = original.lower() #lowercase input - avoids future case issues
if(len(original)> 0 and original.isalpha()): #check for issues first
  first = word[0] #first character of lowercase input
  new_word = word[1:] #rest of the word
  print(new_word+pyg+first) #print the result!
else:
  print("Empty!")

It should be noted that as of Python3, raw_input() should be replaced with input().

In this code snippet, we take our input, translate it to lowercase, check that it isn’t an empty space, check that it has only letters, and then start processing it. If these checks fail, we print “Empty!”.

Inside of our string processing case, we grab the first letter, and store it, then the rest of the word, and store it. Finally, we print out the result: Concatenation of everything past the first word (new_word), the pig latin suffix (pyg), and our first letter (first). Put together, this looks like new_word+pyg+first, or new_word+'ay'+first.


#3

I know it’s just semantics, but it should be “print (new_word+first+pyg)” (without the quotes) to follow the rules of pig latin. Was driving me crazy why it looked incorrect even though it allows it to pass.

Also, shouldn’t it be new_word = word[1:len(word)] (if you’re using the long-form)? Using the above example of word[1:len(new_word)] just gave first letter + pyg. The following worked:

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

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

Whereas the following didn’t:

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

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

#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.