Basic Python
[This material was heavily influenced by (stolen from) the UC Berkeley Python Bootcamp material.]
Compared to a lot of other programming languages, Python is easy to use and understand. This tutorial is just a quick introduction on how to use Python to get you started, and there are a lot of resources on the internet that will take you further.
Some basic info: What we're using is the Jupyter Notebook (often called "IPython Notebook"). You can type commands in each box (called a "cell"), and then push Shift+Enter to run them. The "+" sign near the top creates a new cell.
We're going to learn by doing. Every once in a while, there will be a Task, which will be a simple problem you have to solve using what you've just learned.
The only two rules we will be following: 1) When in doubt, try it out, and 2) the internet is your friend.
Getting Python to talk to us
Task: How would you say Hello Tim's World! or Hello "my" World!?
Python can be a calculator
Character Data Types
Task: What happens when you add any combination of ints, floats, and strings? Int+Int, Float+Float, Str+Str, Int+Float, Int+Str
Task: How do we get the right answer to the previous math expression?
Changing data types:
Using and Defining Variables
You drop a ball and want to know how far it falls in 1 second. The physics equation is: .
If it starts from rest (), then
You can solve the equation with python, using variables:
After changing t, what will happen to d?
So now we can calculate the distance, but it seems kind of silly to restate what "dist" is every time we change "t." This is where functions come in handy:
Defining and Using Functions
What is a function?
- A block of organized, reusable code that is used to perform a single, related action.
- Provides better modularity for your application and a high degree of code reusing.
- You can name a function anything you want as long as it:
- Contains only numbers, letters, underscore
- Does not start with a number
- Is not the same name as a built-in function (like print).
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-16-6860321472f5> in <module>()
----> 1 print dist('cat')
<ipython-input-15-5365f8063925> in dist(t)
1 def dist(t):
2 accel = 9.8
----> 3 answer = 0.5 * accel * t * t
4 return answer
5
TypeError: can't multiply sequence by non-int of type 'float'
Task: What if you want the distance formula to work for both Earth and the Moon (where g = 1.6 m/s)? That is, what if you don't want 'accel' to be fixed at 9.8?
Math
Comparing values
File "<ipython-input-24-f7e412d8cdaf>", line 1
1=2
SyntaxError: can't assign to literal
Modules
- A file consisting of Python code you can reference (any file ending in .py is treated as a module).
- Allows you to logically organize your Python code to make the code easier to understand and use.
- Can define functions, classes and variables.
- Pre-existing modules can be very useful.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-32-1b1e4f39c953> in <module>()
----> 1 print sqrt(4)
NameError: name 'sqrt' is not defined
Strings
Strings are sequences of characters. They can be made of letters, numbers, and symbols. We've actually already seen strings already:
Backslashes ( \ ) tell python to be ready for special characters, called "escape characters". Some examples are:
A string is really just a group of characters. You don't have to always work with the whole string, you can do things to parts of a string:
Once you've created a string, you can't change just one piece of it.
Task: Print out a googol (1 followed by 100 zeros without literally typing '0' 100 times).
Control flow (loops)
Indentation in Python puts things inside of the loop or acts as the "then" of an "if" statement. Other languages may use curly braces {}.
Task: Repeat the previous example (the pow(3,x) one) but with a For loop instead of a While loop, and without using pow().
Data structures in python
We've already seen examples of tuples in the T Swift examples:
Tuples are immutable, which means they are unchangeable. Once you've defined a tuple, you can't change it. (We saw this is true for strings as well.)
Lists are similar to tuples, but they can be changed:
Task: How would you print out the rows in "newList2" one row at a time?
Making Pictures
Go back to your files. Image file black.png should appear. Open it, then right click on the image to open in a new window. This is an easy way to access it and reload it as you make changes. Try changing the size and default color.
Task: How can you print just the width? Just the height?
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-82-9ae41daf449f> in <module>()
11 for y in range(img.height):
12 dist = math.sqrt( (y-ycenter)**2 + (x-xcenter)**2 )
---> 13 pixels[x,y] = (dist, 0, 0)
14
15 img.save('circle.png')
TypeError: integer argument expected, got float
Task: How can you make a white line 10 pixels wide?
Task: How can you make a diagonal white line?
Project:
Create your own picture, modifying pixels however you like. Be creative and challenge yourself!
If you get stuck or it doesn't work, it can help writing out in words on paper or in a word doc exactly what you want it to do, then translate it to python code.
When you're done, copy the image into an email and send it to [email protected]