Skip to content

Instantly share code, notes, and snippets.

@Cysu
Created January 20, 2017 02:06
Show Gist options
  • Save Cysu/b45242c1e22311118d01dba4d8bf2c3a to your computer and use it in GitHub Desktop.
Save Cysu/b45242c1e22311118d01dba4d8bf2c3a to your computer and use it in GitHub Desktop.
[ELEG5491] Python Tutorial
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Python Basics\n",
"\n",
"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.\n",
"\n",
"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.\n",
"\n",
"In this notebook, we will go over some python basics, including numbers, strings, lists, dictionaries, functions, and classes.\n",
"\n",
"Please refer to the official [tutorial](https://docs.python.org/2/tutorial/index.html) for more detailed and advanced instructions. It's a must if you want to be **pythonic** :)."
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"16\n",
"16\n",
"1 2\n",
"1.66666666667\n",
"1 2\n",
"99250068772098856700831462057469632637295940819886900519816298881382867104749399077921128661426144638055424236936271872492800352741649902118143819672601569998100120790496759517636465445895625741609866209900500198407153244604778968016963028050310261417615914468729918240685487878617645976939063464357986165711730976399478507649228686341466967167910126653342134942744851463899927487092486610977146112763567101672645953132196481439339873017088140414661271198500333255713096142335151414630651683065518784081203678487703002802082091236603519026256880624499681781387227574035484831271515683123742149095569260463609655977700938844580611931246495166208695540313698140011638027322566252689780838136351828795314272162111222231170901715612355701347552371530013693855379834865667060014643302459100429783653966913783002290784283455628283355470529932956051484477129333881159930212758687602795088579230431661696010232187390436601614145603241902386663442520160735566561\n"
]
}
],
"source": [
"# Numbers\n",
"a = 5\n",
"b = 3\n",
"print (a + b) * (a - b)\n",
"print a**2 - b**2 # to the power of 2\n",
"print a // b, a % b # integer division\n",
"print a * 1.0 / b # float division\n",
"c = a * 1.0 / b\n",
"print int(c), int(round(c))\n",
"print 123**456 # unlimited integer range!"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"eleg5491\n",
"8\n",
"5.0 / 3 = 1.67\n"
]
}
],
"source": [
"# Strings\n",
"a = 'eleg' # single quotes\n",
"b = \"5491\" # double quotes also fine\n",
"c = a + b # concatenate two strings\n",
"print c\n",
"print len(c) # length of a string\n",
"\n",
"a = 5.0\n",
"b = 3\n",
"print '{} / {} = {:.2f}'.format(a, b, a/b) # :.2f denotes two decimal points of floating number"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello\n",
"HELLO\n",
" hello\n",
" hello \n",
"he(ell)(ell)o\n",
"world\n"
]
}
],
"source": [
"# Some string functions, courtesy of cs231n\n",
"s = \"hello\"\n",
"print s.capitalize() # Capitalize a string; prints \"Hello\"\n",
"print s.upper() # Convert a string to uppercase; prints \"HELLO\"\n",
"print s.rjust(7) # Right-justify a string, padding with spaces; prints \" hello\"\n",
"print s.center(7) # Center a string, padding with spaces; prints \" hello \"\n",
"print s.replace('l', '(ell)') # Replace all instances of one substring with another;\n",
" # prints \"he(ell)(ell)o\"\n",
"print ' world '.strip() # Strip leading and trailing whitespace; prints \"world\""
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[5, 3, 4, 1, 2] 5\n",
"[5, 4, 3, 2, 1]\n",
"5\n",
"1\n",
"[5, 4]\n",
"[2, 1]\n",
"[5, -2, -3, 2, 1]\n",
"1 2 abc [3, 4] \n",
"1 2 abc [3, 4] \n",
"a[0] = 1\n",
"a[1] = 2\n",
"a[2] = abc\n",
"a[3] = [3, 4]\n",
"[1, 2, 3]\n",
"[1, 3]\n",
"[1, 3, 3, 4, 5]\n",
"[0, 1, 3, 3, 4, 5]\n",
"[0, 1, 4, 9, 16]\n",
"[0, 1, 4]\n"
]
}
],
"source": [
"# Lists\n",
"a = [5, 3, 4, 1, 2]\n",
"print a, len(a)\n",
"a.sort(reverse=True) # sort from largest to smallest\n",
"print a\n",
"\n",
"# indexing and slicing\n",
"print a[0] # index from 0\n",
"print a[-1] # -1 means the last one, i.e., a[len(a)-1]\n",
"print a[0:2] # interval [0, 2), i.e., [a[0], a[1]]\n",
"print a[-2:] # interval [len(a)-2, len(a))\n",
"a[1:3] = [-2, -3]\n",
"print a\n",
"\n",
"\n",
"# loops\n",
"a = [1, 2, 'abc', [3,4]] # all types of data can be in a list\n",
"\n",
"# C-style loop, not recommended\n",
"for i in xrange(len(a)):\n",
" print a[i], # a comma at the end means space but not newline\n",
"print '' # print a new line\n",
"\n",
"# pythonic way, recommended\n",
"for x in a:\n",
" print x,\n",
"print ''\n",
"\n",
"# when you want both the index and the value\n",
"for i, x in enumerate(a):\n",
" print 'a[{}] = {}'.format(i, x)\n",
"\n",
"\n",
"# add / delete / extend / prepend\n",
"a = [1,2]\n",
"a.append(3) # a equals to [1,2,3]\n",
"print a\n",
"del a[1] # a equals to [1,3]\n",
"print a\n",
"a.extend([3,4,5]) # a equals to [1,3,3,4,5]\n",
"print a\n",
"a = [0] + a # a equals to [0,1,3,3,4,5]\n",
"print a\n",
"\n",
"\n",
"# list comprehension\n",
"a = [0, 1, 2, 3, 4]\n",
"b = [x**2 for x in a]\n",
"print b\n",
"b = [x**2 for x in a if x < 3]\n",
"print b"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'bob': 12, 'alice': 10, 'eve': 20}\n",
"11\n",
"11\n",
"-1\n",
"bob : 12\n",
"alice : 11\n",
"bob : 12\n",
"alice : 11\n"
]
}
],
"source": [
"# Dictionaries\n",
"\n",
"# create a new dict of <key, value> pairs\n",
"name_to_age = {\n",
" 'alice': 10,\n",
" 'bob': 12,\n",
" 'eve': 20\n",
"}\n",
"print name_to_age\n",
"\n",
"# modify and access a <key, value> pair\n",
"name_to_age['alice'] = 11\n",
"print name_to_age['alice']\n",
"\n",
"# use get to access with default value\n",
"print name_to_age.get('alice', -1)\n",
"print name_to_age.get('trump', -1)\n",
"\n",
"# remove a <key, value> pair\n",
"del name_to_age['eve']\n",
"\n",
"# loops with key\n",
"for name in name_to_age:\n",
" print '{} : {}'.format(name, name_to_age[name])\n",
" \n",
"# loops with key and value\n",
"for name, age in name_to_age.iteritems():\n",
" print '{} : {}'.format(name, age)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"collapsed": false,
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"negative\n",
"zero\n",
"positive\n",
"Hello, Bob\n",
"HELLO, FRED!\n"
]
}
],
"source": [
"# Functions, courtesy of cs231n\n",
"def sign(x):\n",
" if x > 0:\n",
" return 'positive'\n",
" elif x < 0:\n",
" return 'negative'\n",
" else:\n",
" return 'zero'\n",
"\n",
"for x in [-1, 0, 1]:\n",
" print sign(x)\n",
"\n",
"\n",
"\n",
"\n",
"def hello(name, loud=False):\n",
" if loud:\n",
" print 'HELLO, %s!' % name.upper()\n",
" else:\n",
" print 'Hello, %s' % name\n",
"\n",
"hello('Bob') # Prints \"Hello, Bob\"\n",
"hello('Fred', loud=True) # Prints \"HELLO, FRED!\""
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello, Fred\n",
"HELLO, FRED!\n"
]
}
],
"source": [
"# Classes, courtesy of cs231n\n",
"class Greeter(object):\n",
" \n",
" # Constructor\n",
" def __init__(self, name):\n",
" self.name = name # Create an instance variable\n",
" \n",
" # Instance method\n",
" def greet(self, loud=False):\n",
" if loud:\n",
" print 'HELLO, %s!' % self.name.upper()\n",
" else:\n",
" print 'Hello, %s' % self.name\n",
" \n",
"g = Greeter('Fred') # Construct an instance of the Greeter class\n",
"g.greet() # Call an instance method; prints \"Hello, Fred\"\n",
"g.greet(loud=True) # Call an instance method; prints \"HELLO, FRED!\""
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 2",
"language": "python",
"name": "python2"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 2
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython2",
"version": "2.7.13"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment