%run talktools.py
from IPython.display import YouTubeVideo
YouTubeVideo("imhrDrE4-mI",width="640",height="390")
print("Hello, world.")
there are
int
andfloat
(but not doubles)
print(2 + 2)
2 + 2
print(2.1 + 2)
2.1 + 2 == 4.0999999999999996
%run talktools
Python stores floats as their byte representation so is limited by the same 16-bit precision issues as most other languages
In doing calculations, unless you specify otherwise, Python will store the results in the smallest-byte representation
- Indentation matters!
- When you mess up, Python is gentle
- # starts a comments (until the end of the line)
print(2 + 2)
2 + 2
2 # this is a comment and is not printed
# this is also a comment
** Calculator **
**
for power.int
and long
42**42
(42**42).bit_length()
bin(42**42)
Division always leads to a float
2 / 2
2 / 2.0
Note: This is an important difference between Python 2 and Python 3. Old-style division between int
s can be done with a double slash //
2 // 2
3 // 2
2.5 // 2 # egad, dont do this.
There is also complex
types
complex(1,2)
1+2j
1 + 2j - 2j
(3.0*10.0 - 25.0)/5.0
print(3.085e18*1e6) # this is a Megaparsec in units of cm!
t = 1.0 # declare a variable t (time)
accel = 9.8 # acceleration in units of m/s^2
# distance travelled in time t seconds is 1/2 a*t**2
dist = 0.5*accel*t*t
print(dist) # this is the distance in meters
dist1 = accel*(t**2)/2
print(dist1)
dist2 = 0.5*accel*pow(t,2)
print(dist2)
print(6 / 5) ; print(9 / 5)
print(6 // 5) ; print(9 // 5) # remember double-slash integer division returns the floor
6 % 5 # mod operator, get the remainder. x = (x // y)*y + x % y
1 << 2 ## shift: move the number 1 by two bits to the left
## that is make a new number 100 (base 2)
5 >> 1 ## shift: move the number 5 = 101 (base 2) one to
## to the right (10 = 2)
x = 2 ; y = 3 ## assign two variables on the same line!
x | y ## bitwise OR
x ^ y ## exclusive OR (10 ^ 11 = 01)
x & y ## bitwise AND
x = x ^ y ; print(x)
x += 3 ; print(x)
x /= 2.0 ; print(x)
we'll see a lot more mathy operators and functions later
# from before dist1 = 4.9 and dist = 4.9
dist1 == dist
dist < 10
dist <= 4.9
dist < (10 + 2j)
dist < -2.0
dist != 3.1415
Try using some Greek characters as variables:
\Delta
** More on Variables & Types **
0 == False
not False
0.0 == False
not (10.0 - 10.0)
not -1
not 3.1415
x = None # None is something special. Not true or false
None == False
None == True
False or True
False and True
float("nan") == True
print(float('inf'))
import math
math.isnan(float("NaN"))
** More on Variables & Types **
print(type(1))
x = 2 ; type(x)
# bytes are immutable sequences of numbers from 0-255
print((255).to_bytes(2,byteorder='big')) ; type(bytes(10))
type(2) == type(1)
print(type(True))
print(type(type(1)))
print(type(pow))
we can test whether something is a certain type with isinstance()
isinstance(1,int)
isinstance(1,(int,float))
isinstance("spam",str)
isinstance(1.212,int)
isinstance(1.212,int)
We'll see later than numbers are objects, which have functions (methods
) that can act upon themselves:
(1.212).is_integer()
(1.0).is_integer()
builtin-types: int
, bool
, str
, float
, complex
, bytes
Strings are a sequence of characters
Strings are immutable (unlike in C), so you cannot change a string in place (this isn't so bad...)
Strings can be formatted and compared
x = "spam" ; print(type(x))
print("hello!\n...my sire.")
"hello!\n...my sire."
"wah?!" == 'wah?!'
print("'wah?!' said the student")
print("\"wah?!\" said the student")
backslashes (\) start special (escape) characters:
\n = newline (\r = return)
\t = tab
\a = bell
string literals are defined with double quotes or quotes. The outermost quote type cannot be used inside the string (unless it's escaped with a backslash)
See: http://docs.python.org/reference/lexical_analysis.html#string-literals
print("\a\a\a") # try this in CLI python, not the notebook
# raw strings don't escape characters
print(r'This is a raw string...newlines \r\n are ignored.')
# Triple quotes are real useful for multiple line strings
y = '''For score and seven minutes ago,
you folks all learned some basic mathy stuff with Python
and boy were you blown away!'''
print(y)
prepending r
makes that string "raw"
triple quotes allow you to compose long strings
https://docs.python.org/3.4/reference/lexical_analysis.html#literals
print("\N{RIGHT CURLY BRACKET}")
print("\N{BLACK HEART SUIT}")
s = "spam" ; e = "eggs"
print(s + e)
print("spam"
"eggs"
"Trumpkins")
print(s
"eggs")
print(s + " and " + e)
print(s,"and",e, sep=" ")
print("green " + e + " and\n " + s + "\n\t ... and Trumpkins")
print(s*3 + e)
print(s*3,e,sep="->")
print("*"*50)
print("spam" == "good") ; print("spam" == "spam")
"spam" < "zoo"
"s" < "spam"
+
sign*
signprint('I want' + 3 + ' eggs and no ' + s)
print('I want ' + str(3) + ' eggs and no ' + s)
pi = 3.14159
print('I want ' + str(pi) + ' eggs and no ' + s)
print(str(True) + ":" + ' I want ' + str(pi) + ' eggs and no ' + s)
you must concatenate only strings, coercing ("casting")
other variable types to str
there's a cleaner way to do this, with string formatting. we'll see that tomorrow.
faren = input("Enter the temperature (in Fahrenheit): ")
cent = (5.0/9.0)*(faren - 32.0)
faren = float(faren)
cent = (5.0/9.0)*(faren - 32.0) ; print(cent)
faren = float(input("Enter the temperature (in Fahrenheit): "))
print((5.0/9.0)*(faren - 32.0))
s ="spam"
len(s)
len("eggs\n")
len("")
s[0]
s[-1]
len()
gives us the length of an arrayWe can think of strings as arrays (although, unlike in C you never really need to deal with directly addressing character locations in memory)
useful for slicing: indices are between the characters
s[0:1] # get every character between 0 and 1
s[1:4] # get every character between 1 and 4
s[-2:-1]
## slicing [m:n] will return abs(n-m) characters
s[0:100] # if the index is beyond the len(str), you dont segfault!
s[100]
s[1:] # python runs the index to the end
s[:2] # python runs the index to the beginning
s[::-1] # print it out backwards
s = s[:n] + s[n:] for all n
Python has pretty much all of what you use:
if...elif...else, for, while
As well as:
break, continue (within loops)
Does not have:
case (explicitly), goto
Does have: pass
x = 1
if x > 0:
print("yo")
else:
print("dude")
Note: if you are doing this within the Python interpreter you'll see the ...
>>> x = 1
>>> if x > 0:
... print "yo"
... else:
... print "dude"
...
yo
Note colons & indentations (tabbed or spaced)
x = 1
if x > 0:
print("yo")
else:
print("dude")
Indentations with the same block must be the same but not within different blocks (though this is ugly)
one-liners
print("yo" if x > 0 else "dude")
a small program... Do Control-C to stop (in Python/IPython) or "Kernel->Interrupt" in IPython notebook
x = 1
y = 0
while True:
print("yo" if x > 0 else "dude")
x *= -1
y += 1
if y > 42:
break
case statements can be constructed with just a bunch of if, elif,...else
if x < 1:
print("t")
elif x > 100:
print("yo")
else:
print("dude")
ordering matters. The first block of True
in an if/elif gets executed then everything else does not.
blocks cannot be empty
x = "fried goldfish"
if x == "spam for dinner":
print("I will destroy the universe")
else:
# I'm fine with that. I'll do nothing
pass
is a "do nothing" statement
if x == "spam for dinner":
print("I will destroy the universe")
else:
# I'm fine with that. I'll do nothing
pass
The double percent sign at the top of an IPython/Jupyter cell is a cell-level "magic". It's not Python itself, but defined as part of IPython/Jupyter. We'll see more on this later in the bootcamp.
%%file temp1.py
# set some initial variables. Set the initial temperature low
faren = -1000
# we dont want this going on forever, let's make sure we cannot have too many attempts
max_attempts = 6
attempt = 0
while faren < 100:
# let's get the user to tell us what temperature it is
newfaren = float(input("Enter the temperature (in Fahrenheit): "))
if newfaren > faren:
print("It's getting hotter")
elif newfaren < faren:
print("It's getting cooler")
else:
# nothing has changed, just continue in the loop
continue
faren = newfaren # now set the current temp to the new temp just entered
attempt += 1 # bump up the attempt number
if attempt >= max_attempts:
# we have to bail out
break
if attempt >= max_attempts:
# we bailed out because of too many attempts
print("Too many attempts at raising the temperature.")
else:
# we got here because it's hot
print("it's hot here, people.")
%run temp1
%run temp1
%%file temp2.py
# set some initial variables. Set the initial temperature low
faren = -1000
# we dont want this going on forever, let's make sure we cannot have too many attempts
max_attempts = 6
attempt = 0
while faren < 100 and (attempt < max_attempts):
# let's get the user to tell us what temperature it is
newfaren = float(input("Enter the temperature (in Fahrenheit): "))
if newfaren > faren:
print("It's getting hotter")
elif newfaren < faren:
print("It's getting cooler")
else:
# nothing has changed, just continue in the loop
continue
faren = newfaren # now set the current temp to the new temp just entered
attempt += 1 # bump up the attempt number
if attempt >= max_attempts:
# we bailed out because of too many attempts
print("Too many attempts at raising the temperature.")
else:
# we got here because it's hot
print("it's hot here, people.")
UC Berkeley Python Bootcamp - Basic Training (c) J. Bloom 2008-2016 All Rights Reserved