10. Ending Up - Statement Order Question


#1

I wrote my code for this lesson in the following way, where I define all my variables before the if statement. However, I've seen others define the variables inside the if statement. -

pyg = 'ay'

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

However, I do get the correct answer. Could someone please explain to me if the order matters here and I am doing something incorrectly? For example, the code below is what I see other people using -

pyg = 'ay'

original = raw_input('Enter a word:')

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

Thanks for your help!


#2

It would make program sense to test input immediately, so the second example is the way to go. I'm puzzled over the two assignments, though. Why have new_word = ... twice? The second wipes out the first.


#3

Hi @scriptpro64698 ,

Because the code that you posted is not formatted, it is difficult for other users to read and debug it. After code has been pasted into the editing window for posting, you can format it by selecting it, and then by clicking the </> button above the editing area. This will enable us to see important details, such as the indentation and underscores.

In the first example, you process the input before you test to find out whether it contains any characters. If the user happens to enter a word that contains characters, you may not notice a problem, but if the user enters an empty string, your program will crash upon trying to do this ...

first = word[0]

In the second example, you perform the test before processing the data, which is good, but then you have this, before new_word has been defined ...

print new_word

Instead, you should do this ...

print original

Output new_word, after you have completed all of the processing of the data. To test your program, try several cases, including entering an empty string.