473,397 Members | 2,116 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Is there no switch function in Python

I dont seem to be able to find the switch statement in Python.

I would like to be able to do

switch(var)
case 1 :
print "var = 1"
case 2:
print "var = 2"

But it seems that i have to do.

if(var=1)
print "var =1"
elseif(var=2)
print "var=2"

Is ther no easier way??
Jul 18 '05 #1
14 2579
"Rudi Hansen" <rs**************@pobox.dk> writes:
I would like to be able to do

switch(var)
case 1 :
print "var = 1"
case 2:
print "var = 2"

But it seems that i have to do.

if(var=1)
print "var =1"
elseif(var=2)
print "var=2"

Is ther no easier way??


one way is using dicts:

swoosh = {1: "var = 1", 2: "var = 2"}
print swoosh[var]
--
Marius Bernklev
Jul 18 '05 #2
Rudi Hansen <rs**************@pobox.dk> wrote:
I dont seem to be able to find the switch statement in Python.
Right, there isn't one.

I would like to be able to do

switch(var)
case 1 :
print "var = 1"
case 2:
print "var = 2"

But it seems that i have to do.

if(var=1)
print "var =1"
elseif(var=2)
print "var=2"

Is ther no easier way??


several, starting with

if var in (1,2): print 'var = %s' % var

The most Pythonic idiom, when you have to do something substantial in
each branch of the switch, is a dictionary of callables -- in this toy
case it might be:

switch = {1: lambda: sys.stdout.write('var=1\n'),
2: lambda: sys.stdout.write('var=2\n'), }
switch.get(var, lambda: '')()

An if/elif tree is also fine, though the syntax is not as you think...:

if var == 1:
print 'var is one'
elif var == 2:
print 'var is two'

Alex
Jul 18 '05 #3
In article <CR********************@news000.worldonline.dk>,
Rudi Hansen <rs**************@pobox.dk> wrote:
I dont seem to be able to find the switch statement in Python.

I would like to be able to do

switch(var)
case 1 :
print "var = 1"
case 2:
print "var = 2"
5 lines, 55 characters including the print statements.

But it seems that i have to do.

if(var=1)
print "var =1"
elseif(var=2)
print "var=2"
4 lines, 52 characters (once corrected) including the print
statements (as written in the first example).
Is ther no easier way??


In what way do you want it to be "easier"?

--
\S -- si***@chiark.greenend.org.uk -- http://www.chaos.org.uk/~sion/
___ | "Frankly I have no feelings towards penguins one way or the other"
\X/ | -- Arthur C. Clarke
her nu becomež se bera eadward ofdun hlęddre heafdes bęce bump bump bump
Jul 18 '05 #4
In article <1Z*******@news.chiark.greenend.org.uk>,
Sion Arrowsmith <si***@chiark.greenend.org.uk> wrote:
In article <CR********************@news000.worldonline.dk>,
Rudi Hansen <rs**************@pobox.dk> wrote:
I dont seem to be able to find the switch statement in Python.

I would like to be able to do

switch(var)
case 1 :
print "var = 1"
case 2:
print "var = 2"


5 lines, 55 characters including the print statements.


It's even longer if you include the required "break" statement at the
end of case 1 (assuming you're talking about a C-style switch statement
with fall-through cases).

That being said, there are times when I miss switch. For some kinds of
multi-branch logic, I think it expresses the meaning better than a
string of if's. But it's hardly necessary.

The real reason, IMHO, switch existed in C was because it would let the
compiler build very efficient jump tables for switches with many cases.
Imagine switching on the ascii value of a character and having a 128
different cases. The compiler could build a 128 entry jump table and
the switch statement would compile down to a single machine instruction.
Jul 18 '05 #5
>>>>> "Roy" == Roy Smith <ro*@panix.com> writes:

Roy> The real reason, IMHO, switch existed in C was because it
Roy> would let the compiler build very efficient jump tables for
Roy> switches with many cases. Imagine switching on the ascii
Roy> value of a character and having a 128 different cases. The
Roy> compiler could build a 128 entry jump table and the switch
Roy> statement would compile down to a single machine instruction.

C switch is much more flexible than one would expect. It is not just
a cheap replacement of a sequence of if-then-else. E.g., in an
exercise of "The C++ Programming Language" of Bjarne Stroustrup, you
can see the following example code:

void send(int *to, int *from, int count) {
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while (--n > 0);
}
}

Note that this reduces the number of branch statements to execute
8-folds for any compiler but the smartest (as compared to the simplest
code "do { *to++ = *from++ } while (--count > 0);").

I'd instead guess that C has switch because at the times before C,
people code in assembly, and those tricks are popular. The design of
most programming language represents the norm of coding at that time.

Regards,
Isaac.
Jul 18 '05 #6
In article <ro***********************@reader1.panix.com>,
Roy Smith <ro*@panix.com> wrote:
Jul 18 '05 #7
Isaac To <ik****@netscape.net> wrote:
C switch is much more flexible than one would expect. It is not just
a cheap replacement of a sequence of if-then-else. E.g., in an
exercise of "The C++ Programming Language" of Bjarne Stroustrup, you
can see the following example code:

void send(int *to, int *from, int count) {
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while (--n > 0);
}
}


La-de-dah, Bjarne discovers loop unrolling. You don't need a switch
statement to unroll loops.

Hold on a second. Cases 1 through 7 jump into the middle of the do
loop!? Pardon me while I barf. I didn't even know that was legal.
That's the kind of code that gives C++ a bad name.
Jul 18 '05 #8
Don't blame c++. This is a relic of 'C'.

http://catb.org/~esr/jargon/html/D/Duffs-device.html

On Fri, 10 Sep 2004 11:16:12 -0400, Roy Smith <ro*@panix.com> wrote:
Isaac To <ik****@netscape.net> wrote:
C switch is much more flexible than one would expect. It is not just
a cheap replacement of a sequence of if-then-else. E.g., in an
exercise of "The C++ Programming Language" of Bjarne Stroustrup, you
can see the following example code:

void send(int *to, int *from, int count) {
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while (--n > 0);
}
}


La-de-dah, Bjarne discovers loop unrolling. You don't need a switch
statement to unroll loops.

Hold on a second. Cases 1 through 7 jump into the middle of the do
loop!? Pardon me while I barf. I didn't even know that was legal.
That's the kind of code that gives C++ a bad name.
--
http://mail.python.org/mailman/listinfo/python-list

Jul 18 '05 #9
Isaac To wrote:
a cheap replacement of a sequence of if-then-else. E.g., in an
exercise of "The C++ Programming Language" of Bjarne Stroustrup, you
can see the following example code:

void send(int *to, int *from, int count) {
int n = (count + 7) / 8;
switch (count % 8) {
case 0: do { *to++ = *from++;
case 7: *to++ = *from++;
case 6: *to++ = *from++;
case 5: *to++ = *from++;
case 4: *to++ = *from++;
case 3: *to++ = *from++;
case 2: *to++ = *from++;
case 1: *to++ = *from++;
} while (--n > 0);
}
}


This is otherwise known a Duff's device:

http://catb.org/~esr/jargon/html/D/Duffs-device.html

Peter

Jul 18 '05 #10
On Thu, 9 Sep 2004 22:27:02 +0200, al*****@yahoo.com (Alex Martelli) wrote:
Rudi Hansen <rs**************@pobox.dk> wrote:
I dont seem to be able to find the switch statement in Python.


Right, there isn't one.

I would like to be able to do

switch(var)
case 1 :
print "var = 1"
case 2:
print "var = 2"

But it seems that i have to do.

if(var=1)
print "var =1"
elseif(var=2)
print "var=2"

Is ther no easier way??


several, starting with

if var in (1,2): print 'var = %s' % var

The most Pythonic idiom, when you have to do something substantial in
each branch of the switch, is a dictionary of callables -- in this toy
case it might be:

switch = {1: lambda: sys.stdout.write('var=1\n'),
2: lambda: sys.stdout.write('var=2\n'), }
switch.get(var, lambda: '')()

An if/elif tree is also fine, though the syntax is not as you think...:

if var == 1:
print 'var is one'
elif var == 2:
print 'var is two'

The trouble is that other than if/elif/else or some weird exception tricks,
you can't switch between statements that execute as if they were suites of if/elif/else -- i.e.,
in the local namespace. And UIAM current exec introduces special restrictions in a function.
So you can't get a constant-time "jump table" effect.

But IWT if we had named local code suites, we could exec them safely via a mapping. E.g.,

def foo(var): # following is not legal code ;-)
v1: print 'var is one'
v2: # any suite should be ok, not just one-liners
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
exec switch.get(var, '')

It would also be nice if the local bindings of named local code suites were
(or became wrapped on access as) objects that were callable like functions
without parameters. Locally that could be optimized, but if e.g. foo returned
v2 to its caller, there would have to be a wrapper with a mutable closure
capturing the current name space IWT. This would also be interesting to
pass to another function, which then could effectively execute a code suite
in _its_ caller's space. This could lead to all kinds of wild things, _some_ of
which would probably be neat and useful ;-)

It would be nice to get the switch mapping built at def-time, which should be
feasible, since the v1,v2 etc, bindings could be available then. Not sure how
to spell it nicely though, except that I still like the notion of a general
way to specify def-time execution of statements or expression terms. E.g.,
using '..' as a syntactic marker,
switch ..= {1:v1, 2:v2}
could mean create the binding at def-time (necessarily evaluating the rhs then also).

I had previously proposed that
def foo():
x ..= 123
return x
be codewise equivalent to current
def foo(x=123):
return x
without having x appear in the argument list, but still having the same
call-time local-binding initialization effect (i.e., new binding to def-time rhs value).
I mention this because v1 and v2 in the example are not in the namespace that is normally
searched for default arg rhs expressions as in def foo(x=name): ..., so named local suites'
names would have to be included (and allowed to shadow names that might otherwise be found).

No one commented on my previous post on that, perhaps because I didn't split it out into
a separate post with appropriate title. So here I did it again ;-/ The main use would be
efficient local binding initialization without using the default-arg hack or using a factory
funtion to return a function with initialized bindings in a closure.

The other use would allow constant folding for terms in expressions, using ..(expr) as
as spelling for evaluating expr at def-time and using a constant binding to the result
at run-time. E.g.,

def circle_area(r): return ..(__import__('math').pi)*r*r

would generate byte code like what you can now do with Raymond Hettinger's global-constant
optimizing decorator by writing:

pi = __import__('math').pi # just to make it look like the expr above
@bind_constants()
def circle_area(r): return pi*r*r
del pi

(Very nice, Raymond)

Maybe Raymond will make a decorator to do local variable initialization, so we can write
@localinit('name', expr)
def foo():
name = name*2 # usable like default name in def foo(name=expr): ...
return name
;-)

Regards,
Bengt Richter
Jul 18 '05 #11
Bengt Richter wrote:
But IWT if we had named local code suites, we could exec them safely via a mapping. E.g.,

def foo(var): # following is not legal code ;-)
v1: print 'var is one'
v2: # any suite should be ok, not just one-liners
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
exec switch.get(var, '')


I'm probably missing something, but what's wrong with:

def foo(var):
def v1(): print 'var is one'
def v2():
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
switch.get(var, lambda:None)()
Jul 18 '05 #12
Jaime Wyant wrote:
Don't blame c++. This is a relic of 'C'.


Kind of like saying, "Don't blame me for being a violent thug, I went to
ShootEm Elementary School." Sure, C++ inherited lots of questionable
features from C, but there's never been a law requiring all programming
languages to be extensions of C. The designers of C++ must have known
about C's faults; it's their own fault for choosing to use it in the
first place.
Jul 18 '05 #13
Leif K-Brooks <eu*****@ecritters.biz> wrote:
Bengt Richter wrote:
But IWT if we had named local code suites, we could exec them safely via a mapping. E.g.,
def foo(var): # following is not legal code ;-)
v1: print 'var is one'
v2: # any suite should be ok, not just one-liners
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
exec switch.get(var, '')


I'm probably missing something, but what's wrong with:

def foo(var):
def v1(): print 'var is one'
def v2():
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
switch.get(var, lambda:None)()


Nothing wrong. However, if v1 and v2 needed to rebind some names within
foo, they couldn't according to def's semantics -- they could only
rebind local names of their own, or global names with a global
statement, but not local names in their outer function foo. I think the
right approach, if that feature is a must-have, might be to add the one
missing feature, not with a weird new syntax which forces one to choose
between taking arguments and rebinding outer functions' locals, but with
an optional scope indicator on variables. Just IMHO, anyway.
Alex
Jul 18 '05 #14
On Fri, 10 Sep 2004 22:20:13 -0400, Leif K-Brooks <eu*****@ecritters.biz> wrote:
Bengt Richter wrote:
But IWT if we had named local code suites, we could exec them safely via a mapping. E.g.,

def foo(var): # following is not legal code ;-)
v1: print 'var is one'
v2: # any suite should be ok, not just one-liners
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
exec switch.get(var, '')


I'm probably missing something, but what's wrong with:

def foo(var):
def v1(): print 'var is one'
def v2():
print 'var',
print 'is two'
switch = {1:v1, 2:v2}
switch.get(var, lambda:None)()


Sorry, I should have shown an example that really depends on local name space rebinding,
which the OP's example doesn't, and which was my main point. E.g., try getting the effect of:

def foo(var): # following is not legal code ;-)
v1: print 'var is one'
var += 1
status = 'incremented'
v2: # any suite should be ok, not just one-liners
print 'var',
print 'is two'
var *= 2
status = 'doubled'
switch = {1:v1, 2:v2}
exec switch.get(var, '')
print 'var is now %r, and was %s.' % (var, status)
return var, status

Regards,
Bengt Richter
Jul 18 '05 #15

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

14
by: Christian Seberino | last post by:
I know IPython is another interpreter for Python and was wondering what people liked about it and if I should switch to it. If it is so good then why is it not part of the standard Python...
6
by: Jeff Duffy | last post by:
Hi all. I've been wondering why python itself doesn't provide a switch to check a file for valid syntax. I know that you can currently call python -c "import py_compile;...
2
by: Skip Montanaro | last post by:
Stephen> { Stephen> 'one': lambda x:x.blat(), Stephen> 'two': lambda x:x.blah(), Stephen> }.get(someValue, lambda x:0)(someOtherValue) One thing to remember is that function calls in Python...
26
by: Joe Stevenson | last post by:
Hi all, I skimmed through the docs for Python, and I did not find anything like a case or switch statement. I assume there is one and that I just missed it. Can someone please point me to the...
15
by: Mike and Jo | last post by:
I've been converting some code to C++. I'm trying to use the Switch function to compare a result. Is it possible to use switch to evaluate '>0', '<0', 0? Example switch (result) { case...
65
by: He Shiming | last post by:
Hi, I just wrote a function that has over 200 "cases" wrapped in a "switch" statement. I'm wondering if there are performance issues in such implementation. Do I need to optimize it some way? ...
2
by: Pan Xingzhi | last post by:
Guys: Hi there. Recently I'll have to write a quite interesting program in Python on a Linux box. What I need is a function which allows the user to 'switch' the audio output from <an audio...
6
by: Sile | last post by:
Hello, I'm trying to get f2py working from the command line on windows XP. I have mingw32 as my C complier (after some advice on a previous thread) and Compaq Visual Fortran 6.5. Changing my C...
2
by: Phillip B Oldham | last post by:
What would be the optimal/pythonic way to subject an object to a number of tests (based on the object's attributes) and redirect program flow? Say I had the following: pets = {'name':...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.