python programming language

Learn from examples

I have python 2 installed as python2 .py files I have python 3 installed as python3 .py3 files typically, just python is now up to date python3 (my .py3 files) 1. Program to output an integer, a string, and a floating point number, initially just one method. exp1.py source code # exp1.py first example simple output integer, string, double # note # makes rest of line a comment i = 7 # declare variable i with initial value 7 ac = 'a' # single character no type required msg = "sample string" # declare msg with string in quotes x = 37.95 # declare floating point x with initial value y = 127.34e10 # declare double precision with initial value print "exp1.py running" # simple print title print "i=", # for decimal "," prevents end of line print i # value after i= print "ac=", # for character print ac print "msg=", # for string print msg print "x=", # for simple floating point print x print "y=", # for double with exponent print y exp1_py.out Output from execution: exp1.py running i= 7 ac= a msg= sample string x= 37.95 y= 1.2734e+12 exp1.py3 source code # exp1.py3 first example simple output integer, string, double # note # makes rest of line a comment i = 7 # declare variable i with initial value 7 ac = 'a' # single character no type required msg = "sample string" # declare msg with string in quotes x = 37.95 # declare floating point x with initial value y = 127.34e10 # declare double precision with initial value print("exp1.py3 running") # simple print title print("i=", i) # for decimal print("ac=", ac) # for character print("msg=",msg) # for string print("x=",x) # for simple floating point print("y=",y) # for double with exponent print("x=%6.3f"%(x)) # using format print("y=%g"%(y)) # using format exp1_py3.out Output from execution: exp1.py3 running i= 7 ac= a msg= sample string x= 37.95 y= 1273400000000.0 x=37.950 y=1.2734e+12 2. commands to compile and execute the source code at a minimum, Windows, Linux, MacOSX. Windows: python exp1.py python3 exp1.py3 Linux: python exp1.py python3 exp1.py3 MacOSX python exp1.py python3 exp1.py3 To save output in a file: python exp1.py > exp1_py.out python3 exp1.py3 > exp1_py3.out 3. You must be able to declare variables and list and arrays and matrix of various types. exp3.py source code # exp3.py example file more complete structure, list, arrays, matrix import math from numpy import array # for vector and matrix def main(): print "exp3.py running" a_list=[7, 7.25, "abc"] # any types print "a_list=", print a_list print "a_list[2]=", # selecting item 2, start with 0 print a_list[2] a_list.append("def") # append to end of list print "append=", print a_list del a_list[1] # delete a selected item print "delete=", print a_list print "len(a_list)=", print len(a_list) # get the length of a list print " " a_tuple=2, 3, 5, 7 # can not modify all same type b_tuple=(2, 3, 5, 7) # same data as above all same type print "a_tuple=", print a_tuple print "b_tuple=", print b_tuple print "b_tuple[2]=", # select item 2 for printing print b_tuple[2] # b_tuple[2] = 9 # no modify selected item print " " dict={1:'a', 2:'b', 3:'c'} # dictionary key : value print "dict=", print dict dict[5]='e' print "dict 5=", print dict print "dict[3]=", # look up by key print dict[3] print " " z=range(5) # zero based, length 5, no 5 print "range(5)=", print z z=range(1,5) # 1 based, length 4, no 5 print "range(1,5)=", print z z=range(1,7,2) # step size 2, no 7 print "range(1,7,2)=", print z print " " Y = array([0.0 for i in range(4)]) # initialize to zero print "array([0.0 for i in range(4)])=" print Y A = array([[1.0 for j in range(4)] for i in range(3)]) # initialize to 1 print "array([1.0 for j in range(4)] for i in range(3)])=" print A A[2,3] = 2.0 print "A[2,3] = 2.0 # then A=" print A print " " if __name__ == '__main__': main() exp3_py.out Output from execution: exp3.py running a_list= [7, 7.25, 'abc'] a_list[2]= abc append= [7, 7.25, 'abc', 'def'] delete= [7, 'abc', 'def'] len(a_list)= 3 a_tuple= (2, 3, 5, 7) b_tuple= (2, 3, 5, 7) b_tuple[2]= 5 dict= {1: 'a', 2: 'b', 3: 'c'} dict 5= {1: 'a', 2: 'b', 3: 'c', 5: 'e'} dict[3]= c range(5)= [0, 1, 2, 3, 4] range(1,5)= [1, 2, 3, 4] range(1,7,2)= [1, 3, 5] array([0.0 for i in range(4)])= [ 0. 0. 0. 0.] array([1.0 for j in range(4)] for i in range(3)])= [[ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 1.]] A[2,3] = 2.0 [[ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 2.]] exp3.py3 source code # exp3.py3 example file more complete structure, list, arrays, matrix import math from numpy import array # for vector and matrix def main(): print("exp3.py3 running") a_list=[7, 7.25, "abc"] # any types print("a_list=",a_list) print("a_list[2]=",a_list[2]) # selecting item 2, start with 0 a_list.append("def") # append to end of list print("append=",a_list) del a_list[1] # delete a selected item print("delete=",a_list) print("len(a_list)=",len(a_list)) # get the length of a list print(" ") a_tuple=2, 3, 5, 7 # can not modify all same type b_tuple=(2, 3, 5, 7) # same data as above all same type print("a_tuple=",a_tuple) print("b_tuple=",b_tuple) print("b_tuple[2]=",b_tuple[2]) # select item 2 for printing # b_tuple[2] = 9 # no modify selected item print(" ") dict={1:'a', 2:'b', 3:'c'} # dictionary key : value print("dict=",dict) dict[5]='e' print("dict[5]=e",dict) print("dict[3]=",dict[3]) # look up by key print(" ") z=range(5) # zero based, length 5, no 5 print("range(5)=",z) z=range(1,5) # 1 based, length 4, no 5 print("range(1,5)=",z) z=range(1,7,2) # step size 2, no 7 print("range(1,7,2)=",z) print(" ") Y = array([0.0 for i in range(4)]) # initialize to zero print("array([0.0 for i in range(4)])=") print(Y) A = array([[1.0 for j in range(4)] for i in range(3)]) # initialize to 1 print("array([1.0 for j in range(4)] for i in range(3)])=") print(A) A[2,3] = 2.0 print("A[2,3] = 2.0") print(A) print(" ") if __name__ == '__main__': main() exp3_py3.out Output from execution: exp3.py3 running a_list= [7, 7.25, 'abc'] a_list[2]= abc append= [7, 7.25, 'abc', 'def'] delete= [7, 'abc', 'def'] len(a_list)= 3 a_tuple= (2, 3, 5, 7) b_tuple= (2, 3, 5, 7) b_tuple[2]= 5 dict= {1: 'a', 2: 'b', 3: 'c'} dict[5]=e {1: 'a', 2: 'b', 3: 'c', 5: 'e'} dict[3]= c range(5)= range(0, 5) range(1,5)= range(1, 5) range(1,7,2)= range(1, 7, 2) array([0.0 for i in range(4)])= [ 0. 0. 0. 0.] array([1.0 for j in range(4)] for i in range(3)])= [[ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 1.]] A[2,3] = 2.0 [[ 1. 1. 1. 1.] [ 1. 1. 1. 1.] [ 1. 1. 1. 2.]] 4. You need to be able to have loops, iteration statements exp4.py source code # exp4.py example file loops, iteration def main(): print "exp4.py running" print "for i in range(5):" for i in range(5): # : required, indent loop, blank line terminates print i print "for i in range(1,6):" for i in range(1,6): # starting value, stop at 6-1 or i<6 print i print "for i in range(1,8,2):" for i in range(1,8,2): # increment by 2 i=1; i<8; i=i+2 print i print "bad for x in range(-1.5,1.5,0.5): range must be integer" print "while x < 1.5:" x = -1.5 print x while x < 1.5: # while must have : blank line end of while x = x + 0.5 print x if __name__ == '__main__': main() exp4_py.out Output from execution: exp4.py running for i in range(5): 0 1 2 3 4 for i in range(1,6): 1 2 3 4 5 for i in range(1,8,2): 1 3 5 7 bad for x in range(-1.5,1.5,0.5): range must be integer while x < 1.5: -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 exp4.py3 source code # exp4.py3 example file loops, iteration def main(): print("exp43.py running") print("for i in range(5):") for i in range(5): # : required, indent loop, blank line terminates print(i) print("for i in range(1,6):") for i in range(1,6): # starting value, stop at 6-1 or i<6 print(i) print("for i in range(1,8,2):") for i in range(1,8,2): # increment by 2 i=1; i<8; i=i+2 print(i) print("bad for x in range(-1.5,1.5,0.5): range must be integer") print("while x < 1.5:") x = -1.5 print(x) while x < 1.5: # while must have : blank line end of while x = x + 0.5 print(x) if __name__ == '__main__': main() exp4_py3.out Output from execution: exp4.py3 running for i in range(5): 0 1 2 3 4 for i in range(1,6): 1 2 3 4 5 for i in range(1,8,2): 1 3 5 7 bad for x in range(-1.5,1.5,0.5): range must be integer while x < 1.5: -1.5 -1.0 -0.5 0.0 0.5 1.0 1.5 5. You need if then else conditional statements exp5.py source code # exp5.py example file if, elif, else conditional statements def main(): print "exp5.py running" a = 3 b = 4 print "simple if ab:" if a > b: # this will be False print "a > b" else: # else: in same column or same tabs as "if" print "not a>b" print " elif part else part if a>b:" if a > b: # this will be False only one elif can execute print "a > b" elif a >= b: print "a >= b" elif a == b: print "a == b" elif a != b: print "a != b" # True, prints elif a <= b: print "a <= b" else: # not run because elif above True print "a>b" print "and or not in if" if (a > b and a !=b) or a == b: print "False" elif not a == b: print "not a == b" else: # else: in same column or same tabs as "if" print "a < b" me = True if me: print "me = True" if __name__ == '__main__': main() exp5_py.out Output from execution: exp5.py running simple if ab: not a>b elif part else part if a>b: a != b and or not in if not a == b me = True exp5.py3 source code # exp5.py3 example file if, elif, else conditional statements def main(): print("exp5.py3 running") a = 3 b = 4 print("simple if ab:") if a > b: # this will be False print("a > b") else: # else: in same column or same tabs as "if" print("not a>b") print(" elif part else part if a>b:") if a > b: # this will be False only one elif can execute print("a > b") elif a >= b: print("a >= b") elif a == b: print("a == b") elif a != b: print("a != b") # True, prints elif a <= b: print("a <= b") else: # not run because elif above True print("a>b") print("and or not in if") if (a > b and a !=b) or a == b: print("False") elif not a == b: print("not a == b") else: # else: in same column or same tabs as "if" print("a < b") me = True if me: print("me = True") if __name__ == '__main__': main() exp5_py3.out Output from execution: exp5.py3 running simple if ab: not a>b elif part else part if a>b: a != b and or not in if not a == b me = True 6. You need to be able to create functions, procedures, subroutines. exp6.py source code # exp6.py example file create functions, procedures, subroutines def jp(): # trivial just print, must have : indent, blank line print "jp() running" def add2(a,b): # input values and return a value (any types) return a+b def rtnmany(a,b): # more than one value returned c = a+b d = a-b e = a*b f = a/b return c,d,e,f def main(): print "exp6.py running" jp() c = add2(3,5) print "c=", print c v1,v2,v3,v4 = rtnmany(6,3) print v1,v2,v3,v4 if __name__ == '__main__': main() exp6_py.out Output from execution: exp6.py running jp() running c= 8 9 3 18 2 exp6.py3 source code # exp6.py3 example file create functions, procedures, subroutines def jp(): # trivial just print, must have : indent, blank line print("jp() running") def add2(a,b): # input values and return a value (any types) return a+b def rtnmany(a,b): # more than one value returned c = a+b d = a-b e = a*b f = a/b return c,d,e,f def main(): print("exp6.py3 running") jp() c = add2(3,5) print("c=",c) v1,v2,v3,v4 = rtnmany(6,3) print(v1,v2,v3,v4) if __name__ == '__main__': main() exp6_py3.out Output from execution: exp6.py3 running jp() running c= 8 9 3 18 2.0 7. You need to be able to read and write files in various formats. exp7.py source code # exp7.py example file read and write files of various types def main(): line1 = "line1\n" # needs \n new line line2 = "line2\n" line3 = "line3\n" print "exp7.py running" print "write a file exp7file.txt" file7 = open("exp7file.txt","w") # open a file for writing file7.write(line1) # creates file, overwrites if exists file7.write(line2) file7.write(line3) file7.close() # close the file print "file written" print "read the entire file just written" inp = open("exp7file.txt","r") # open existing file for reading inputs = inp.read() # reads entire file inp.close() # close the file print "read from exp7file.txt file" print inputs print "read a line at a time" inp = open("exp7file.txt","r") # open existing file for reading input1 = inp.readline() # reads one line print input1 input1 = inp.readline() # reads next line print input1 input1 = inp.readline() # reads next line print input1 inp.close() # close the file # read numbers from file print "read numbers from file data.txt" with open('data.txt') as f: polyShape = [] for line in f: line = line.split() # to deal with blank if line: # lines (ie skip them) line = [int(i) for i in line] polyShape.append(line) print polyShape if __name__ == '__main__': main() exp7_py.out Output from execution: exp7.py running write a file exp7file.txt file written read the entire file just written read from exp7file.txt file line1 line2 line3 read a line at a time line1 line2 line3 read numbers from file data.txt [[0, 0, 3, 50], [50, 100, 3, 20]] data.txt data file exp7.py3 source code # exp7.py3 example file read and write files of various types def main(): line1 = "line1\n" # needs \n new line line2 = "line2\n" line3 = "line3\n" print("exp73.py running") print("write a file exp7file.txt") file7 = open("exp7file.txt","w") # open a file for writing file7.write(line1) # creates file, overwrites if exists file7.write(line2) file7.write(line3) file7.close() # close the file print("file written") print("read the entire file just written") inp = open("exp7file.txt","r") # open existing file for reading inputs = inp.read() # reads entire file inp.close() # close the file print("read from exp7file.txt file and print") print(inputs) print("read a line at a time") inp = open("exp7file.txt","r") # open existing file for reading input1 = inp.readline() # reads one line print(input1) input1 = inp.readline() # reads next line print(input1) input1 = inp.readline() # reads next line print(input1) inp.close() # close the file # read numbers from file print("read numbers from file data.txt") with open('data.txt') as f: polyShape = [] for line in f: line = line.split() # to deal with blank if line: # lines (ie skip them) line = [int(i) for i in line] polyShape.append(line) print(polyShape) if __name__ == '__main__': main() exp7_py3.out Output from execution exp73.py running write a file exp7file.txt file written read the entire file just written read from exp7file.txt file and print line1 line2 line3 read a line at a time line1 line2 line3 read numbers from file data.txt [[0, 0, 3, 50], [50, 100, 3, 20]] data.txt data file 8. You need to be able to use a number of files combined to build a program. This may include packages, libraries, operating system commands, header files, etc. exp8.py source code # exp8.py example file other functions def main(): print "exp8.py running" a = str(1.0/7.0) # '0.142857142857' print a b = repr(1.0/7.0) # '0.14285714285714285' print b c = len(b) print "c=len(b) =", print c # Here are two ways to write a table of squares and cubes: for x in range(1, 5): print repr(x).rjust(2), repr(x*x).rjust(3), print repr(x*x*x).rjust(4) print " " for x in range(1,5): print '{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x) # read numbers from file with open('data.txt') as f: polyShape = [] for line in f: line = line.split() # to deal with blank if line: # lines (ie skip them) line = [int(i) for i in line] polyShape.append(line) print polyShape if __name__ == '__main__': main() exp8_py.out Output from execution: exp8.py running 0.14285714285714285 0.14285714285714285 c=len(b) = 19 1 1 1 2 4 8 3 9 27 4 16 64 1 1 1 2 4 8 3 9 27 4 16 64 [[0, 0, 3, 50], [50, 100, 3, 20]] exp8.py3 source code # exp8.py3 example file other functions def main(): print("exp8.py3 running") a = str(1.0/7.0) # '0.142857142857' print(a) b = repr(1.0/7.0) # '0.14285714285714285' print(b) c = len(b) print("c=len(b) =",c) # Here are two ways to write a table of squares and cubes: for x in range(1, 5): print(repr(x).rjust(2), repr(x*x).rjust(3), repr(x*x*x).rjust(4)) print(" ") for x in range(1,5): print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x)) # read numbers from file with open('data.txt') as f: polyShape = [] for line in f: line = line.split() # to deal with blank if line: # lines (ie skip them) line = [int(i) for i in line] polyShape.append(line) print(polyShape) if __name__ == '__main__': main() exp8_py3.out Output from execution: exp8.py3 running 0.14285714285714285 0.14285714285714285 c=len(b) = 19 1 1 1 2 4 8 3 9 27 4 16 64 1 1 1 2 4 8 3 9 27 4 16 64 [[0, 0, 3, 50], [50, 100, 3, 20]] Python packages, such as numpy, can list the names of their functions. The list can be very long and is one string, using dir(). print(dir(numpy.matlib)) is shown in next example: test_numpy.py source code test_numpy_py.out Output of execution test_numpy.py3 source code test_numpy_py3.out Output of execution time_thread.py source code time_thread_py.out Output of execution time_thread.py3 source code time_thread_py3.out Output of execution Other links: read_command_arg.py3 source code read_command_arg_py3.out1 read_command_arg_py3.out2 read_command_arg_py3.out3 read_command_arg_py3.out4 read_keyboard.py3 source code read_keyboard_py3.out output Other links using tkinter for graphics: w1tk.py source code # w1tk.py python using Tkinter, see web for documentation from Tkinter import * root=Tk() root.title('w1tk.py click to exit') def mouseB1press(event): # left sys.exit() c=Canvas(root, width=200, height=100, bg='white') c.create_line( 50, 50,150, 50,fill='black') c.create_line(150, 50,150, 75,fill='black') c.create_line(150, 75, 50, 75,fill='black') c.create_line( 50, 75, 50, 50,fill='black') c.create_text(100,30, text='click here to exit', fill='black') c.bind('' , mouseB1press) c.pack() root.mainloop() Output from execution: w1tk.py3 source code w1tkxy.py3 source code with x,y Output from w1tkxy.py3 on windows: red dashed line different on Linux w2tk.py3 source code w3tk.py3 source code w4tk.py3 source code w5tk.py3 source code rubber_box.py3 source code colorw.py3 source code puzzel.py3 source code many python 3 changes Now, you are ready for a more complete language summary

Last updated 3/9/2022