[Tutor] __name__=='__main__'

bob gailer bgailer at gmail.com
Tue Feb 21 01:55:39 CET 2012


No one else has caught another problem. I comment on it below:

On 2/20/2012 6:46 PM, Michael Lewis wrote:
> Hi everyone,
>
> I am having some trouble understanding how to use __name__== 
> '__main__'. Can you please give me some insight? Also, to use this, it 
> needs to be within a function? Do you typically just throw it in your 
> very last function or create a separate function just for this? I at 
> first put it outside and after all my functions but got the error 
> below and then put it inside my last function and the program ran. 
> (side note, I have an error in my return for MultiplyText that I am 
> still trying to work out, so you can ignore that part).
>
> Code:
>
> '''homework 5_1'''
>
> def MultiplyText(text, multiplier):
>     '''Recieve a S. For digits in S, multiply by multiplier and return 
> updated S.'''
>     for num in text:
>         return ''.join(str(int(num) * multiplier) if num.isdigit() 
> else num for num in text)
This will fail, as multiplier is a string.
>
>
> def GetUserInput():
>     '''Get S & multiplier. Test multiplier.isdigit(). Call 
> MultiplyText(text, multiplier)'''
>     while True:
>         text = raw_input('Enter some text: ')
>         multiplier = raw_input('Enter a multiplier: ')
>         try:
>             multiplier.isdigit()
multiplier.isdigit() returns True or False. It will not raise an exception!
>             break
>         except ValueError:
>             continue
>     new_text = MultiplyText(text, multiplier)
>     return new_text
>
>     if __name == '__main__':
>         print GetUserInput()
>
To fix both problems replace
multiplier.isdigit()
with
multiplier = int(multiplier)

-- 
Bob Gailer
919-636-4239
Chapel Hill NC



More information about the Tutor mailing list