Simplify Python

Dave Angel davea at
Tue Apr 6 23:55:03 CEST 2010

ja1lbr3ak wrote:
> I'm trying to teach myself Python, and so have been simplifying a
> calculator program that I wrote. The original was 77 lines for the
> same functionality. Problem is, I've hit a wall. Can anyone help?
> loop = input("Enter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: ")
> while loop < 3 and loop > 0:
>     if loop == 1:
>         print input("\nPut in an equation: ")
>     if loop == 2:
>         a, b, n = 1, 1, (input("\nWhat Fibonacci number do you want to
> go to? "))
>         while n > 0:
>             print a
>             a, b, n = b, a+b, n-1
>     loop = input("\nEnter 1 for the calculator, 2 for the Fibonacci
> sequence, or something else to quit: ")
Since this is apparently some form of self-imposed contest, it'd be nice 
to know the rules.  Usual rule of thumb is to make the program correct 
before trying to optimize it.  For example, this program doesn't guard 
against user error, like entering  AAA+5 for the equation, nor against 
maliciousness, such as entering  range(10**8).

Also, it refers to 'equation' when a better term would be 'expression.'

So, are you trying to minimize line count?  Or character count?  Or 
variables?  Or readability (look up obfuscation contest) ?

You could eliminate the redundant parens around the call to input().
You could eliminate the loop variable and the extra call to input() by 
using break, and moving the test to the beginning of a while-True loop.  
And if you used elif clauses, you wouldn't need the separate if test.
You could probably obfuscate the fibonacci loop by some kind of list 
You could simplify processing n by using range() instead of while.  Then 
no increment is needed.
You could use semicolons to pack multiple statements on each line if 
line count matters, and character count does not.
You could use tab for indenting (yecch) if characters matter.  And use 
one-character variable names (yecch).


More information about the Python-list mailing list