Reid Otsuji
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # UC San Diego School of Global Policy and Strategy Skills Course # 3 weeks - Introduction to Python 1/28/2019 - 2/11/2019 GPS Auditorium: 6:00 - 9:00pm TritonEd Schedule: Posted in TritonEd --- ## Instructors: Bia Villas Boas Reid Otsuji TA: Caio Mansini Helper: Arden Tran, Gui Castelao # TAKE SURVEY https://goo.gl/forms/Fqkgnz0Q6RxtD7Bo2 # Collaborative note taking! ### Need Help? - #### If you need help- put a pink sticky on your laptop so an instructor can come assist - Also, your instructors/helpers are on HackMD here, so feel free to throw a question or ask for help via the notes here as we go along ## Python Day 1 ### Getting Started - Get data here: https://swcarpentry.github.io/python-novice-inflammation/setup/ - if you have a mac, double-click the downloaded .zip files to unpack them - they'll create the 'data' and 'code' folders automatically...along with the necessary data. - You should end up with 2 folders - 'data' and 'code'. - make sure they're located in an easy to find place like your Desktop - Go to your terminal - for mac: shortcut to Spotlight by pressing `CMD` + `SpaceBar` and then type in `terminal` - Run the command to open Jupyter Notebooks in your terminal by entering `jupyter notebook` and hit enter Some info about the Jupyter Notebook environment and Python programming language in general: ` # this is a comment` Use the `#` symbol to denote a comment within your Jupyter Notebook - this is also frequently used a means to help document your analysis and code for your collaborators ### Running some code in Jupyter - You can run code within the Jupyter Notebook kernel and it will allow you to program and see the direct output all within a single document ``` # this is a comment # multiplication in Python with the * operator 5 * 3 output = 15 # assigning variables with the assignment operator = weight_kg_text = 'weight in kilograms' print(weight_kg_text) ``` output: `weight in kilograms` Overview of conceptO: we made an arbitrary variable name with `weight_kg_text` and then used the assignment operator `=` to assign that variable to the value `'weight in kilograms'` and then we used the `print()` function to output the value of the variable by using the `print()` function with the argument `weight_kg_text` like this: `print(weight_kg_text)` What is an argument? In Python and many programming languages, the functions or commands you'll run will have arguments that help define the desired output. In basic terms, arguments are extra instructions given to a function so that it knows what to do! For example, the `print()` function has many arguments you can pass along, but for this start we will just focus on the first argument that looks like this: `print(argument1)` ### Exercise 1: ``` a = 1 b = a a = 2 print("a =", a) print("b =", b) ``` What's the output? ### Exercise 2: What does `print(third, fourth)` shows after you run: ``` first, second = 'global', 'policy' third, fourth = second, first ``` What's the putput? ### Python in the Kitchen: Libraries - a library is to python as a kitchen appliance is to a kitchen - Libraries have Functions/Modules - To access a library, use the `import` statement like so: ``` import numpy numpy.loadtxt(fname = 'inflammation-01.csv', delimiter = ',') ``` Library and function/module syntax (i.e. how do I do that function call?) Syntax for calling on a library's function/modules is this: `v` What happens when you don't add an argument to a function? Python resorts to default values, which is set by the library/module/function Need help with a library/function/module? - Use the help statement `?` following the lib/function/module you need help with like this: `numpy.loadtxt?` - Python will pull up the documentation on that specified item for you - if that fails - google time! ### Arguments continued... ``` numpy.loadtxt(fname = 'inflammation-01.csv', delimiter = ',') print(type(data)) print(data.dtype) print(data.shape) #returns a tuple with x = rows, y = columns ``` ### Numpy Arrays - first of all, Numpy is a portmanteu of numbers and python, hence NumPy - you'll find a lot of Python libraries have some sort of name origin that ties in with Python. - Numpy arrays have the attribute shape - shape gives you the dimensions of the array in the format [rows x columns] - we can check the value of an array at a specific position by specifying indices: data[1,2] ``` print('first value is:', data[0,0]) ``` output: `first value is: 0.0` ``` print('middle value is:', data[30,20]) ``` output: `middle value is: 13.0` #### Slicing with `:` ``` print(data[0:4, 0:10]) ``` - Remember that number sequencing in Python starts with `0` and when sliced, the last number argument will be omitted. For example: - `0:4` will give you `0,1,2,3` - which is 4 values ``` print(data[5:10, 3:5]) print(data[0,0:10]) #example of syntax shortcut with slicing small = data[:3, 36:] # data[0:3, 36:40] print(small.shape) print(data.shape) double_data = data * 2 print(double_data) print('original') print(data[:3,36:]) print('double') print(double_data[:3,36:]) trip_data = data + double_data print(trip_data[:3,36:]) print(small.shape) print(numpy.mean(data)) ``` Ok, more complexity: ``` maxval, minval, stdval = numpy.max(data), numpy.min(data), numpy.std(data) print('maximum is:', maxval) print('minimum is:', minval) print('standard deviation is:', stdval) ``` The above code is the same as: ``` maxval = numpy.max(data) minval = numpy.min(data) stdval = numpy.std(data) ``` Regarding our data and approach: ``` patient_0 = data[0, :] #how do I select all the data for patient_0? print(patient_0.shape) print(numpy.max(patient_0)) numpy.max(data, axis = 1) #What does the axis option do? is 1=column? finding the max in each column? Nevermind, got crossed up - check out: https://i.stack.imgur.com/p2PGi.png Hold on, getting reference cheat sheets for you all max_infla = numpy.max(data, axis = 1) print(max_infla.shape) ``` ELI5 this voodoo pls: ``` print(data[0, :]) print(data[1, :]) #what the heck happens? print(data[0, :]) # this one takes the first row, hence the 0 in the rows argument print(data[1, :]) # this one takes the second row, hence the 1 in the rows argument because everything in Python starts with 0, not 1. ``` Conceptually, let's break down what happens above: - `print(data[0, :])` is just a `print()` function with the argument for the object `data` and within `data` we also specified with `[0, :]` what portion of the object `data` we wanted the `print()` function to evaluate. - The `data[0, :]` is just us adding two arguments for starting and ending of the data - think back to algebra/geometry with planar X, Y coordinates. So, we are just specifying that the start of what we want from `data` is `0` and that's easy. The next part - the end of what we want from `data` is ` :` which is using the `:` slicing operator to denote the default slice values - so that translates to everything! So, we are asking `data` start at row 1 (because Python starts everything as 0) and then take everything after that. Hence, we are asking it to print all of row 1! ## Python and related cheat sheets - Cheat Sheets (link expires in 7 days): https://ucsdcloud-my.sharepoint.com/:b:/g/personal/artran_ucsd_edu/ERm-GDiD9pxAqtrlBu_7vbcBKIUqHW5JeKnLFrwol7h2Uw - Good to have in your back pocket - feel free to download a copy and save to your local drive - Courtesy of Data Science & Engineering master's program and HDSI (HALICIOĞLU DATA SCIENCE INSTITUTE) ### matplotlib ``` ave_infla = numpy.mean(data, axis = 0) print(ave_infla.shape) #now let's import pyplot from matplotlib library import matplotlib.pyplot # why the 'matplotlib.pyplot' and not just import all matplotlib? # Because we only need pyplot so this helps us save memory and create faster and more responsive code %matplotlib inline image = matplotlib.pyplot.imshow(datra) matplotlib.pyplot ave_infla = numpy.mean(data, axis = 0) ave_plot = matplotlib.pyplot.plot(ave_infla) matplotlib.pyplot.show() ``` ``` max_plot = matplotlib.pyplot.plot(numpy.max(data, axis = 0)) matplotlib.pyplot.show() min_plot = matplotlib.pyplot.plot(numpy.min(data, axis = 0)) matplotlib.pyplot.show() ``` - Do we need to run show? On Jupyter Notebook upon running the `%matplotlib inline` statement, you won't actually need to use `matplotlib.pyplot.show()` to show the image. However, we add that in for cases where we may be exporting this notebook elsewhere that would require the show method to bring up the image. ``` import numpy import matplotlib.pyplot data = numpy.loadtxt('inflammation-01.csv', delimiter = ',') #make a plot that has one row and three columns - max, min, mean fig = matplotlib.pyplot.figure(figsize = (10, 3)) # figsize argument (width, height) ratio axes1 = fig.add_subplot(1, 3, 1) #(rows, columns, which subplot) axes2 = fig.add_subplot(1, 3, 2) axes3 = fig.add_subplot(1, 3, 3) axes1.plot(numpy.max(data, axis = 0)) axes1.set_ylabel('Max Inflammation') axes2.plot(numpy.min(data, axis = 0)) axes2.set_ylabel('Min Inflammation') axes3.plot(numpy.mean(data, axis = 0)) axes3.set_ylabel('Average Inflammation') matplotlib.pyplot.show() fig.tight_layout() matplotlib.pyplot.show() ``` ### Exercise 3: Write a code that plots the average, maximum, minimum, and standard deviation aacross the patients as four subplots. | Average | Standard Deviation | | ----------- | -------------------| | Maximum | Minimum | Solution (you can rearrange into order by renumbering axes1-4): ``` #let's resize the fig fig = matplotlib.pyplot.figure(figsize = (16, 4)) axes1 = fig.add_subplot(1, 4, 1) axes2 = fig.add_subplot(1, 4, 2) axes3 = fig.add_subplot(1, 4, 3) axes4 = fig.add_subplot(1, 4, 4) axes1.plot(numpy.max(data, axis = 0)) axes1.set_ylabel('Max Inflammation') axes2.plot(numpy.min(data, axis = 0)) axes2.set_ylabel('Min Inflammation') axes3.plot(numpy.mean(data, axis = 0)) axes3.set_ylabel('Average Inflammation') axes4.plot(numpy.std(data, axis = 0)) axes4.set_ylabel('Standard Deviation') matplotlib.pyplot.show() fig.tight_layout() matplotlib.pyplot.show() ``` ## Week 1 - Please sign in below: ##### Name (A ### ) Reid Otsuji (A12345678) Yifan Dong(A53256391) Camila Gomez Wills (A53265648) Navdhrishty Singh (A12972272) Isabelle Chen (A12692259) Greg Householter (A53288838) Yi Liu (A53257075) James Lee (A53272394) Hui Zhang(A53248115) Kelis Wong (A53233278) Noah Gerber (A11844436) Savas Tarhan (A53222479) Qinghui Zhang (A14166055) Zixuan Dai (A53270250) Jiahang Zhang (A53278367) Diego Jimenez (A92016548) Gala Ledezma (A12804158) Cesar Perez (A53265549) XINYU ZHANG(A53287451) Inderpal Pamma (A53282970) Wenlin Zhao(A53271207) Renee Johnson (A12699790) Yucheng Shen (A53290227) Ha Pham (A53257685) Grace Yuan(A53274857) Yunzhou Luo(A53233781) Sibo Su (A53255631) Hannah Ashby (A13026919) Wenhan Zhu (A53277425) Malena Hernandez (A53289951) Jicuo Dai(A53251206) Anh Nguyen (A53245210) Julian Del Castillo (A12825937) Katherine Tian (A12828524) Paul Koenig (A12629448) Nick Rhodes (A11893860) JingTing Xu (A53281950) Yifan Huang (A53268424) imge su cetin Mingpu Xiao (A53281212) Wendy Romero (A53217156) Xuan Gu(A53291635) Qiurong Ren (A53281118) Grace Yuan(A53274857) Qiaochu Cong(A53290453) Wendy Romero (A53217156) Courtney Geigle (a00310086) --- ## Python Day 2 ### Repeating Actions with loops - range() function ``` for counter in range(N): #(do things with counter and other variables, N times) ``` - Let's open Jupyter Notebook by going to our terminal and typing `jupyter notebook` - open a new Python 3 notebook and for ease, try to open in the same folder you have your datasets we downloaded last week ``` for counter in range(3): print(counter) #remember to get that walk-in indent before print(counter) ``` Output should be: ``` 0 1 2 ``` ### Exercise 1: - Python has a built-in function called **range** that creates a sequence of numbers. Range can accept 1, 2, or 3 parameters. - If one parameter is given, range creates a sequence of that length, starting at zero and incrementing by 1. For example, range(3) produces the numbers 0,1,2 - If two parameters are given, range starts at the first and ends just before the second, incrememting by one. For example, range(2, 5) produces 2, 3, 4. - If range is given 3 paramters, it starts at the first one, ends just before the second one, and increments by the third one. For example, range(3, 10, 2) produces 3, 5, 7, 9. - Using python's built-in functions **len** and **range**, complete the loops below so that it prints **every other** letter of 'sociology' `len()` = short for Length and is a built-in function to return the number of characters in the argument you input. ``` word = 'sociology' for i in range(0,len(word),2): print(word[i]) ``` Alternatively, ``` for i in range(0,len('sociology'),2): print(word[i]) ``` ### Repeating Actions with Loops - Tracking Variables ### Challenge: - Python allows you to create an empty string by assigning empty quotes to variables - `my_variable = ''` - Knowing that two strings can be concatenated using the `+` operator, write a loop that takes a string and produces a new string with the characters in reverse order, so that 'pizza' becomes 'azzip' ``` word = 'pizza' for i in range(len(word)-1, -1, -1): print('i = ', i, word[i]) ``` Solution: ``` word = 'pizza' for i in reversed(word): print(i) ``` The above takes into use the built-in python function `reversed()` Another solution: ``` word = 'pizza' for i in word[::-1]: print(i) ``` The above takes into account what we learned about slicing lists and using the slicers `:` **Write that answer here:** ________________________ ``` string1 = 'p' string2 = 'i' string3 = 'z' string4 = 'z' string5 = 'a' print (string5 + string4 + string3 + string2 + string1) pizza="pizza" azzip="" for i in range(len(pizza)): azzip=pizza[i]+azzip print(azzip) word='pizza' b='' for i in range(len(word)-1,-1,-1): b= b+ word[i] print(b) word = 'pizza' my_variable = '' for i in word: my_variable = i + my_variable print(my_variable) ``` ________________ ### Important note on a mistake you want to avoid: ``` print = 'foo' for i in range(10): print(i) ``` You get this error: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-82-32dd6fa70972> in <module> 1 for i in range(10): ----> 2 print(i) TypeError: 'str' object is not callable ``` Why? Because `print` was used as a variable name and assigned a value, so when we try to run the `print()` function, we get the above error. Stay woke. Variable names creepin'. ### About Markdown ``` # This is a comment ``` - We can turn a cell in our Jupyter Notebook into a Markdown cell rather than a Python3 cell. This let's us avoid having to use the `#` everytime we want to make a comment and just format with Markdown! - Go to `cell` and then choose `cell type` and then select `Markdown` - This let's us format in the cell with headings like below: `# Level 1` # Level 1 heading `Level 2` ## Level 2 heading `**bold**` **bold** `*italics*` *italics* ### Python, Jupyter, Markdown, etc. Cheat Sheets: - download here: [Link expires in 14 days, so get and download now](https://ucsdcloud-my.sharepoint.com/:f:/g/personal/artran_ucsd_edu/ElIRBJImwLJCuTj8qp2wKxQB0EJVaUNz5Ra-7hrW5kN-6g) ### Storing Multiple Values in Lists ``` odds = [1, 3, 5, 7] print(odds) print('first and last are', odds[0], odds[-1]) s = 'string' print('I think', s[-1], 'is equal to', s[5]) for number in odds: print(number) for char in 'string': print(char) ``` ### Important note: can use the term `banana` or whatever in lieu of `char` ### Strings and immutability ``` my_word = 'Brasil' my_word[3] = 'z' ``` We get the error: ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-94-5d1222434421> in <module> ----> 1 my_word[3] = 'z' TypeError: 'str' object does not support item assignment ``` We cannot change an immutable object such as a string, and need to either reassign it completely with `my_word = 'Brazil'` We can change lists via index like so: ``` countries = ['France', 'Australia', 'Brasil'] print(countries[2]) print('countries[2] was', countries[2]) countries[2] = 'Brazil' print('Now, countries[2] is', countries[2]) ``` ### Nesting Lists (lists inside of lists inside of lists inside of lists) - remember the salt and pepper shaker example ``` list_of_lists = ['1', ['avocadoes', 'jalapenos'], 3, ['other things', 'and some more']] print(list_of_lists) ``` - alright, now how do I get jalapenos? ``` print(list_of_lists[1][1]) ``` - Should get jalapenos ### Append function ``` empty = [] empty.append(9) print(empty) empty = empty + ['surf'] print(empty) ``` ### reverse() method ``` odds.reverse() print('odds after reversing', odds) ``` The above method does change the list permanently, so when you call the list `odds` it will now be in the reversed order. ### Exercise 2: - Use a for-loop to convert the string 'surf' into a list of letters: ['s', 'u', 'r', 'f'] Solution: ``` list_wanna = [] word='surf' for i in range(len(word)): list_wanna=list_wanna+[word[i]] print(list_wanna) ``` ``` list = [] word = 'surf' for i in word: list.append(i) print(list) ``` the above is an example of using for-loops to iterate and this is a microscopic example but the power of for-loops is hugely demonstrated with large datasets that will require its iterative functionality. ``` print(list('surf')) ``` The above is a great example of Python's concise code and built in functions ``` jedi_name = 'Luke Skywalker' first_name = jedi_name[0:4] print(first_name) ``` ## Using ranges to extract values from a list: ``` planets = ['Tatooine', 'Naboo', 'Jupiter', 'Arrakis'] star_wars_planets = planets[:2] print(star_wars_planets) ``` The difference between the extremas (first and second values) in a range with a slice `:` is the total number of elements. For example, `[0:2]` would mean trhe two extremas difference calculated as 2-0 = 2. So if we extracrted values from a list with the range `0:2` we would get two elements. In this case, that would be 'Tatooine' and 'Naboo' ``` #this counts 0 - 10 for i in range(10): print(i) #this counts 0 - 10 by every 3rd value (think Lil Jon's song - 3, 6, 9) for i in range(10)[::3]: print(i) ``` # Use stepsize index to print every other charactere “In an octopus’s garden in the shade” use the \ to enter a break to help compile strings with quotations or apostrophes in the string value like so: ``` string = 'In an octopus\'s garden in the shade' print(string[::2]) ``` ### Let's get this data - in Jupyter, whenever you start the notebook, you'll typically be taken to a file directory system - use that directory system to navigate to where we stored the data from last class (try your desktop) - Start a new notebook ### glob ``` import glob print(glob.glob('inflammation*.csv')) ``` The list is more disorganized than Congress, let's sort this, fam: ``` print(sorted(glob.glob('inflammation*.csv'))) ``` And let's import numpy and matplotlib.pyplot and grab those files ``` import numpy import matplotlib.pyplot filenames = sorted(glob.glob('inflammation*.csv')) sub_set = filenames[0:3] for f in sub_set: print(f)+ data = numpy.loadtxt(f, delimiter = ',') fig = matplotlib.pyplot.figure(figsize = (10,3)) ax1 = fig.add_subplot(1, 3, 1) ax2 = fig.add_subplot(1, 3, 2) ax3 = fig.add_subplot(1, 3, 3) ax1.plot(numpy.mean(data, axis = 0)) ax1.set_ylabel('average') ax2.plot(numpy.max(data, axis = 0)) ax2.set_ylabel('maximum') ax3.plot(numpy.min(data, axis = 0)) ax3.set_ylabel('minimum') fig.tight_layout() ``` ### Arguments and kwargs (Key Word Arguments) [ELI5 on Args and kwargs](https://pythontips.com/2013/08/04/args-and-kwargs-in-python-explained/) ### Great work, fam - see you next week fellow kids ## Write your notes here: ## Week 2 - Please sign in below: ##### Name (A ### ) Diego Jimenez A92016548 Inderpal Pamma A53282970 Kelis Wong A53233278 Wenlin Zhao A53271207 Zixuan Dai A53270250 Jicuo Dai A53251206 Isabelle Chen (A12692259) Yucheng Shen (A53290227) Noah Gerber (A11844436) Yifan Dong (A53256391) XINYU ZHANG(A53287451) Qiurong Ren (A53281118) Qiaochu Cong(A53290453) Qinghui Zhang(A14166055) Wenhan Zhu (A53277425) Savas Tarhan (A53222479) Greg Householter (A53288838) Anh Nguyen (A53245210) Navdhrishty Singh (A12972272) Yang Xuan (A14466001) Jiahang Zhang(A53278367) Yifan Huang(A53268424) Ha Pham (A53257685) Cesar Perez (A53265549) Katherine Tian (A12828524) Camila Gomez Wills (A53265648) Renee Johnson (A12699790) Valeria Buelna (A53247990) Yunzhou Luo (A53233781) Hui Zhang(A53248115) James Lee (A53272394) Yi Liu(A53257075) Wendy Romero (A53217156) Gala Ledezma (A12804158) Xuan Gu (A53291635) Sibo Su (A53255631) Paul Koenig (A12629448) # Python Day 3 ### Recap - Variables - Libraries - Numpy Arrays, indexing, slicing - reading data with `numpy.loadtxt` - for-loops - lists ### Cheat Sheets for Python, numpy, etc. - download here: [Link expires in 7 days, so get and download now](https://ucsdcloud-my.sharepoint.com/:f:/g/personal/artran_ucsd_edu/ElIRBJImwLJCuTj8qp2wKxQB0EJVaUNz5Ra-7hrW5kN-6g) - High-res and pre-formatted for printing into your own binder notebook ### Warm-up - Knowing that '' creates an empty string and that two strings can be concatenated using the + operator, write a loop that takes a string and produces a new string with the characters in reverse order, so 'stressed' becomes 'desserts'! ### Notes ``` oldstring = 'stressed' new_string = '' for char in oldstring: new_string = char + new_string print(new_string) ``` ## Python Conditionals (loops) ``` average = numpy.zeros([60,40]) count = 0 filenames = glob.glob('infla_data/inflammation*.csv') for f in filenames: print('processing file', f) data = numpy.loadtxt(f, delimiter = ',') average + average + data count = count+1 average = average/len(filenames) print(average.shape) ``` - Conditional statements ``` num = 37 if num > 100: print('greater') else: print('not greater') print('done') ``` ``` if num > 100: print('greater') else: print('not greater') ``` ### boolean values - "Boolean values are the two constant objects False and True. They are used to represent truth values (other values can also be considered false or true)." ### Exercise: ``` if 4 > 5: print('A') elif 4 == 5: print('B') elif 4 < 5: print('C') ``` ### Assignment vesus Equivalency `=` or `==` - the `=` operator is assigns a value like this: ` x = 'gon give it to you` - the `==` operator compares equivalency like so: ` x == rapper` which would yield a boolean of either true of false. In this case, false. ``` num = 10 if num > 3: print('greater') elif num == 10: print('equal') elif num < 3: print('not greater') ``` Output: `greater` - Why? Because the above conditionals are run in order and return the first value that resolves, and in this case that is 10 is greater than 3, ergo 'greater' Logical Operators `(num > 3) and (num = 10)` Output: False - Why? We're testing for both values with the `and` operator - so if any one of them is false, the return is false! `(num > 3) and (num <= 10)` Output: True ``` num = 20 (num > 3) or (num <= 10) ``` Output: True - Why? The logical operator `or` seeks only one value to be true to return true! ``` num = 10 cond1 = num >3 cond2 = num == 10 print('cond1 is ', cond1, ' and cond2 is ', cond2,'.', sep='') ``` Can we multiply them? Consider that booleans are read as either numeric values of 0 and 1 or True and False. So, yeah, we can multiple them! `print(cond1 * cond2)` output: `1` ### Scenario: - You are in charge of organizing the website for a symposium. In order to submit and abstract, participants have to create an account on the website. Write a Python program to check the validity of password input by users. - Validation: - At least 1 character from `[$#@]` - Minimum length 6 cahracters. - Maximum length 16 characters. - Ask your partner to make a password and test with your script. - tip: ``` string = 'THi$isastring' 'z' in string ``` password = 'jdsddd@' if len(password)<=6: print('too shot') elif len(password)>=11: print('too long') elif ('$' in password)+('@' in password)+('#' in password)<1: print('char') else: print('pass') ### doggo password script ``` print('gib password plz') password = input() chars = '@#$' for i in range(len(password)): if password[i] in chars: has_chars = True else: has_chars = False if len(password) < 6: print('TOO SMOL') elif len(password) > 16: print('TOO CHONK') elif has_chars is False: print('TOO BASIC') elif len(password) >= 6 and len(password) <= 16 and has_chars is True: print('GOOD BOYE') ``` password="" if ("$" not in password) and ("#" not in password) and ("@" not in password): print("password must contain $ # or @") elif len(password) < 6: print("password must contain at least 6 characters") elif len(password) > 16: print("password cannot contain more than 16 characters") password = 'Scrspp@' if '#@$' in password: print('right') elif len(password)>=6: print('right') elif len(password)<=16: print('right') else : print('wrong') password = 'giuihijhu$' if (len(password)>16) or (len(password)<6): print("Password must be between 6 and 16 characters") elif ('@' in password ) or ('$' in password) or ('#' in password): print("Good to go") else: print("Missing special character (@$#)") password = "tes@ting" for i in password: if i in ["@","$","#"]: specialcharacter = specialcharacter + 1 else: specialcharacter = specialcharacter + 0 if len(password) < 6: print("You need at least 6 characters") elif len(password) > 16: print("You need less than 16 characters") elif specialcharacter < 1: print("Your password must include $ # or @") else: print("You have a good password") http://swcarpentry.github.io/python-novice-gapminder/files/python-novice-gapminder-data.zip ## Week 3 - Please sign in below: ##### Name (A ### ) Greg Householter (A53288838) Paul Koenig (A12629448) Katherine Tian (A12828524) Kelis Wong (A53233278) Navdhrishty Singh (A12972272) Noah Gerber (A11844436) Savas Tarhan (A53222479) Jicuo Dai(A53251206) Hui Zhang(A53248115) Yi Liu(A53257075) Yang Xuan (A14466001) Jiahang Zhang (A53278367) Isabelle Chen (A12692259) Gala Ledezma (A12804158) Nick Rhodes (A11893860) Yucheng Shen (A53290227) Qiaochu Cong (A53290453) Wendy Romero (A53217156) James Lee (A53272394) Courtney Geigle (A00310086) Ha Pham (A53257685) Inderpal Pamma (A53282970) Diego Jimenez (A92016548) Camila Gomez Wills (A53265648) Yunzhou Luo (A53233781) Haotian Chen (A53257482) ### Gapminder Dataset http://swcarpentry.github.io/python-novice-gapminder/files/python-novice-gapminder-data.zip ### loading data into pandas ``` import pandas data = pandas.read_csv('data/gapminder_gdp_oceania.csv') ``` ``` data = pandas.read_csv('gapminder_gdp_oceania.csv',index_col='country') pirnt(data) ``` ## Pandas functions: ``` data.info() #() are used because this is a function ``` ``` data.columns #no () are used because it is a built in command ``` ``` data.T ``` Data set information: gapminder.org find the HDI Human Development Index - copy the link https://docs.google.com/spreadsheet/pub?key=tyadrylIpQ1K_iHP407374Q&output=xlsx ``` url = 'https://docs.google.com/spreadsheet/pub?key=tyadrylIpQ1K_iHP407374Q&output=xlsx' ``` ``` data = read_excel(url) ``` ``` data ``` ### Plotting data in Pandas ##### import matplotlib ``` import matplotlib.pyplot as plt #plt is an alias %matplotlib inline #prints plots to notebook ``` ``` df = americas.loc['Argentina'] df ``` ``` years = americas.columns.str.strip('gdpPercap_') years ``` ``` americas.drop(labels='continent',axis=1, inplace=True) #needed to use americas.drop to remove the continent column ``` ``` years = americas.columns.str.strip('gdpPercap_') # remove gdpPercap from headings to leave only years years ``` ``` americas.columns = years.astype(int) # convert years to integers ``` ``` americas.loc['Argentina'].plot() # plot data ``` ##### plot more data ``` #plot data with labels americas.loc['Argentina'].plot(label ='Argentina', marker ='o') americas.loc['Chile'].plot(label='Chile', marker ='o') #add another "--" line with markers americas.loc['Ecuador'].plot(label='Ecuador', linestyle ='--', marker='o') #add labels to plot plt.legend() plt.xlabel('year') plt.ylabel('GDP per capita') plt.savefig('americas.png', dpi=150) # save plot to file - there are different file types matplotlib can be save by changing file extentsion ``` ### check matplotlib.org gallery to see and make many more different plots programming in python plotting and programming in python

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully