1 #!/usr/bin/python3 2 ######### Variables ######### 3 # Each variable in python has a "type". The variable type is not pre-defined, it is "DYNAMICALLY" resolved at run-time 4 answer = 42 # "answer" contained an integer because we gave it 5 print(answer) # as an integer! 6 # 42 7 is_it_thursday = True # These both are 'booleans' or true/false 8 is_it_wednesday = False # values 9 pi_approx = 3.1415 # This will be a floating point number 10 my_string = "Value of pi number" # This is a string datatype 11 print(pi_approx, my_string) 12 # 3.1415 Value of pi number 13 print ("my_string[0]: ", my_string[0]) # Access substrings use [] 14 # my_string[0]: V 15 print ("my_string[1:5]: ", my_string[1:5]) # or indices 16 # my_string[1:5]: alue 17 # print(pi_approx + my_string) 18 ## TypeError: unsupported operand type(s) for +: 'float' and 'str' 19 print(my_string + " in four digits after .") 20 # Value of pi number in four digits after . 21 print(type(pi_approx)) # You can get the data type of any object 22 # <class 'float'> 23 # Addition, subtraction, multiplication, division are as you expect 24 float1 = 5.75; float2 = 2.25 25 print(float1 + float2); print(float1 - float2); print(float1 * float2); print(float1 / float2) 26 print(5 % 2) # Modulus |
1 ## More Complicated Data Types 2 # LIST. What if we want to store many integers? We need a list. 3 prices = [10, 20, 30, 40, 50] # A way to define a list in place 4 colors = [] # We can also make an empty list and add to it 5 colors.append("Green") 6 colors.append("Blue") 7 colors.append("Red") 8 print(colors) 9 prices.append("Sixty") # We can also add unlike data to a list 10 print(prices) # Items in a list can be of different type 11 print(colors[0]) # Single list elements can be accessed 12 print(colors[2]) # with the operator [ ] 13 ourlist = [1, 2, 3, 4, 5] # Basic List Operations 14 print(ourlist+ourlist) # Concatenation 15 print(3*ourlist) # Repetition 16 multiplied_ourlist = [value * 3 for value in ourlist] # Membership 17 print(multiplied_ourlist) # Iteration 18 # 19 # TUPLE. A tuple is a sequence ordered data enclosed between (). 20 tuple1 = "a", "b", "c", "d" 21 tuple2 = ('physics', 'chemistry', 2022, 2023) # Data heterogeneous 22 tuple3 = (1, 2, 3, 4, 5 ) 23 ikc_muh_55_info = ("IKC-MH", "55", 2023, "February", 28) 24 print("tuple1[0]: ", tuple1[0]) # access to single element 25 print("tuple2[1:5]: ", tuple2[1:5]) # access to slice 26 print(ikc_muh_55_info[0] + "." + ikc_muh_55_info[1]) 27 print(tuple3) |
1 # DICTIONARY. An unordered collection of items 2 person = {"name": "Mehmet", "age": 19} 3 print(f"{person['name']} is {person['age']} years old.") 4 print(person["name"]) 5 squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81} 6 for i in squares: 7 print(squares[i]) 8 # 9 ######### Loops in Python ######### 10 # Repeat code until a conditional statement ends the loop 11 # WHILE. 12 list = [1, 1, 2, 3, 5, 8] 13 print(list) 14 print("i", "list[i]") 15 i = 0 16 while (i < len(list)): # While loops are the basic type 17 print(i, list[i]) 18 i = i + 1 19 # 20 # FOR. The 'for' loop is the way to write it faster. 21 for i in range(0, len(list)): 22 print(i, list[i]) 23 # Or you can do so even neater 24 for e in list: 25 print(e) |
1 ######### Conditionals in Python ######### 2 # Sometimes you want to execute code only in certain circumstances 3 answer = 42 # Change answer and see what code is executed 4 if answer == 42: 5 print('This is the answer to the ultimate question') 6 elif answer < 42: 7 print('This is less than the answer to the ultimate question') 8 else: 9 print('This is more than the answer to the ultimate question') 10 print('This print statement is run no matter what because it is not indented!') 11 # Using boolean operations. Question: How long does it take me to get to work? 12 snowy = True 13 day = "Monday" 14 rainy = True 15 if (snowy == False) and (day != "Monday"): # "and" is boolean and. True only if both are true. False otherwise 16 time = 7 17 elif (snowy == True) and (day == "Monday"): 18 time = 11 19 elif (rainy == True) or (day == "Monday"): 20 time = 9 21 print("It takes me %d minutes" % (time)) |
1 # while & if statements example 2 number = 23 3 running = True 4 while running: 5 guess = int(input('Enter an integer : ')) 6 if guess == number: 7 print('Congratulations, you guessed it.') 8 running = False # this causes the while loop to stop 9 elif guess < number: 10 print('No, it is a little higher than that.') 11 else: 12 print('No, it is a little lower than that.') 13 else: 14 print('The while loop is over.') 15 print('Done') # Do anything else you want to do here 16 # 17 ######### Functions in Python ######### 18 # A function is a block of code which only runs when it is called and can be run repetitively. 19 # use the def keyword, and indent because this creates a new block 20 def print_me(string): # Function definition is here 21 "This prints a passed string into this function" # The first statement of a function can be an optional statement 22 print(string) 23 return # End with the "return" keyword 24 print_me("I'm first call to user defined function!") # Function call 25 print_me("Again second call to the same function") # Function call |
1 def changelist( mylist ): 2 """This changes a passed list into this function""" 3 mylist = [1,20,3,4] # Call by Value in Python. This assigns new reference in mylist 4 # Call by Reference when commenting this line 5 print("Address inside the function: ", id(mylist)) 6 mylist.append(9) 7 mylist[0]=7 8 mylist.remove(20) 9 print("Values inside the function: ", mylist) 10 mylist = [10,20,30] # Function call 11 print("Initial values outside the function: ", mylist) 12 print("Address outside the function: ", id(mylist)) 13 changelist( mylist ) 14 print("Values outside the function: ", mylist) 15 # Initial values outside the function: [10, 20, 30] 16 # Address outside the function: 140390909223488 # Call by Value 17 # Address inside the function: 140390919434048 # Call by Value 18 # Values inside the function: [7, 3, 4, 9] # Call by Value 19 # Values outside the function: [10, 20, 30] # Call by Value 20 # 21 # Initial values outside the function: [10, 20, 30] 22 # Address outside the function: 140390919434048 # Call by Ref. 23 # Address inside the function: 140390919434048 # Call by Ref. 24 # Values inside the function: [7, 30, 9] # Call by Reference 25 # Values outside the function: [7, 30, 9] # Call by Reference |
1 def step(x): # Your functions can return data if you so choose 2 if (x < 0): 3 return -1 4 elif (x > 0): 5 return 1 6 print(step(-1)) # call functions by repeating their name, and putting your variable in the parenthesis 7 print(step(1)) # Your variable need not be named the same thing, but it should be the right type 8 # what happens for x = 0? 9 print(step(0)) # Python automatically adds in a "return none" statement if you are missing one. 10 # 11 # Fix the return none issue 12 def step_v2(x): 13 if (x < 0): 14 return -1 15 elif (x >= 0): 16 return 1 17 print(step_v2(0)) |
1 ######### Importing in Python ######### 2 # Just about every standard math function on a calculator has a python equivalent pre-made. 3 import math 4 float1 = 5.75 5 float2 = 2.25 6 print(math.log(float1)); print(math.exp(float2)); print(math.pow(2,5)) 7 print(2.0**5.0) # There is a quicker way to write exponents 8 # 9 ######### Numpy - "The Fundamental Package for Scientific Computing with Python" ######### 10 # numpy has arrays, which function similarly to Python lists. 11 # 12 # Generally, it is used a convention on names used to import packages (such as numpy, scipy, and matplotlib) 13 # import [package] as [alias] 14 import numpy as np 15 import matplotlib as mpl 16 import matplotlib.pyplot as plt 17 # 18 # Generally scipy is not imported as module because interesting functions in scipy are actually located in the submodules, so submodules or single functions are imported 19 # from [package] import [module] as [alias] 20 from scipy import fftpack 21 from scipy import integrate |
1 import numpy as np # Here, we grab all of the functions and tools from the numpy package and store them in a local variable called np. 2 l = [1,2,3,4] # python list 3 print(l) 4 l_np = np.array(l) 5 print(l_np) 6 print(l*5) # multiplying a python list replicates it 7 print(l_np*5) # numpy applies operation elementwise 8 # 9 ## 1D array 10 a1 = np.array([1,2,3,4]) # initialized with a numpy list. Be careful with syntax. The parentheses and brackets are both required 11 print(a1) 12 print(a1.shape) # shape indicates the rank of the array 13 # 14 ## Rank 2 array 15 # row vector 16 a2 = np.array([[1,2,3,4]]) 17 print(a2) 18 print(a2.shape) # shape indicates the rank of the array. this looks more like a row vector 19 # column vector 20 a3 = np.array([[1], 21 [2], 22 [3], 23 [4]]) 24 print(a3) 25 print(a3.shape) # this looks more like a column vector |
1 import numpy as np 2 a = np.array([0, 10, 20, 30, 40]) 3 print(a) 4 print(a[:]) 5 print(a[1:3]) 6 a[1] = 15 7 print(a) 8 b = np.arange(-5, 5, 0.5) 9 print(b) 10 print(b**2) 11 1/b 12 # <input>:1: divide by zero encountered in true_divide 13 1/b[10] 14 # <input>:1: divide by zero encountered in double_scalars 15 # 16 ## Element-wise operations 17 a = np.array([1, 2, 3]) 18 b = np.array([9, 8, 7]) 19 print(a) 20 print(a.shape); print(b.shape) 21 print(a[0]) # Access elements from them just like a list 22 # 23 # Element-wise operations. This is different from MATLAB where you add a dot to get element wise operators. 24 c = a + b 25 d = a - b 26 e = a * b 27 f = a / b 28 print(c); print(d); print(e); print(f) |
1 import numpy as np 2 # What about multi-dimensional arrays? Matrices! You just nest lists within lists 3 A = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]]); print(A) 4 # [[1 2 3] 5 # [4 5 6] 6 # [7 8 9]] 7 print(A.shape) 8 # (3, 3) 9 B = np.array([[1, 1, 1],[2, 2, 2],[3, 3, 3]]); print(B) 10 C = np.matmul(A, B); print(C) # Then matrix multiplication 11 print(np.linalg.det(A)) # Or determinants 12 # 13 import numpy as np 14 p = np.poly1d([3,4,5]) 15 print(p) 16 # 2 17 # 3 x + 4 x + 5 18 print(p*p) 19 # 4 3 2 20 # 9 x + 24 x + 46 x + 40 x + 25 21 print(p.integ(k=6)) 22 # 3 2 23 # 1 x + 2 x + 5 x + 6 24 print(p.deriv()) 25 # 6 x + 4 26 p([4, 5]) 27 # array([ 69, 100]) |
1 ##### SciPy is a scientific computation library in Python ##### 2 # A collection of functions to perform basic scientific programming and data analysis 3 # Integrate a list of numbers using scipy you might use a function called trapz from the integrate package 4 import scipy.integrate as integ 5 # from scipy import integrate as integ 6 result = integ.trapz([0, 1, 2, 3, 4, 5]) 7 print(result) 8 # Integrate sin(x) from 0 to Pi you could use the quad function 9 import numpy as np 10 import scipy.integrate as integ 11 result = integ.quad(np.sin, 0, np.pi) 12 print(result) 13 # 14 ######### Matplotlib ######### 15 # Matplotlib, like many Python packages, is organized into a number of "modules" (essentially subsets of functions). 16 import matplotlib.pyplot as plt # import packages with alias 17 # from matplotlib import pyplot as plt 18 x_vals = [-2, -1, 0, 1, 2] 19 y_vals = [-4, -2, 0, 2, 4] 20 print(x_vals,y_vals) 21 plt.xlabel('abscissa') # add a label to the x axis 22 plt.ylabel('ordinate') # add a label to the y axis 23 plt.title('A practice plot') # add a title 24 plt.plot(x_vals, y_vals, marker="o") 25 plt.savefig('plot_0.png') # save the figure to the current diretory as a png file 26 plt.show() |
1 import matplotlib.pyplot as plt 2 import numpy as np 3 t = np.arange(0.0, 2.0, 0.01) 4 print(t) 5 print(t.shape) 6 print(len(t)) 7 s = 1 + np.sin(2*np.pi*t) # Degree to Radian conversion 8 print(s) 9 plt.plot(t, s) 10 plt.xlabel('Time (s)'); plt.ylabel('Voltage (mV)') 11 plt.title('Voltage vs Time') 12 plt.grid(True) 13 plt.savefig("test.png") 14 plt.show() 15 # 16 # Multiplotting 17 import numpy as np 18 import matplotlib.pyplot as plt 19 x1 = np.linspace(0.0, 5.0); x2 = np.linspace(0.0, 2.0) 20 y1 = np.cos(2*np.pi*x1)*np.exp(-x1); y2 = np.cos(2*np.pi*x2) 21 plt.subplot(2, 1, 1) # use the subplot function to generate multiple panels within the same plotting window 22 plt.plot(x1, y1, 'o-') 23 plt.title(' 2 subplots') 24 plt.ylabel('Damped oscillation') 25 plt.subplot(2, 1, 2) 26 plt.plot(x2, y2, '.-') 27 plt.xlabel('time (s)'); plt.ylabel('Undamped') 28 plt.show() |
1 # importing all functions from pylab module 2 from pylab import * # Not the preferred methodology. Means to bring everything in to the top level name space 3 x = arange(1, 10, 0.5); print(x) 4 xsquare = x**2; print(xsquare) 5 xcube = x**3; print(xcube) 6 xsquareroot = x**0.5; print(xsquareroot) 7 figure(1) # open figure 1 8 plot(x, xsquare) # basic plot 9 xlabel('abscissa') # add a label to the x axis 10 ylabel('ordinate') # add a label to the y axis 11 title('A practice plot') # add a title 12 savefig('plot_1.png') # save the figure to the current diretory 13 figure(2) # open a second figure 14 plot(x, xsquare,'ro',x,xcube,'g+--') # Two plots. Red circles with no line. Green plus signs joined by a dashed curve 15 xlabel('abscissa') # x and y labels, title 16 ylabel('ordinate') # x and y labels, title 17 title('More practice') # x and y labels, title 18 legend(('squared', 'cubed')) # add a legend 19 savefig('plot_2.png') # save the figure 20 figure(3) # open a third figure 21 subplot(3,1,1); plot(x,xsquareroot,'k*:')# Black stars+dotted line 22 title('square roots') # add a title 23 subplot(3,1,2); plot(x, xsquare,'r>-') # Red triangles+dashed line 24 title('squares') # add a title 25 subplot(3,1,3); plot(x, xcube,'mh-') # Magenta hexagons+solid line 26 title('cubes') # add a title 27 savefig('plot_3.png') # save the figure 28 show() |
1 ######### How to find documentation ######### 2 # The dir(module) function can be used to look at the namespace of a module or package, i.e. to find out names that are defined inside the module 3 # The help(function) function is available for each module/object and allows to know the documentation for each module or function 4 # 5 import math 6 dir() 7 dir(math.acos) 8 help(math.acos) 9 import matplotlib.pyplot 10 dir(matplotlib.pyplot) |