![]() |
| ||
| "choose" in Python? There's a function that repeatedly shows up in languages, usually with more or less the following form (Python syntax): var1 = raw_input("Input a number between one and three.")
Or something like that. I've also seen it called "switch." Does Python have anything like this? |
| ||
| Re: "choose" in Python? In Python you can set up a dictionary to mimic switch/case ... def choose(s):Even in C the switch/case statement is not as efficient as multiple if/elif statements, so Python did not implement it. |
| ||
| Re: "choose" in Python? That is pretty ingenious! Does it work without using lambda? e.g '1':"w/e", etc |
| ||
| Re: "choose" in Python? Actually, in this case you don't need lambda, since you are only returning a string. Please shorten the code to ... def choose(s):Mildy more elegant ... def choose(s): |
| ||
| Re: "choose" in Python? And, um, while we're at it...what does Lambda do, anyway? |
| ||
| Re: "choose" in Python? Lambda creates an anonymous function, and is used to create a short inline function. Lambda calculus is part of functional programming. It simply states that all computational constructs can be defined in terms of lambda. Interested? Read the article in: http://linuxgazette.net/109/pramode.html |
| ||
| Re: "choose" in Python? I'm going to feel really stupid when I see the answer to my question, because I'm sure I've seen it before and I've just forgotten. Anyway, I was just fiddling with this example, and I can't remember how to add a default case. In the example given I want to return the text "Bad input" for any value other than 1, 2, or 3. What do I need to add to the dictionary? |
| ||
| Re: "choose" in Python? The standard try/except way would be: def choose(s):Or straight foreward with dictionary method get(): def choose2(s):This is closer to the switch/case default. |
| ||
| Re: "choose" in Python? Thanks, I knew it was something simple that I had seen before. * SLAPS FOREHEAD * |
| All times are GMT -4. The time now is 3:16 am. |
Forum system based on vBulletin Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
©2003 - 2008 DaniWeb® LLC