#!/usr/bin/env python # coding: utf-8 # # *This notebook contains course material from [CBE30338](https://jckantor.github.io/CBE30338) # by Jeffrey Kantor (jeff at nd.edu); the content is available [on Github](https://github.com/jckantor/CBE30338.git). # The text is released under the [CC-BY-NC-ND-4.0 license](https://creativecommons.org/licenses/by-nc-nd/4.0/legalcode), # and code is released under the [MIT license](https://opensource.org/licenses/MIT).* # # < [Python Basics](http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/01.02-Python-Basics.ipynb) | [Contents](toc.ipynb) | [Python Numeric Integration Revisited](http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/01.04-Python-Numeric-Integration-Revisited.ipynb) >

Open in Colab

Download # # Python Conditionals and Libraries # ## A Tutorial by Jacob Gerace # ## Conditionals in Python # In[24]: #Sometimes you want to execute code only in certain circumstances. #Change answer and see what code is executed: answer = 42 if answer == 42: print('This is the answer to the ultimate question') elif answer < 42: print('This is less than the answer to the ultimate question') else: print('This is more than the answer to the ultimate question') print('This print statement is run no matter what because it is not indented!') #An if statement is an example of a structure that creates a new block. The block includes all of the code that is #indented. The indentation (tab character) is imperative. Don't forget it! #This is normally just good coding style in other languages, but in python it isn't optional #We can check multiple things at once using boolean operations snowy = True day = "Monday" #How long does it take me to get to class in the morning? if (snowy == False) and (day != "Monday"): #and is boolean and. True only if both are true. False otherwise time = 7 elif (snowy == True) and (day == "Monday"): time = 11 elif (rainy == True) or (day == "Monday"): time = 9 print("It takes me %d minutes" %(time)) #You can structure these statements more neatly if you "nest" if statements (put an if statement inside an if statement) #But this is just for edification. # ## Functions in Python # In[15]: #We can separate off code into functions, that can take input and can give output. They serve as black boxes from the #perspective of the rest of our code #use the def keyword, and indent because this creates a new block def print_me( string ): print(string) #End with the "return" keyword return #Your functions can return data if you so choose def step(x): if (x < 0): return -1 elif (x > 0): return 1 #call functions by repeating their name, and putting your variable in the parenthesis. #Your variable need not be named the same thing, but it should be the right type! print(step(-1)) print(step(1)) #what happens for x = 0? print(step(0)) #Python automatically adds in a "return none" statement if you are missing one. #If you see "none" make sure your program can work with that! #Fix the return none issue def step_v2(x): if (x < 0): return -1 elif (x >= 0): return 1 print(step_v2(0)) # ## Numpy - "The Fundamental Package for Scientific Computing with Python" # In[16]: 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. #You can call that variable whatever you like, but 'np' is standard. #numpy has arrays, which function similarly to python lists. a = np.array([1,2,3]) b = np.array([9,8,7]) #Be careful with syntax. The parentheses and brackets are both required! print(a) #Access elements from them just like you would a regular list print(a[0]) #Element-wise operations are a breeze! c = a + b d = a - b e = a * b f = a / b print(c) print(d) print(e) print(f) #This is different from MATLAB where you add a dot to get element wise operators. #What about multi-dimensional arrays? Matrices! #You just nest lists within lists! A = np.array( [[1,2,3], [4,5,6], [7,8,9]] ) B = np.array( [[1,1,1], [2,2,2], [3,3,3]] ) #Then matrix multlication C = np.matmul(A,B) print(C) #Or determinants: print(np.linalg.det(A)) #Now, let's use numpy for something essential for you: Numeric Integration #Define the function you want to integrate.... #dy/dt = t: def deriv(y,t): return t #Note this doesn't use y in the return. That is okay, but we need to include it just to satisfy the function we will use. #Set your initial or boundary condition IC = 0 #Give the number of points to evaluate the integration start_time = 0 end_time = 10 num_times = 101 times = np.linspace(start_time, end_time, num_times) from scipy.integrate import odeint integrated_func = odeint(deriv,IC,times) #Can we plot the result? You betcha. Just import a new package get_ipython().run_line_magic('matplotlib', 'inline') import matplotlib.pyplot as plt from ipywidgets import interact plt.plot(times, integrated_func) plt.title("y = (1/2)t^2") #Very similar to MATLAB! # ## Additional Resources # * If you still feel VERY lost: [Code Academy](https://www.codecademy.com/learn/learn-python) # # * If you want a good reference site: [Official Python Reference](https://docs.python.org/3/reference/) # # * If you want to learn python robustly: [Learn Python the Hard Way](https://learnpythonthehardway.org/book/) # # * Feel free to contact me at: **jgerace (at) nd (dot) edu** # # In[ ]: # # < [Python Basics](http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/01.02-Python-Basics.ipynb) | [Contents](toc.ipynb) | [Python Numeric Integration Revisited](http://nbviewer.jupyter.org/github/jckantor/CBE30338/blob/master/notebooks/01.04-Python-Numeric-Integration-Revisited.ipynb) >

Open in Colab

Download