Training Up: Intro to Python Nicole Lama
Overview Applications of Python Essential Programming Terms Python Syntax Basics in Python
Python First Introduced in 1990 by Guido van Rossum Popularized in 2004 by Google Pros: user-friendliness, readability, generalizability
Python Applications include: Statistical Analysis Data Mining Software Development Data Visualization Machine Learning and more!
Python Cons: Can be slow (integration with C speeds things up) Relative to other programming languages, debugging can be more time consuming
Programming Terms Data Types – integers (2), strings (“Jane”), floats (2.2), Boolean(True or False) Operators – +, -, <, >, ==, and, or, is, not,!
Programming Terms Data Structures – Things that can store data/information List, Array Dictionaries, HashMaps Trees Queues, Stacks Blockchain
Lists List = [element0, element1, …, elementn] Access : List[0] will output the first element List[n] will output the nth element List = [“Shalini”, 2, True] Can contain different data types!
Dictionaries Dictionary = {Key : Value} Access : Dictionary[Key] = Value Dict = {“Nikhita”: 24, “Joseph”: 18} Dict[“Nikhita”] output: 24
Programming Terms Variable – an object you can store data into, and access later. Use camelCase or under_scores Function – a callable routine which may return a value. Useful for repeating procedures many times Argument – a variable, or data, accepted by function Library – an outside collection of functions. Useful so you don’t have to write your own functions.
Programming Terms Commenting – # or ‘’’. Useful for leaving notes or instructions. Will not be read by Python Errors – Indicative of bugs in your code. Usually cause your script to crash. Warnings – Indicative of some issue with your code but typically will not crash your script Ex: DeprecationWarnings, RunTimeWarnings
Python Syntax Variable Var = “a unit that stores data types/information” Ex: Num = 3 Str = “Hello!” Flt = 3.3 *Variable names can be anything you want!!
Python Functions func() will print out whatever you feed it as an argument Def func(a): Print(a) Identations matter in Python! #call your function after defining it func(“Hi!”) Calling your function like this will print “Hi!”
Python Functions Function with return: Def func(a): Print(a) return 1 If return is used, make sure to assign variable to “catch” your value. Return will end your function. catchValue is now equal to 0 catchValue = func(“Hello”)
Python Syntax Argument: input for your function to do work on Func(a)
Python Syntax Library: package with useful functions you can use import numpy or import numpy as np from numpy import add
Python Syntax Comments: useful for adding notes or instructions in code. Not read by Python. # This is a comment ‘’’ This is a longer comment that spans multiple lines ‘’’
Common Python Errors Syntax Error : missing “, ‘ , or : ? Missing Indentation error List index out of range: Tried to access an element that exceeds list size Segmentation Fault: You ran out of memory. Happens with For and While loops on occasion Keyword error: happens when trying to access a non existing key in a dictionary
Common Python Errors NameError: Variable was called but never assigned TypeError: Check your datatypes E.g. Don’t’ do math operations on strings https://pythonforbiologists.com/29-common-beginner-errors-on-one-page/
Fixing Python Errors Traceback (most recent call last): Tells you where your bug is Traceback (most recent call last): File "C:/Users/nicol/Desktop/IntroToPython.py", line 122, in <module> blah NameError: name 'blah' is not defined Will tell you error type. Variable was never defined in this case
Python Built-In Functions Useful tools that the developers included in Python to make your life easier
Python Built-In Functions Print(*objects) Purpose: display value of something Argument : Any variable, or data type Returns: nothing https://www.programiz.com/python-programming/methods/built-in/print
Python Built-In Functions Functions to transform data types: Int(obj) Float(obj) Str(obj) List(obj)
Python Built-In Functions : String Methods Methods specifically made for strings Super useful for manipulating any data All return a modified string Ex: “hello!”. capitalize()
Python Built-In Functions : String Methods str.upper() str.lower() str.capitalize()
Python Built-In Functions : String Methods “sep”.join(iterable) Purpose: will join together a list of things into one string Ex: “-”.join([“Built”, “In”]) output: “Built-In” * Sep can be any separator: commas, periods, dashes, even words!
Python Built-In Functions : String Methods str.replace(replaceMe,withThis) Replace anything in a string with something else Ex: “I can’t do it”.replace(“can’t”, “can”) output: I can do it
Python Built-In Functions : String Methods str.split(sep) Purpose: will split a string into a list Ex: “Rose, Lilac, Daisy”.split(“,”) output: [“Rose”, “Lilac”, “Daisy”]
Python Built-In Functions : String Methods str.strip() What we see: “ I’m a sentence! ” What Python sees: “\tI’m\sa\ssentence\s\s\s\s”
Python Built-In Functions : String Methods str.strip() Purpose: Get’s rid of white space in a string Ex: “ I’m a sentence! ”.strip() output: “I’m a sentence!”
Python Built-In Functions : List Methods list. append() list. extend() list. count() list. pop() list. reverse() list. clear()
Python Built-In Functions : Dictionary Methods dict. values() dict. keys() dict. get()
Python Built-In Functions : Reading External Files inFile = open(“C:\Users\nlama\example.txt”) do stuff with inFile inFile.close()
Programming Terms If Statements- Do something only if a condition is met For Loops- To repeat something a certain amount of times While Loops- To repeat something until a condition is met
Python Operators +,-,%,* : Math operators == : is equal to <, > : less than, greater than <= : less than or equal to ! : is not is, not: and, or: logical operators
Python Operators 8 <= 9 Output: True 8 is not 9 8 != 9
Python Syntax If statement x = 0 if (x < 0): print("Negative number")
Python Syntax For loop numbers = [1,2,3,4] for (num in numbers): print(num*2)
Python Syntax While loop i = 0 while(i < 6 ): print(i) i=i+1 *i=i+1 is the same as i+=1
Additional Info Popular Libraries in Python: -numPy : General Math -pandas : Dataset Manipulation -sklearn, sciPy: Statistics -matplotlib, seaborn, bokeh : Data visualization -random : Random number gen, Distributions -sys, os, csv : Accessing and Reading files
Additional Info When to indent in Python: http://www.peachpit.com/articles/article.aspx?p=1312792&seqNum=3
Additional Info https://www.w3schools.com/python/python_intro.asp https://www.codecademy.com/learn/learn-python https://www.python-course.eu/advanced_topics.php