No activity today, make something!
Simplest Python python program structure

20141124024305 guodepei  

python program structure

  • func:
def fib(n):    # write Fibonacci series up to n
    """"""Print a Fibonacci series up to n.""""""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()
  • return: return result
  • if…elseif…:
if x < 0:
     x = 0
     print('Negative changed to zero')
elif x == 0:
     print('Zero')
elif x == 1:
     print('Single')
else:
     print('More')
  • for:
for i in range(5):
    print(i)

  • foreach:
for x in a:
    print(x, len(x))
  • case:
    • if...elif...elif...else
    • dictionary
values = {
           value1: do_some_stuff1,
           value2: do_some_stuff2,
           ...
           valueN: do_some_stuffN,
         }
values.get(var, do_default_stuff)()
    • lambda
result = {
  'a': lambda x: x * 5,
  'b': lambda x: x + 7,
  'c': lambda x: x - 2
}[value](x)"
  • try…catch:
import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as err:
    print(""I/O error: {0}"".format(err))
except ValueError:
    print(""Could not convert data to an integer."")
except:
    print(""Unexpected error:"", sys.exc_info()[0])
    raise


def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print(""division by zero!"")
    else:
        print(""result is"", result)
    finally:
        print(""executing finally clause"")
  • main:
if __name__ == '__main__':
  #for i in range(256):
  #  print '%d: %c' % (i, i)
  sortfile('G:\\40 My Audio\\English')
  • arg:
if __name__ == '__main__':
  #for i in range(256):
  #  print '%d: %c' % (i, i)
  sortfile('G:\\40 My Audio\\English')
  • class: class Foo(object):

  • import:

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

from ..filters import equalizer