Nikolay Koldunov
koldunovn@gmail.com
Python uses duck typing
Variable - is a facility for storing data. The current value of the variable is the data actially stored in the variable.
a = 10
a
type(a)
z = 10.
z
aa = 3
bb = 2.
aa/bb
type(z)
calculate $a+b$, where $a=2$, $b = 3$
Legal names consist of any combination of letters and digits, starting with a letter.
These are allowable:
LatLon, Lat2Lon, l5, L2, z25c5
These are not allowable:
Lat-Lon, 2Lat, %x, @sign
Use names that reflect the values they represent.
b = '2'
b
Some operations are not allowed on different types:
a+b
But some of them are allowed:
b*a
Might be a source of confusion :)
String variables can be combined:
c = ' guys walk into a bar'
c
d = "Two"
d+c
In order to include variable of another type in to string you have to convert it:
str(a)+c
In IPython you can get the list of object's methods and attributes by typing dot and pressing TAB:
c.
Methods are basically default functions that can be applied to our variable:
c.upper()
c.title()
c.count('a')
c
c.find('into')
If you need help on method in IPython type something like:
c.find?
Or open bracket and press SHIFT + TAB:
c.find(
c.rsplit()
Pure python does not do much. To do some specific tasks you need to import modules. Here I am going to demonstrate several ways to do so.
The most common one is to import complete library. In this example we import math - a library that contain mathematical functions:
pi
import math
Here we get value of pi. Note how function pi is called. We have to use name of the library, then dot, then name of the function from the library:
math.pi
Another option is to import it like this:
from math import *
In this case all functions will be imported in to the name-space and you can use pi directly, without typing the name of the library first:
pi
But generally it's a bad idea, because your name-space is populated by things that you don't really need and it's hard to tell where the function comes from.
whos
You can import only function that you need:
from math import pi
pi
3.141592653589793
Or import library as alias in order to avoid extensive typing:
import math as mt
mt.pi
3.141592653589793
type(pi)
float
import numpy as np