x
, my_variable
, or variable_1
=
x = 1
x
1
y = 2
z = x + y
z
3
w
--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-4-b938b801a0bf> in <module>() ----> 1 w NameError: name 'w' is not defined
Variable names in Python can contain alphanumerical characters a-z
, A-Z
, 0-9
and some special characters such
as _
. Normal variable names must start with a letter.
By convention, variable names start with a lower-case letter, and Class names start with a capital letter.
In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:
and, as, assert, break, class,
continue, def, del, elif, else,
except, exec, finally, for, from,
global, if, import, in, is, lambda,
not, or, pass, print, raise,
return, try, while, with, yield
Note: Be aware of the keyword lambda
, which could easily be a natural variable name in a scientific program. But
being a keyword, it cannot be used as a variable name.
Since Python is dynamically typed, it automatically sets the types of your variables upon assignment
x = 1
type(x)
int
y = 2.
type(y)
float
y = 2e0
print(y, type(y))
2.0 <class 'float'>
3.17e1
31.7
a = True
b = False
type(a)
bool
z = '3'
type(z)
str
a = 1
type(a)
int
b = 2.
type(b) is int
False
x = 1
print(type(x))
<class 'int'>
y = 2.
print(type(y))
<class 'float'>
print(type(int(y)))
<class 'int'>
print(type(x+y))
<class 'float'>
z = '3'
w = x + z
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-17-b0119eed5a5f> in <module>() 1 z = '3' ----> 2 w = x + z TypeError: unsupported operand type(s) for +: 'int' and 'str'
w = x + int(z)
print(w, type(w))
4 <class 'int'>
print(bool(0))
print(bool(1))
False True
print(bool(0.))
print(bool(1.))
False True
print(bool('0'))
print(bool('1'))
True True
print(bool('True'))
print(bool('False'))
True True
Operators are defined as "constructs which can manipulate the values of operands"...
Arithmetic operators:
+
-
*
/
//
(integer division)**
(power)%
(modulus)1 + 1
2
1. + 1.
2.0
1 + 1.
2.0
5 - 2
3
5. - 2.
3.0
5 - 3 + 1
3
5 - (3 + 1)
1
2 * 4
8
2. * 4
8.0
3 / 4
0.75
3. / 4.
0.75
3 // 4
0
5 // 4
1
5. // 4.
1.0
10 - 2 * 3
4
10 - (2 * 3)
4
(10 - 2) * 3
24
((2 + 3) - 1) * 2
8
0 / 1
0.0
1 / 0
--------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-42-b710d87c980c> in <module>() ----> 1 1 / 0 ZeroDivisionError: division by zero
2**3
8
2.**3
8.0
2. ** 3
8.0
2. * * 3
File "<ipython-input-46-522aca73570c>", line 1 2. * * 3 ^ SyntaxError: invalid syntax
# Note: don't try to use the caret (^) for power in Python!
# For the curious: https://docs.python.org/2/reference/expressions.html#binary-bitwise-operations
2^3
1
5 % 4
1
4 % 4
0
16 % 4
0
17 % 4
1
Comparisons are operators which evaluate properties
of their operands and always return either True
or False
Common comparisons:
<
>
==
>=
<=
!=
1 < 2
True
a = 1 < 2
print(a, type(a))
True <class 'bool'>
2 == 2
True
2 == 2.
True
2 != 2.
False
2 != 1
True
3 <= 4
True
3 <= 3
True
3 <= 2.9
False
1 < 2 < 3
True
2 <= 2 < 3
True
2 <= (2 < 3)
False
is
and is not
check whether two things point to the same object, not just equality
1 is 1
True
1 is 1.
False
x = 1
y = 1
x is y
True
x = 1.
y = 1
x is y
False
x = 1.
y = 1.
x is y
False
x = 1.
y = 1.
x == y
True
x = 1.
y = x
x is y
True
and
: x and y
first evaluates x
x
is false, its value is returnedy
is evaluated and the resulting value is returnedor
: x or y
first evaluates x
x
is true, its value is returnedy
is evaluated and the resulting value is returnednot
: yields True
if its argument is false, False
otherwiseand
¶True and False
False
True and True
True
1 and True
True
1 and False
False
True and 0
0
bool(True and 0)
False
or
¶True or False
True
False or True
True
1 or False
1
not
¶True is not False
True
not True
False
not 2
False
not 0
True
1 is not 2
True
x = 1
y = 1.
x is not y
True
1 < 2 < 3
True
(1 < 2) and (2 < 3)
True
(1 < 2) and (1 > 2)
False
0 is not 1 and 2 is not 3
True
0 is 1 or 2 is 2
True
(0 is 1) or (2 is 2)
True
s = 'hello world'
type(s)
str
len(s)
11
s[1]
'e'
s[0]
'h'
s[len(s)-1]
'd'
s[-1]
'd'
s.replace('hello', 'goodbye')
'goodbye world'
s.replace('l', 'L')
'heLLo worLd'
You can pull out different chunks of the string using [start:end:step]
start
defaults to 0end
defaults to len(string)-1
(i.e. the last character)step
defaults to 1s[0:5]
'hello'
s[:5]
'hello'
s[6:]
'world'
s[:]
'hello world'
s[::1]
'hello world'
s[::2]
'hlowrd'
'hel' + 'lo'
'hello'
s[:5] + s[6:]
'helloworld'
'he' + 11 + 0
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-108-9053e2a1686c> in <module>() ----> 1 'he' + 11 + 0 TypeError: Can't convert 'int' object to str implicitly
'he' + str(11) + str(0)
'he110'
print('hello', 'world')
hello world
'{} {}'.format('hello', 'world')
'hello world'
'{1} {0}'.format('hello', 'world')
'world hello'
x = 'everybody'
'{} {}'.format('hello', x)
'hello everybody'
from math import pi
'pi is {:.3f}'.format(pi)
'pi is 3.142'
'π is {:.3f}'.format(pi)
'π is 3.142'
number = 1.0
superlative = 'loneliest'
'{num:g} is the {adj} number'.format(adj=superlative, num=number)
'1 is the loneliest number'
a = [1,2,3]
a
[1, 2, 3]
type(a)
list
['hello', 'world']
['hello', 'world']
[1, 'love']
[1, 'love']
a = [1, 'two', 3.]
print(a[0])
print(a[1])
print(a[2])
1 two 3.0
len(a)
3
a[3]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-124-94e7916e7615> in <module>() ----> 1 a[3] IndexError: list index out of range
a[-1]
3.0
type(a[-1])
float
a = [[1,2,3], [4,5]]
a
[[1, 2, 3], [4, 5]]
a[0]
[1, 2, 3]
a[1]
[4, 5]
a[0][1]
2
a[1][:]
[4, 5]
start = 5
stop = 15
step = 2
range(start, stop, step)
range(5, 15, 2)
list(range(start, stop, step))
[5, 7, 9, 11, 13]
a = list('hello world')
a
['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
a[0] = 'H'
a
['H', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
a[6] = 'W'
a
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
a.append('!')
a
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!']
a.insert(5, ',')
a
['H', 'e', 'l', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
a.remove('l')
a
['H', 'e', 'l', 'o', ',', ' ', 'W', 'o', 'r', 'l', 'd', '!']
''.join(a)
'Helo, World!'
'\n'.join(a)
'H\ne\nl\no\n,\n \nW\no\nr\nl\nd\n!'
print('\n'.join(a))
H e l o , W o r l d !
b = []
b.append(1)
b.append(2)
b
[1, 2]
b.reverse()
b
[2, 1]
b.sort()
b
[1, 2]
c = [1,2,3,4,5]
2 in c
True
7 in c
False
c.index(3)
2
c.index(10)
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-150-eaf98f12e547> in <module>() ----> 1 c.index(10) ValueError: 10 is not in list
print(c)
c.remove(2)
print(c)
[1, 2, 3, 4, 5] [1, 3, 4, 5]
print(c)
popped = c.pop(c.index(5))
print(c, popped)
[1, 3, 4, 5] [1, 3, 4] 5
Tuples are like lists but immutable, meaning they cannot be changed
d = (1,2)
d
(1, 2)
d[0]
1
d[0] = 5
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-155-731803ff65f5> in <module>() ----> 1 d[0] = 5 TypeError: 'tuple' object does not support item assignment
e = tuple([1,2,3])
e
(1, 2, 3)
{key1 : value1, ...}
{'a': 1, 'b': 2}
{'a': 1, 'b': 2}
{1: 'hello', 'two': 'world'}
{1: 'hello', 'two': 'world'}
d = {'a': 1, 'b': 2, 'c': 3}
d
{'a': 1, 'b': 2, 'c': 3}
d['d'] = 4
d
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
d['c']
3
x = 'c'
d[x]
3
param = {'mass': 5.0, 'acceleration': 3.2}
param['force'] = param['mass'] * param['acceleration']
param
{'acceleration': 3.2, 'force': 16.0, 'mass': 5.0}
if
, elif
(else if), and else
if condition:
and are then indented belowif True:
print('hi')
hi
if False:
print('bye')
if True:
print('hi')
else:
print('bye')
hi
x = 0
if x < 1:
print('{} is less than 1'.format(x))
elif x > 1:
print('{} is greater than 1'.format(x))
else:
print('I guess {} *is* 1?'.format(x))
0 is less than 1
x = 1
if x < 1:
print('{} is less than 1'.format(x))
elif x > 1:
print('{} is greater than 1'.format(x))
else:
print('I guess {} *is* 1?'.format(x))
I guess 1 *is* 1?
x = 2
if x < 1:
print('{} is less than 1'.format(x))
elif x > 1:
print('{} is greater than 1'.format(x))
else:
print('I guess {} *is* 1?'.format(x))
2 is greater than 1
a = 1
if a == 1:
a = 2
elif a == 2:
a = 3
else:
a = 4
a
2
a = 2
if a == 1:
a = 2
elif a == 2:
a = 3
else:
a = 4
a
3
a = 7
if a == 1:
a = 2
elif a == 2:
a = 3
else:
a = 4
a
4
for
loops¶for x in [1,2,3]:
print(x)
1 2 3
for x in range(3):
print(x)
0 1 2
for x in ['hello', 'world']:
print(x)
hello world
for x in 'hello world':
print(x)
h e l l o w o r l d
for x in range(11):
sq = x**2
print('{x} squared is {sq}!'.format(x=x, sq=sq))
0 squared is 0! 1 squared is 1! 2 squared is 4! 3 squared is 9! 4 squared is 16! 5 squared is 25! 6 squared is 36! 7 squared is 49! 8 squared is 64! 9 squared is 81! 10 squared is 100!
from math import sqrt
for x in range(101):
rt = sqrt(x)
if rt == round(rt):
print('{x} is {rt:g} squared!'.format(x=x, rt=rt))
0 is 0 squared! 1 is 1 squared! 4 is 2 squared! 9 is 3 squared! 16 is 4 squared! 25 is 5 squared! 36 is 6 squared! 49 is 7 squared! 64 is 8 squared! 81 is 9 squared! 100 is 10 squared!
while
loops¶while
loops keep executing until they evalute to False
Ctl+C
(or Ctl+D
) if you do...x = 0
while x < 5:
print(x)
x = x + 1
0 1 2 3 4
y = 0
while y < 5:
print(y)
y += 1
0 1 2 3 4
z = 5
while z:
print(z)
z -= 1
5 4 3 2 1
[x for x in range(11)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[x**2 for x in range(11)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
['{num} squared is {sq}'.format(num=x, sq=x**2) for x in range(11)]
['0 squared is 0', '1 squared is 1', '2 squared is 4', '3 squared is 9', '4 squared is 16', '5 squared is 25', '6 squared is 36', '7 squared is 49', '8 squared is 64', '9 squared is 81', '10 squared is 100']
squares = {x: x**2 for x in range(11)}
print(squares)
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81, 10: 100}
squares[5]
25
for key, value in squares.items():
print('{k} is the square root of {v}'.format(k=key, v=value))
0 is the square root of 0 1 is the square root of 1 2 is the square root of 4 3 is the square root of 9 4 is the square root of 16 5 is the square root of 25 6 is the square root of 36 7 is the square root of 49 8 is the square root of 64 9 is the square root of 81 10 is the square root of 100
To use a module in a Python program it first has to be imported. A module can be imported using the import
statement. For example, to import the module math
, which contains many standard mathematical functions, we can do:
import math
$ \cos(2 \pi) = 1 $
math.cos(2. * math.pi)
1.0
$ \cos(\frac{\pi}{2}) = 0 $
math.cos(math.pi / 2.)
6.123233995736766e-17
# https://docs.python.org/2/tutorial/floatingpoint.html
round(math.cos(math.pi / 2.), 10)
0.0
Importing from modules
from math import cos, pi
cos(2. * pi)
1.0
import *
from math import *
sin(2. * pi)
-2.4492935982947064e-16
dir(math)[10:20]
['atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf']
math.
File "<ipython-input-195-186ff497df9b>", line 1 math. ^ SyntaxError: invalid syntax
help(math.log)
Help on built-in function log in module math: log(...) log(x[, base]) Return the logarithm of x to the given base. If the base not specified, returns the natural logarithm (base e) of x.
math.log(math.e)
1.0
math.log(10., 10.)
1.0
print(3.**2)
print(math.pow(3,2))
9.0 9.0
print(math.e**3.)
print(math.exp(3.))
20.085536923187664 20.085536923187668
Functions are reusable and flexible bits of Python code
Functions are scoped - they have access to global variables, but variables created inside of them are local to the function and invisible outside of it
def func_name(x):
return x**2
def print_hello():
print('hello')
print_hello()
hello
def print_hello(name):
''' Prints "hello, {name}".'''
print('hello, {}'.format(name))
print_hello('world')
hello, world
print_hello()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-204-1d7abd17f6fd> in <module>() ----> 1 print_hello() TypeError: print_hello() missing 1 required positional argument: 'name'
def print_hello(name='buddy'):
print('hello, {}'.format(name))
print_hello('world')
hello, world
print_hello()
hello, buddy
def sq_print(x):
''' Prints the square of x (x^2) '''
print(x**2)
sq_print(3)
9
three_sq = sq_print(3)
9
print(three_sq)
None
type(three_sq)
NoneType
sq_print(3) * 5
9
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-213-6d191d07124a> in <module>() ----> 1 sq_print(3) * 5 TypeError: unsupported operand type(s) for *: 'NoneType' and 'int'
def sq(x):
''' Returns the square of x (x^2)'''
return x**2
sq(3)
9
three_sq = sq(3)
print(three_sq)
9
type(three_sq)
int
sq(3) * 5
45
def sq_with_print(x):
''' Returns the square of x (x^2) and prints it '''
s = x**2
print('{x} squared is {s}'.format(x=x, s=s))
return s
sq_with_print(5)
5 squared is 25
25
s = sq_with_print(5)
print(s)
print(type(s))
5 squared is 25 25 <class 'int'>
def rectangle(w, h):
''' Given a width `w` and height `h`, returns the area and perimeter of the corresponding rectangle '''
area = w * h
perim = 2 * (w + h)
return area, perim
rectangle(5, 10)
(50, 30)
my_rect = rectangle(5, 10)
print(type(my_rect))
print(my_rect[0])
<class 'tuple'> 50
area, perim = rectangle(5, 10)
print(type(area))
print(area)
<class 'int'> 50
def rectangle(w, h):
''' Given a width `w` and height `h`, returns the area and perimeter of the corresponding rectangle in a dict '''
area = w * h
perim = 2 * (w + h)
return {'area': area, 'perim': perim}
rectangle(7, 8)
{'area': 56, 'perim': 30}
my_rect = rectangle(7, 8)
print(my_rect['area'])
56
def rectangle(w, h):
''' Given a width w and height h, returns some info about the corresponding rectangle '''
area = w * h
perim = 2 * (w + h)
return {'w': w,
'h': h,
'area': area,
'perim': perim}
rectangle(3, 4)
{'area': 12, 'h': 4, 'perim': 14, 'w': 3}
from math import pow
pow?
def my_pow(x, y=2):
''' Return x to the power of y, where y defaults to 2 '''
return x**y
my_pow(3, 2)
9
my_pow(3)
9
my_pow(x=3, y=2)
9
my_pow(y=2, x=3)
9
a = 1
def make_a_two():
''' Try to change the value of a to 2 '''
a = 2
print(a)
1
make_a_two()
print(a)
1
def make_a_two():
''' Try to change the value of a to 2 '''
a = 2
print('The value of a is {}'.format(a))
make_a_two()
The value of a is 2
print(a)
1
global_a = 5
def print_global_a():
''' Print out the value of global_a '''
print('global_a contains {}'.format(global_a))
print_global_a()
global_a contains 5
def print_global_a():
''' Print out the value of global_a '''
global_a = 7
print('global_a contains {}'.format(global_a))
print_global_a()
global_a contains 7
print(global_a)
5