First Python Examples

Outline


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)))



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:

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.html
import 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.html
while 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 [1]
  rin = combrn (n-1)
  rout = [1]
  for i in range (len(rin)-1):
    rout += [rin[i] + rin[i+1]]
  rout += [1]
  return rout

def combrow (rin: list):
  rout = [1]
  # print (len (rin))
  for i in range (len(rin)-1):
    rout += [rin[i] + rin[i+1]]
  rout += [1]
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 x

def 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 ([1]) # 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))


(end)