[Tutor] __name__=='__main__'
Michael Lewis
mjolewis at gmail.com
Tue Feb 21 00:46:37 CET 2012
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)
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()
break
except ValueError:
continue
new_text = MultiplyText(text, multiplier)
return new_text
if __name == '__main__':
print GetUserInput()
Error I got when __name == ' __main__' was outside of any function:
Traceback (most recent call last):
File "C:/Python27/Homework/Homework5_1.py", line 24, in <module>
if __name == '__main__':
NameError: name '__name' is not defined
--
Michael J. Lewis
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120220/b5590c41/attachment.html>
More information about the Tutor
mailing list