[Tutor] for loop question

Hugo Arts hugo.yoshi at gmail.com
Wed Jul 4 11:30:05 CEST 2012


On Sun, Jul 1, 2012 at 11:50 PM, Jim <electrical at triad.rr.com> wrote:

> Hello Friends,
> I apologize for being such a bother. This problem has been evading me all
> day. Can you please give me a hint as to why I cannot put the variable
> UpperCaseSentence outside of the for loop?
> I can do it in other instances but not in this one.
> Thank you so much,
> Jim
>
> #Main function.
> def main():
>
>     mySentence = (input("Enter text."))
>
>     mySentenceList = mySentence.split('.')
>
>
>
>     #Call fixCase function. Send it mySentenceList and receive result
>     #and stores result in variable named output.
>     output = fixCase(mySentenceList)
>     print(output)
>
>
>
> def fixCase(myList):
>     #Begin making a loop through the list, using a variable myString
>     for myString in range (len(myList)):
>         tempString = myList[myString] #Store in temporary variable.
>         myList[myString] = tempString[0:1].upper() +
> tempString[1:len(tempString)] #Replace with upper
>         UpperCaseSentence = (myList[myString])
>         print(UpperCaseSentence)
>
>
> #Call main function
> main()
>
>
Exactly in what way are you trying to hoist it outside of the loop? The way
UpperCaseSentence is defined right now, it depends on myString, which
exists only inside the loop. You can't move that out of the loop since
myString won't exist there.

A few other comments:

- tempString[0:1] may be written as tempString[:1]. Similarly,
tempString[1:len(tempString)] may be written as tempString[1:]. In simple
terms, you can leave out part of the slice and it will default to the end
or beginning.
-  You might want to have a look at str.capitalize(). It does exactly what
you need.

HTH,
Hugo
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120704/fc9a39b9/attachment.html>


More information about the Tutor mailing list