case do problem

MRAB python at mrabarnett.plus.com
Tue Mar 2 13:26:08 EST 2010


Tracubik wrote:
> 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
> 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.
>> Is there a better solution to solve this problem? and, generally 
> speaking, the try..except block slow down the execution of the program or 
> not?
>Use a dict:
 m_Switch = {1: 1, 2: 10, 3: 100}
and then catch the KeyError.
Don't use a bare 'except', catch the specific exception you want to
catch, and don't worry about the speed unless you discover that it's
real problem.


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /