User Name Password Register
DaniWeb IT Discussion Community
All
What is DaniWeb IT Discussion Community?
You're currently browsing the Python section within the Software Development category of DaniWeb, a massive community of 429,743 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 4,088 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our Python advertiser: Programming Forums

"choose" in Python?

Join Date: Jan 2008
Posts: 606
Reputation: ZZucker is an unknown quantity at this point 
Rep Power: 2
Solved Threads: 21
ZZucker's Avatar
ZZucker ZZucker is offline Offline
Practically a Master Poster

Re: "choose" in Python?

  #8  
May 12th, 2008
The standard try/except way would be:
  1. def choose(s):
  2. try:
  3. return "You entered " + {
  4. '1' : "one",
  5. '2' : "two",
  6. '3' : "three"
  7. }[s]
  8. except:
  9. return "Bad input"
  10.  
  11. var1 = raw_input("Input a number between one and three: ")
  12. print choose(var1)
Or straight foreward with dictionary method get():
  1. def choose2(s):
  2. return "You entered " + {
  3. '1' : "one",
  4. '2' : "two",
  5. '3' : "three"
  6. }.get(s, "a bad number")
  7.  
  8. var1 = raw_input("Input a number between one and three: ")
  9. print choose2(var1)
This is closer to the switch/case default.
Last edited by ZZucker : May 12th, 2008 at 11:24 am.
Never argue with idiots, they'll just bring you down to their level and beat you with their experience.
Reply With Quote  
All times are GMT -4. The time now is 3:07 pm.
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC