python_functions_1.html


001| '''Python Functions.'''
002| 
003| adder0 = lambda a,b: a+b
004| 
005| def adder1 (a, b):
006|     '''Add two numbers.'''
007|     return a+b
008| 
009| def adder2 (*terms):
010|     '''Add any numbers together.'''
011|     total = 0
012|     for term in terms:
013|         total += term
014|     return total
015| 
016| 
017| def vector3d (x=0.0, y=0.0, z=0.0):
018|     '''Return a 3D tuple.'''
019|     return (float(x), float(y), float(z))
020| 
021| def vector5d (**kwargs):
022|     '''Return a 5D tuple.'''
023|     x = float(kwargs['x']) if 'x' in kwargs else 0.0
024|     y = float(kwargs['y']) if 'y' in kwargs else 0.0
025|     z = float(kwargs['z']) if 'z' in kwargs else 0.0
026|     w = float(kwargs['w']) if 'w' in kwargs else 0.0
027|     u = float(kwargs['u']) if 'u' in kwargs else 0.0
028|     return (x, y, z, w, u)
029| 
030| 
031| print(f'{adder0(21,42) = }')
032| print(f'{adder1(21,42) = }')
033| print(f'{adder2(21,42,63,84) = }')
034| print()
035| 
036| print(f'vec3d: {vector3d()}')
037| print(f'vec3d: {vector3d(3,4,5)}')
038| print(f'vec3d: {vector3d(z=1.0)}')
039| print()
040| print(f'vec5d: {vector5d()}')
041| print(f'vec5d: {vector5d(x=1, y=2, z=3, w=4, u=5)}')
042| print(f'vec5d: {vector5d(w=1.0, u=2.0)}')
043| print()
044| 
045| 
046| def counter (start=1, step=1, dtype=int):
047|     '''Generator function. Returns endless series.'''
048|     curr = start
049|     while True:
050|         yield dtype(curr)
051|         curr += step
052| 
053| # Adding serial numbers to obects (letters)...
054| letters = ['a', 'b', 'c', 'd', 'e', 'f']
055| for ix,n in zip(counter(1001), letters):
056|     print(f'{ix}: {n}')
057| print()
058| 
059| # Alphabet with ASCII codes in decimal and hex...
060| base = ord('A')
061| alphabet = [chr(base+cx) for cx in range(26)]
062| for ix,n in zip(counter(base), alphabet):
063|     print(f'{n} = {ix} = 0x{ix:02x}')
064| print()
065| 
066| # Use the counter with floats...
067| ctr = counter(dtype=float, step=0.25, start=0)
068| for ix in range(8):
069|     print(f'{ix}: {next(ctr)}')
070| print()
071| 
072| # Use the counter with alphas...
073| ctr = counter(dtype=chr, start=97)
074| items = [next(ctr) for _ in range(12)]
075| print(items)
076| print()
077| 
078| # NEVER DO THIS!! (Infinite loop; runs forever!)
079| #for ix in counter():
080| # print(ix)
081| #print()
082| 
083| 
084| print()
085| """eof"""
086|