Python is an easy-to-learn and easy-to-use programming language. Most deep learning frameworks have python interfaces, which allow you to design and develop your own neural networks rapidly.
Readability is the most important thing to keep in mind when writing python code. But efficiency should never be ignored. Don't let your python code become the bottleneck when training neural networks.
In this notebook, we will go over some python basics, including numbers, strings, lists, dictionaries, functions, and classes.
Please refer to the official tutorial for more detailed and advanced instructions. It's a must if you want to be pythonic :).
# Numbers
a = 5
b = 3
print (a + b) * (a - b)
print a**2 - b**2 # to the power of 2
print a // b, a % b # integer division
print a * 1.0 / b # float division
c = a * 1.0 / b
print int(c), int(round(c))
print 123**456 # unlimited integer range!
16 16 1 2 1.66666666667 1 2 99250068772098856700831462057469632637295940819886900519816298881382867104749399077921128661426144638055424236936271872492800352741649902118143819672601569998100120790496759517636465445895625741609866209900500198407153244604778968016963028050310261417615914468729918240685487878617645976939063464357986165711730976399478507649228686341466967167910126653342134942744851463899927487092486610977146112763567101672645953132196481439339873017088140414661271198500333255713096142335151414630651683065518784081203678487703002802082091236603519026256880624499681781387227574035484831271515683123742149095569260463609655977700938844580611931246495166208695540313698140011638027322566252689780838136351828795314272162111222231170901715612355701347552371530013693855379834865667060014643302459100429783653966913783002290784283455628283355470529932956051484477129333881159930212758687602795088579230431661696010232187390436601614145603241902386663442520160735566561
# Strings
a = 'eleg' # single quotes
b = "5491" # double quotes also fine
c = a + b # concatenate two strings
print c
print len(c) # length of a string
a = 5.0
b = 3
print '{} / {} = {:.2f}'.format(a, b, a/b) # :.2f denotes two decimal points of floating number
eleg5491 8 5.0 / 3 = 1.67
# Some string functions, courtesy of cs231n
s = "hello"
print s.capitalize() # Capitalize a string; prints "Hello"
print s.upper() # Convert a string to uppercase; prints "HELLO"
print s.rjust(7) # Right-justify a string, padding with spaces; prints " hello"
print s.center(7) # Center a string, padding with spaces; prints " hello "
print s.replace('l', '(ell)') # Replace all instances of one substring with another;
# prints "he(ell)(ell)o"
print ' world '.strip() # Strip leading and trailing whitespace; prints "world"
Hello HELLO hello hello he(ell)(ell)o world
# Lists
a = [5, 3, 4, 1, 2]
print a, len(a)
a.sort(reverse=True) # sort from largest to smallest
print a
# indexing and slicing
print a[0] # index from 0
print a[-1] # -1 means the last one, i.e., a[len(a)-1]
print a[0:2] # interval [0, 2), i.e., [a[0], a[1]]
print a[-2:] # interval [len(a)-2, len(a))
a[1:3] = [-2, -3]
print a
# loops
a = [1, 2, 'abc', [3,4]] # all types of data can be in a list
# C-style loop, not recommended
for i in xrange(len(a)):
print a[i], # a comma at the end means space but not newline
print '' # print a new line
# pythonic way, recommended
for x in a:
print x,
print ''
# when you want both the index and the value
for i, x in enumerate(a):
print 'a[{}] = {}'.format(i, x)
# add / delete / extend / prepend
a = [1,2]
a.append(3) # a equals to [1,2,3]
print a
del a[1] # a equals to [1,3]
print a
a.extend([3,4,5]) # a equals to [1,3,3,4,5]
print a
a = [0] + a # a equals to [0,1,3,3,4,5]
print a
# list comprehension
a = [0, 1, 2, 3, 4]
b = [x**2 for x in a]
print b
b = [x**2 for x in a if x < 3]
print b
[5, 3, 4, 1, 2] 5 [5, 4, 3, 2, 1] 5 1 [5, 4] [2, 1] [5, -2, -3, 2, 1] 1 2 abc [3, 4] 1 2 abc [3, 4] a[0] = 1 a[1] = 2 a[2] = abc a[3] = [3, 4] [1, 2, 3] [1, 3] [1, 3, 3, 4, 5] [0, 1, 3, 3, 4, 5] [0, 1, 4, 9, 16] [0, 1, 4]
# Dictionaries
# create a new dict of <key, value> pairs
name_to_age = {
'alice': 10,
'bob': 12,
'eve': 20
}
print name_to_age
# modify and access a <key, value> pair
name_to_age['alice'] = 11
print name_to_age['alice']
# use get to access with default value
print name_to_age.get('alice', -1)
print name_to_age.get('trump', -1)
# remove a <key, value> pair
del name_to_age['eve']
# loops with key
for name in name_to_age:
print '{} : {}'.format(name, name_to_age[name])
# loops with key and value
for name, age in name_to_age.iteritems():
print '{} : {}'.format(name, age)
{'bob': 12, 'alice': 10, 'eve': 20} 11 11 -1 bob : 12 alice : 11 bob : 12 alice : 11
# Functions, courtesy of cs231n
def sign(x):
if x > 0:
return 'positive'
elif x < 0:
return 'negative'
else:
return 'zero'
for x in [-1, 0, 1]:
print sign(x)
def hello(name, loud=False):
if loud:
print 'HELLO, %s!' % name.upper()
else:
print 'Hello, %s' % name
hello('Bob') # Prints "Hello, Bob"
hello('Fred', loud=True) # Prints "HELLO, FRED!"
negative zero positive Hello, Bob HELLO, FRED!
# Classes, courtesy of cs231n
class Greeter(object):
# Constructor
def __init__(self, name):
self.name = name # Create an instance variable
# Instance method
def greet(self, loud=False):
if loud:
print 'HELLO, %s!' % self.name.upper()
else:
print 'Hello, %s' % self.name
g = Greeter('Fred') # Construct an instance of the Greeter class
g.greet() # Call an instance method; prints "Hello, Fred"
g.greet(loud=True) # Call an instance method; prints "HELLO, FRED!"
Hello, Fred HELLO, FRED!