# First Python Examples

## Code:

``` # https://www.w3schools.com/ print ('welcome to python') # print (45+(72%5)) # n = 334 # m = 17 # print (n/m) # name = input ("name: ") # print (name) # nn = input ("integer: ") # k = int (nn) # print (k) aa = 33 ab = 45 # aa = int (input("int a: ")) # ab = int (input("int b: ")) print (aa, "<", ab, aa < ab) # Python 3: print (f'{aa:3d}' + " < " + f'{ab:3d}' + " " + f'{(aa < ab):b}') # Python 2 & 3: print ('%3d'%aa + " < " + '%3d'%ab + " " + '%r'%(aa < ab)) s = '%d' % aa print (s) list = [33, 55, 12, 12] print ("   min:", min   (33, 55, 12)) print ("   max:", max   (33, 55, 12)) print (" range:", range (33, 55, 12)) print ("   sum:", sum   (list)) print ("length:", len   (list)) print (" count:", list.count (12)) print ("  type:", type (list)) ```

## Formatting

Some examples of formatting:

print('{:^9} {:^20} {:^20} {:^6} {:^20} {:^20}'.
format('x', 'sin(x)', 'cos(x)', 'z', 'sqrt(z)', 'log10(z)'))

print('{:>9} {:20.17f} {:20.17f} {:6.2f} {:20.17f} {:20.17f}'.
format(str(x) + 'pi/64', sin(xpi), cos(xpi), z, sqrt(z), log10(z)))

## If conditions example

Try inputs a b c and d to the following code
1. as desired
2. always YES
3. always NO
4. as desired
while True:
v = input ("input: ")
if v == 'q': break

if v == 'a' or v == 'b' or v == 'c':
print ("1: YES, == a, b or c")
else:
print ("1: NO , == NOT a, b, or c")

if v == 'a' or 'b' or 'c':
print ("2: YES, or a, b or c")
else:
print ("2: NO , or NOT a, b, or c")

if v == ('a', 'b', 'c'):
print ("3: YES, = list a, b or c")
else:
print ("3: NO , = list NOT a, b, or c")

if v in ('a', 'b', 'c'):
print ("4: YES, in list a, b or c")
else:
print ("4: NO , in list NOT a, b, or c")

## For loop

``` for b in range (10): # print # print arguments: objects, sep, end, file, flush # sep default is ' ', end default is '\n'   c = b + 20   print (c, f'{c*c:5d}', f'{c*c*c:5,d}', end=' - ', sep=" ^ ")   print ('a') for d in range (10, 5, -2):   print ('d', d+3, end = ' > ')   print (d+99123) ```

## List and Function

``` # v3.py list = [98, 76, 71, 87, 83, 90, 57, 79, 82, 94] print ("average:", sum(list)/len(list), "of", len(list), "grades") print (list) import decimal from decimal import Decimal p = Decimal ("22.232") print (p) import statistics print ("Stat mean:", statistics.mean(list)) print ("Sorted:", sorted(list)) import random def roll ():   d1 = random.randrange(1,7)   d2 = random.randrange(1,7)   d3 = random.randrange(1,7)   d4 = random.randrange(1,7)   d5 = random.randrange(1,7)   return (d1, d2, d3, d4, d5) def rolla (n):   f = []   for g in range (n):     f += [random.randrange(1,7)]   return f print (roll) e = roll () print (e) print (sorted(e)) h = rolla (20) print (h) print (sorted(h)) ```

## While-true input loop:

• This loop will run until the user enters a 'q', but the general idea of keep going no matter what until a quit or exit code is entered is a good way to run a program.
• The code highlighted in yellow is one way to let the user enter a number of values on an input line, using split to get a list of strings, and the map to convert that list to integers or floats.
• The try/except block is one effective way to check the input for the correct type - in the case of the green line, for an int.
• The same test could be used in the map part of the code as well.
• The final for loop is some ways to handle formatted output.
```while True:
p = 1000.00   r = 5.0   r = r/100 + 1
b = input ("enter n, q to quit: ")

if b == 'q':
break

try:
b = int (b)
except ValueError:
print ("b should be an integer > 0")
continue

if b < 0:
print ("b should be > 0")
continue

n = b + 5
for y in range (b,n):
a = p * r ** y
print (f'{y:>5}{a:>30,.5f}')

print ()

from decimal import Decimal
p = Decimal(1000.00)
r = Decimal(r)

for y in range (b,n):
a = p * r **y
print (f'{y:>5}{a:>30,.5f}')  print("calculating volume")  a, b, c = map(float, input("for a box,enter 3 sides:\n").split())  vol = a*b*c  print(f"volume is{vol:,.5f}")```

## While true with functions

```# regular expressions:# see: https://docs.python.org/3.8/library/re.htmlimport re

def firstName ():
re = input ("enter first name, * to quit: ")
if re == '*': return False
return re

def zipcode ():
while True:
zip = input ("enter zip code, * for different person: ")
if zip == '*': return False
if re.match (r"(?!(\d{5}-\d{4}\$)|(\d{5}\$))", zip):
print (f"----- zip code is not in the proper format, please try again\n")
else:
return zip
# The := is a new feature in python 3.8# constants defined as false: None, False, versions of 0, empty sets# see: https://docs.python.org/3.8/library/stdtypes.htmlwhile True:
if (not(fn := firstName ())): break
if (not(zc := zipcode   ())): continue
print (f"name: {fn}\nzip code: {zc}\n")

print ("Thanks")

```

## C(N,K) Functions

```def combrn (n):
if n <= 0:
return 
rin = combrn (n-1)
rout = 
for i in range (len(rin)-1):
rout += [rin[i] + rin[i+1]]
rout += 
return rout

def combrow (rin: list):
rout = 
# print (len (rin))
for i in range (len(rin)-1):
rout += [rin[i] + rin[i+1]]
rout += 
return rout

# The following uses the memoization technique# where a dictionary is used to remember values# already computed# from functools import lru_cache# @lru_cache(maxsize = None)cdict = {}def combmem (n, k):  x = cdict.get ((n, k))  if x != None: return x  if n == 0 or k == 0 or k == n:    return 1  if n < 0 or k < 0 or k > n:    return 0  x = combmem(n-1, k) + combmem(n-1, k-1)  cdict[(n, k)] = x  return xdef comb (n, k):
if n == 0 or k == 0 or k == n:
return 1
if n < 0 or k < 0 or k > n:
return 0
return comb (n-1, k) + comb (n-1, k-1)

# r = 55# for a in range (r+1):#   for b in range (a+1):#     print (combmem (a, b), end=" ")#   print ()n, k = (200, 100)x = combmem (n, k)print (f"C({n}, {k}) = {x:,d}")# print ("\nrow by row recursion:\n")
# p = combrow ()
# for a in range (r-1):
# p = combrow (p)
# print (str(p).replace ('[', '').replace(",","").replace(']', ''))

for a in range (r+1):
p = combrn (a)
print (str(p).replace ('[', '').replace(",","").replace(']', ''))

# print (combrn (10))
```

## Interest

• This example compares calculating interest using Decimal and float data type, and
• One approach to flexible input
"""Example 3.11 - Compound interest"""

from decimal import Decimal

principal  = Decimal ('1000')
rate       = Decimal ('.05')
principalf = 1000.0
ratef      = .05
start      = 0
end        = start + 5

prompt = """ q to quit
optional values, 0 to use old value:
1. starting year
2. number of years
3. principal
4. interest rate, %
"""

def myPrint (year, amount):
print (f'{year:>6}: {amount:>10,.2f}')

while True:
line = input (prompt).split()
if len(line) > 0:
if line == 'q': break
if line != '0':
start = int(line)
end   = start + 5
if len(line) > 1:
if line != '0':
end = start + int(line)
if len(line) > 2:
if line != '0':
principal  = Decimal (line)
principalf = float   (line)
if len(line) > 3:
if line != '0':
rate  = Decimal (line) / 100
ratef = float   (line) / 100

for year in range (start, end):
myPrint (str(year)+'d', principal  * (1+rate )**year)
myPrint (str(year)+'f', principalf * (1+ratef)**year)
print ()

## Try with multiple inputs

# V021.py
# multiple input values with try/except

prompt = "Enter numerator, denominator, precision:\n"

while True:
try:
a = input (prompt)
if a == 'q': break
a, b, c = a.split()
a = float (a)
b = float (b)
c = int (c)
print (f'{a}/{b} = {a/b*100:.{c}f}%\n')
except ValueError:
if type(a) is str:
print ("Problem with a")
elif type(b) is str:
print ("Problem with b")
elif type(c) is str:
print ("Problem with c")
else:
print ("A problem")

(end)