[Tutor] Help with converting a string into a integer

Mark Lawrence breamoreboy at yahoo.co.uk
Fri Nov 1 04:10:50 CET 2013


On 01/11/2013 02:36, bob gailer wrote:
> On 10/31/2013 2:51 PM, Carmen Salcedo wrote:
>> Thanks Bob! :) I'm very new at programming in Python. I appreciate
>> your feedback.
> Here are some improvements to consider:
>
> import string
> def main():
>      d = {"1" : phoneTranslator, "2" : backwardString}  # map user
> selection to corresponding function
>      while True:
>          selection = raw_input("Enter you choice. Enter 1 " +
>                         "for Phone Translator or 2 for Backward String.")
>          operation = d.get(selection, None) # retrieve corresponding
> function or None
>          if operation: # did we get something?
>              operation() # call it
>              break # out of the while loop
>          print "Invalid choice"
>
> def phoneTranslator():
>      trans = string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ",
> "22233344455566677778889999")
>      print "Phone Translator "
>      phoneNumber = raw_input ("Please enter the phone number: ").upper()
>      phoneNumber = phoneNumber.translate(trans)
>      print phoneNumber[:3] + "-" + phoneNumber[3:]
>
> def backwardString():
>      print "not implemented"
>
> main()
>

Better yet wrap the call to main() so it's not always called when the 
module gets imported, plus some error handling wouldn't go amiss.  For 
anyone using Python 3 raw_input becomes input and you don't need the 
import string, it's simply str.maketrans(...).

-- 
Python is the second best programming language in the world.
But the best has yet to be invented.  Christian Tismer

Mark Lawrence



More information about the Tutor mailing list