print("Hello world!")
Hello world!
# <--- This is a comment. This line is ignored by Python
a = 1
b = 2
print(a+b , a-b , a*b , a/b, a//b) # Addition, subtraction, multiplication, real division, floor division
# Note: in Python 3, 1/2 = 0.5. In older versions (Python 2), 1/2 = 0 (Integer division)
b += 1 # increase value of b
print(b)
a = b**2 # a is now equal to 9 (b*b). Note that I can freely redefine a even if it was already defined
print(a%2 , a%3) # Remainder of integer vision
3 -1 2 0.5 0 3 1 0
a_int = 5 # Integer
a_float = 5.0 # Float
a_str = "5.0" # String of characters
a_bool = True # Can also be False
# Type conversion
print(a_str, float(a_str)) # Convert string to float
print(a_int, bool(a_int))# 5 is non-zero and therefore evaluates to True
print(a_int, str(a_int)) # Convert integer to string
print(a_str, int(float(a_str))) # Convert string to float then integer
5.0 5.0 5 True 5 5 5.0 5
for i in range(5):
print("Loop stage:", i) # Note the indentation used to define blocks (inside the loop: indented.)
i += 1 # variable i still exists after the loop
print(i)
while i < 10:
i += 1
print(i)
Loop stage: 0 Loop stage: 1 Loop stage: 2 Loop stage: 3 Loop stage: 4 5 10
# In a Jupyter Notebook, variables from previous cells still exist
if i < 10 :
print("i lower than 10")
elif i > 10:
print("i greater than 10")
else:
print("i exactly 10 : ", i==10) # a single = means assigning a value. A double == means testing equality
# greater or equal: >= ; lower or equal: <=
i exactly 10 : True
def someTestFunction(x,y):
return x*y
print(someTestFunction(4,5))
print(someTestFunction(94,107))
20 10058
a = [1,2,3,4,5]
b = [8.0,'foo',True,2,"bar"] # A list can hold several types. Strings can be delimited by either ' or "
print("Iterating on list a:")
for x in a:
print(x)
print("Iterating on both lists:")
if len(a) == len(b):
for i in range(len(a)):
print(a[i],b[i])
b.append(42) # Lists are dynamic, can always add stuff
b.append(a) # Lists can contain other lists
print("Enumerating modified list b:")
for i,x in enumerate(b):
print(i,x)
Iterating on list a: 1 2 3 4 5 Iterating on both lists: 1 8.0 2 foo 3 True 4 2 5 bar Enumerating modified list b: 0 8.0 1 foo 2 True 3 2 4 bar 5 42 6 [1, 2, 3, 4, 5]
c = b.pop() # Remove last element of the list
print(c == a) # ... which happens to be list a
print(b) # Can print a list directly - see that its last element is gone now
print("---")
# We can access individual elements of the list:
print(b[0],b[1]) # First two
print(b[-1],b[-2])# Last two
# and we can slice the list:
print(b[2:]) # All elements from number 2 to the last
True [8.0, 'foo', True, 2, 'bar', 42] --- 8.0 foo 42 bar [True, 2, 'bar', 42]
# Strings are lists too!
hw = "Hello World!"
for x in hw: print(x)
print(hw.split(' ')[1]) # Separate into two substring using whitespace as delimiter, then print the second part
print(hw.replace('World','All')) # String substitution
print(hw + 'How are you?') # String concatenation
H e l l o W o r l d ! World! Hello All! Hello World!How are you?
a = {'foo':58,'bar':42,8:5} # Unordered list where each object is assigned a name, a "key"
# Keys can be string, integer, ...
print(a['foo'])
print(a[8]) # Access the element named "8"
for x in a.keys(): print(x) # Iterate on the list of keys
if 'foo' in a.keys() and 'bar' in a.keys():
print("Good keys. Sum:",a['foo'] + a['bar'])
58 5 foo bar 8 Good keys. Sum: 100
# Classic syntax
myfile = open('demo.txt','w') # 'w' : open in 'write' mode
myfile.write('foo')
myfile.close()
# New/recommended python syntax
with open('demo.txt','w') as myfile: # I open the same file: it is erased
myfile.write('foo') # Indented block. The file is closed automatically at the end of the block
# Write a list to a file, line by line
a = ['a','b','c','d']
with open('demo.txt','w') as myfile:
for item in a :
myfile.write(item + '\n') # '\n' : linebreak
# Read that file, line by line
with open('demo.txt','r') as myfile: # 'r' : open in 'read' mode
b = []
for line in myfile:
b.append( line.rstrip('\n')) # Remove the '\n' linebreak character
print(b == a) # Should be True
True
import time # Use the library relative to time
currentTime = time.time() # Get current epoch in seconds
time.sleep(5) # Sleep for 5 seconds
elapsedTime = time.time() - currentTime
print("Slept for {} seconds".format(elapsedTime)) # Note the way I insert a variable into a string
from math import pi # I only want pi from that library and nothing else, so I don't need to write "math.pi"
print(pi)
from math import log as ln # I can rename a library or function when importing it
print(ln(2.7))
Slept for 5.000266790390015 seconds 3.141592653589793 0.9932517730102834
I keep using those over and over again
math
: mathematical objects and functionsos
: communicate with the file system (check file existence, etc)sys
: communicate with the system. In particular, sys.argv
to get command-line argumentsargparse
: parser for command-line argumentsglob
: function glob.glob()
to list files in a directory as a Python listpickle
: save a Python object as a binary file or load it.copy
: when you need to make sure that you get a copy instead of a pointer (typically for lists, arrays, etc)time
: self-explanatorynumpy
: advanced math tools and functions, in particular fast management of arrays, vectors, etc. Very powerfulscipy
: numpy's sister library dedicated to statisticsmatplotlib
: plotting library inspired from MatlabAnd specifically for machine learning: scikit-learn
, keras
, tensorflow
, pytorch
%matplotlib inline
# The above line is for Jupyter Notebooks only
import matplotlib.pyplot as plt # Import plotting library - I write this line so much I have muscle memory for it
plt.plot([1,2,3],[1,4,9])
[<matplotlib.lines.Line2D at 0x1d08626e470>]
fig1 = plt.figure()
x = range(-10,20,2)
y_quadratic = [a**2 for a in x] # Create a list in a single line
y_cubic = [a**3 for a in x]
plt.plot(x,y_quadratic,'--',label='quad',color='blue')
plt.plot(x,y_cubic,'o-',label='cube',color='red')
plt.xlabel('Horizontal Axis')
plt.ylabel('Vertical Axis')
plt.title("Full demo")
plt.legend(loc='best') # Can also specify 'upper left', 'lower right', etc
plt.xlim((-15,25)) # Limits on the x-axis
#plt.yscale('log') # In case you want a logarithmic plot
plt.text(0,3000,'Some text',fontsize='12',rotation=30,color='green')
<matplotlib.text.Text at 0x1d086369a58>
a = [1,2,3,4]
b = a # Is this a copy? Or a pointer?
b.append(5) # If it was a copy, then a and b should be different now
print(a,b) # Modifying b also modifies a.
print(a is b) # They are still the same.
print('---')
# Here is a workaround
c = [x for x in a] # I specify that the list should have the same content, instead of being the same
c.append(6)
print(a,c) # Here I changed c but I didn't change a.
# Be careful however: if 'a' contains a list, then you can run in the same problem
# You can use the Python library 'copy' (with a 'deep copy') to make 100% sure you won't have that issue
[1, 2, 3, 4, 5] [1, 2, 3, 4, 5] True --- [1, 2, 3, 4, 5] [1, 2, 3, 4, 5, 6]
import this
The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!