Python Basics
Trevor Watkins [email protected] Joy Su [email protected] Vishnu Deepak [email protected]Logistics (Etherpad, Code of Conduct, Breaks, etc)
Learning Objectives
• Understand the importance of design and problem solving in coding
• Create a simple algorithm using (pseudocode) • Understand the different uses of Python
Why Python
• Python is a high-level programming language • Open source and community driven
https://www.python.org/community/ ,
stackoverflow, support, etc
• Source can be compiled or run just-in-time • Great first language to learn how to code
Why Python?
• “Tried and true” language that has been in development since 1991
• Can interface with Open Source GIS toolsets • Can create applications
• System administration • Cross platform
• Machine learning • Data Analytics
Why design is so important
• You can’t build a building without a blueprint • You can’t bake a cake without the instructions • Design is about being a great problem solver • Have you ever heard of Algorithms?
• Pseudocode = Algorithm • Flowchart = Algorithm
Pseudocode
• Generally written in the language that you speak
• Example: Bake a cake, ingredients,
instructions: Preheat oven to 350 degrees, mix cake, eggs, butter, and milk in a saucepan, mix ingredients in saucepan for 10 minutes on
medium, pour into cake sheet, leave in oven for 35 minutes.
Pseudocode
Now you try 5 minutes!
• How do you make a peanut butter and jelly
sandwich? Show us your process by writing an algorithm in pseudocode
• Write an algorithm in pseudocode using the Etherpad:
An example for coding
• I want to take the average of three numbers • Algorithm is as follows:
• Start program
• Input three numbers
• Take the sum of those three numbers and divide by 3
• Output answer • End program
Flowchart
• Visual representation of an algorithm that shows the flow of logic of your program
Flowchart example
Start Program
Input three values
Calculate sum of values entered, divide by number
of values
Output result
Lets play around!
• Hello Workshop Attendees
Print(“Hello Workshop Attendees”)
• Prints Hello Workshop Attendees to standard out
• Open Spyder and try it out yourself • Follow along using Spyder
More than just printing
• Python is an object-oriented language
• Practically everything can be treated as an object
• “Hello Workshop Attendees” is a string
• Strings, as objects, have methods that return
String Methods
• Assign a string to a variable • In this case “fname”
• fname.title() • fname.upper()
• fname.isdigit() • fname.islower() • fname.split()
String Methods
• The string held in your variable (fname) remains the same
• The method returns an altered string Uppercase
“TREVOR”
• Changing the variable requires reassignment
– fname = hw.upper()
Variables and simple data types
• Every variable is connected to a value, which is the information associated with that variable
• Some Rules
• Variables can only contain letters, numbers, and underscores
• Can only began with a letter or underscore, not with a number
• Spaces are not allowed
• No python keywords, for, while, etc.
• Must be mnemonic: A name that makes sense for your code
Violations will result in Syntax error
Spyder will show you that an error exists before you try to run the code
If you run it anyway, it will show you the error and error type
A Syntax error is an incorrectly placed command or instruction that causes a failure in execution
Variables and simple data types
• Integers: (whole numbers) you can +, -, *, and /• Two ** denotes exponents
• Floats: (Any number with a decimal point)
• Dividing any two numbers in Python will result in a float, even if the
numbers are both integers, and if one of the numbers in the operation is a float
As you can see spacing is optional, however, try to use spacing, which is good programming practice and makes your code more readable. Python forces spacing in some situations
Comments
• # anything following the hash mark is ignored by the python interpretor
• Can also use “”” “””, or ‘’’ ‘’’ where you can write anything you want in between the triple quotations
Recap work (Coding rooms) 5
minutes
• Place a comment before your code
• Assign your favorite place to travel to a variable (assign a string to a variable).
• Use the string method .upper to alter the string.
• Assign a numerical value to two variables. • Post your code in the Etherpad. (Put your
name first and then paste your code afterwards.
Data Structures
• Are used to group and organize data • Used for similar or related data
• There are python defined data structures • But….you can also create your own data
structures
Lists
• Think of a list as a stack of cards, on which your information is written
• The information stays in the order you place it in until you modify that order
• Methods return a string or subset of the list or modify the list to add or remove components • Written as var[index], index refers to order
within set (think card number, starting at 0) • Square brackets indicate a list []
Coding Room 5 (minutes)
Write a program that shows a list of 5 of your favorite animals, display the names of the
animals, add a new animal to the list and display the list. Call the program animals.py
Post your code in the Etherpad. (Put your name first and then paste your code afterwards).
Dictionaries
• Dictionaries are sets of key & value pairs
• Allows you to identify values by a descriptive name instead of order in a list
• Keys are unordered unless explicitly sorted • A key value can be a number, string, list, or
another dictionary
Sets
• A set is a collection which is unordered and unindexed. In Python sets are written with curly brackets.
• Sets are unordered, so you cannot be sure in which order the items will appear.
• You cannot access items in a set by referring to an index, since sets are unordered the
Conditional Branching
If else statement
• if and else
if variable == condition:
#do something based on v == c
else:
#do something based on v != c
• elif allows for additional branching
if condition:
elif another condition: …
else: #none of the above
Python supports the usual logical conditions from mathematics:
Equals: a == b Not Equals: a != b Less than: a < b
Less than or equal to: a <= b Greater than: a > b
For Loops
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
• This is less like the ”for” keyword in other
programming languages, and works more like an iterator method as found in other object-orientated programming languages
• The for loop does not require an indexing variable to set beforehand.
Break Statement
• With the break statement we can stop the loop before it has looped through all the items:
Continue
• With the continue statement we can stop the current iteration of the loop, and continue
Functions
• A function is a block of code which only runs when it is called.
• You can pass data, known as parameters, into a function.
• A function can return data as a result. • In Python a function is defined using