case do problem

Alf P. Steinbach alfps at start.no
Tue Mar 2 19:00:09 CET 2010


* Tracubik:
> hi, i've to convert from Pascal this code:
> 
> iterations=0;
> count=0;
> REPEAT;
>   iterations = iterations+1;
>   ...
>   IF (genericCondition) THEN count=count+1;
>   ...
>   CASE count OF:
> 	1: m = 1
>         2: m = 10
>         3: m = 100

Uhm, is this syntactically valid Pascal? As I recall, every Pascal construct was 
delimited in some way. Once I had the complete Pascal syntax in my head, but 
alas, not anymore...


> UNTIL count = 4 OR iterations = 20
> 
> i do something like this:
> 
> iterations = 0
> count = 0
> 
> m_Switch = (1,10,100)
> 
> while True:
> 	iterations +=1
> 	...
> 	if (genericCondition):
> 		count +=1
> 	...
> 	try:
> 		m = m_Switch[count-1]
> 	except: pass
> 	if count = 4 or iterations = 20
> 
> the problem is that when count = 4 m_Switch[4-1] have no value, so i use 
> the try..except.

   iterations = 0
   count = 0
   while not( count == 4 or iterations == 20 ):
       iterations += 1
       # ...
       if generic_condition:
           count += 1
       # ...
       m = (1, 10, 100, 100)[count]


> Is there a better solution to solve this problem?

Define "better". Do you mean faster, more clear, shorter, using less memory, what?

Above I've assumed that you want to get rid of the try block, since that's what 
you're asking about:


> and, generally 
> speaking, the try..except block slow down the execution of the program or 
> not?

Probably, but don't think about it. Python programming is at a level where that 
kind of efficiency doesn't count. Or, ideally it shouldn't count.


Cheers & hth.,

- Alf



More information about the Python-list mailing list