Difference between revisions of "Python: Basics"

From Ittichai Chammavanijakul's Wiki
Jump to navigation Jump to search
(Created page with "* Comment ** Single-line comment <pre> # Hello World </pre> ** Multiple-line comment <pre> """"Hello World""" </pre> * Functions <pre> .isalpha() # Check if alpha ...")
 
Line 1: Line 1:
 
* Comment
 
* Comment
 
+
** Single-line comment  
** Single-line comment
 
 
 
 
<pre>
 
<pre>
 
 
# Hello World
 
# Hello World
 
 
</pre>
 
</pre>
 
 
** Multiple-line comment
 
** Multiple-line comment
 
 
<pre>
 
<pre>
 
 
""""Hello
 
""""Hello
 
 
World"""
 
World"""
 
 
</pre>
 
</pre>
 
 
* Functions
 
* Functions
 
 
<pre>
 
<pre>
 
+
.isalpha() # Check if alpha characters
.isalpha()   # Check if alpha characters
 
 
 
 
<pre>
 
<pre>
 
 
* Create a function
 
* Create a function
 
 
<pre>
 
<pre>
 
 
def <function_name> ():
 
def <function_name> ():
  
Line 40: Line 24:
  
 
sum(args)  # You add arguments up
 
sum(args)  # You add arguments up
 
 
</pre>
 
</pre>
  
 
* Import defined functions
 
* Import defined functions
 
 
<pre>
 
<pre>
 
 
from <module> import <function>
 
from <module> import <function>
 
 
Sample:
 
Sample:
 +
import math  #  Import all, use math.sqrt
 +
math import sqrt  # Import only sqrt, no need to qualify
 +
from math import * # Just import metadata??
  
import math          #  Import all, use math.sqrt
+
import this # Easter Egg - The Zen of Python
 
 
math import sqrt      # Import only sqrt, no need to qualify
 
 
 
from math import *    # Just import metadata??
 
 
 
import this         # Easter Egg - The Zen of Python
 
 
 
 
</pre>
 
</pre>
 
 
* If-then-else on one line
 
* If-then-else on one line
 
 
<pre>
 
<pre>
 
 
Boolean = True if (1 == 2) else False
 
Boolean = True if (1 == 2) else False
  
 
if    :
 
if    :
 
 
elif  :
 
elif  :
 
 
else:
 
else:
 
 
</pre>
 
</pre>
  
 
* List
 
* List
 
 
<pre>
 
<pre>
 
 
<list_name> = []  # Empty list
 
<list_name> = []  # Empty list
 
 
<list_name>.append(<item>)
 
<list_name>.append(<item>)
 
 
</pre>
 
</pre>
  
 
* List samples
 
* List samples
 
 
<pre>
 
<pre>
 
 
my_list.index("dog")  # Return the first index that contains the string “dog”
 
my_list.index("dog")  # Return the first index that contains the string “dog”
 
 
my_list.insert(4,"cat") # Add item “cat” at index 4 and bump the rest forward
 
my_list.insert(4,"cat") # Add item “cat” at index 4 and bump the rest forward
 
 
</pre>
 
</pre>
  
 
* For loop the list
 
* For loop the list
 
 
<pre>
 
<pre>
 
 
my_list = [1,9,3,8,5,7]
 
my_list = [1,9,3,8,5,7]
 
 
for number in my_list:
 
for number in my_list:
 
+
print number * 2
    print number * 2
 
  
 
my_list.sort()
 
my_list.sort()
 
 
</pre>
 
</pre>
 
 
* Remove item from the list
 
* Remove item from the list
 
 
** n.pop(index) will remove the item at index from the list and return it to you:
 
** n.pop(index) will remove the item at index from the list and return it to you:
 
 
<pre>
 
<pre>
 
 
n = [1, 3, 5]
 
n = [1, 3, 5]
 
n.pop(1)
 
n.pop(1)
Line 121: Line 74:
 
# prints [1, 5]
 
# prints [1, 5]
 
</pre>
 
</pre>
 
 
** n.remove(item) will remove the actual item if it finds it:
 
** n.remove(item) will remove the actual item if it finds it:
 
 
<pre>
 
<pre>
 
 
n.remove(1)
 
n.remove(1)
 
# Removes 1 from the list,
 
# Removes 1 from the list,
Line 132: Line 82:
 
# prints [3, 5]
 
# prints [3, 5]
 
</pre>
 
</pre>
 
 
** del(n[1] is like .pop in that it will remove the item at the given index, but it won't return it:
 
** del(n[1] is like .pop in that it will remove the item at the given index, but it won't return it:
 
 
<pre>
 
<pre>
 
 
del(n[1])
 
del(n[1])
 
# Doesn't return anything
 
# Doesn't return anything
 
print n
 
print n
 
# prints [1, 5]
 
# prints [1, 5]
 
 
</pre>
 
</pre>
  
 
* Dictionary
 
* Dictionary
 
 
<pre>
 
<pre>
 
 
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
 
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
 
 
</pre>
 
</pre>
  
 
* Dictionary sample
 
* Dictionary sample
 
 
<pre>
 
<pre>
 
 
menu = {} # Empty dictionary
 
menu = {} # Empty dictionary
 
 
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
 
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
  
 
def plane_ride_cost(city):
 
def plane_ride_cost(city):
  data = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 475}
+
    data = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 475}
  return data[city]
+
    return data[city]
 
 
 
</pre>
 
</pre>
 
 
* Remove item in dictionary
 
* Remove item in dictionary
 
 
** del deletes a key and its value based on the key you tell it to delete
 
** del deletes a key and its value based on the key you tell it to delete
 
 
<pre>
 
<pre>
 
 
del dict_name[key_name]
 
del dict_name[key_name]
 
 
</pre>
 
</pre>
 
 
** .remove() removes a key and its value based on the value you tell it to delete.
 
** .remove() removes a key and its value based on the value you tell it to delete.
 
 
<pre>
 
<pre>
 
 
my_list.remove(value)
 
my_list.remove(value)
 
 
</pre>
 
</pre>
  
 
* More dictionary samples
 
* More dictionary samples
 
 
<pre>
 
<pre>
 
 
inventory = {'gold' : 500,
 
inventory = {'gold' : 500,
 
 
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
 
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
 
 
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
 
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
  
 
# Adding a key 'burlap bag' and assigning a list to it
 
# Adding a key 'burlap bag' and assigning a list to it
 
 
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
 
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
  
 
# Sorting the list found under the key 'pouch'
 
# Sorting the list found under the key 'pouch'
 
 
inventory['pouch'].sort()
 
inventory['pouch'].sort()
 
 
# Here the dictionary access expression takes the place of a list name
 
# Here the dictionary access expression takes the place of a list name
  
 
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
 
inventory['pocket'] = ['seashell', 'strange berry', 'lint']
 
 
inventory['backpack'].sort()
 
inventory['backpack'].sort()
  
Line 211: Line 133:
  
 
inventory['gold'] = inventory['gold']+50
 
inventory['gold'] = inventory['gold']+50
 
 
</pre>
 
</pre>
  
 
* Dictionaries are unordered
 
* Dictionaries are unordered
 
 
<pre>
 
<pre>
 
 
d => {"foo" : "bar"}
 
d => {"foo" : "bar"}
  
for key in d:
+
for key in d:  
  print d[key]  # prints "bar"
+
    print d[key]  # prints "bar"  
 
</pre>
 
</pre>
  
 
* Print vertically
 
* Print vertically
 
 
<pre>
 
<pre>
 
 
for letter in "Codecademy":
 
for letter in "Codecademy":
 
+
print letter
    print letter
 
  
 
C
 
C
Line 242: Line 158:
 
m
 
m
 
y
 
y
 
 
</pre>
 
</pre>
 
 
<pre>
 
<pre>
 
 
def average(alist):
 
def average(alist):
 
+
return sum(alist)/len(alist)
    return sum(alist)/len(alist)
 
  
 
score = round(score)
 
score = round(score)
 
 
</pre>
 
</pre>
  
Line 258: Line 169:
  
 
<pre>
 
<pre>
 
 
from random import randrange
 
from random import randrange
  
# Generate a
+
# Generate a  
 
 
 
random_number = randrange(1, 10)
 
random_number = randrange(1, 10)
 
 
</pre>
 
</pre>
  
 
* Enumerate
 
* Enumerate
 
 
<pre>
 
<pre>
  
Line 274: Line 181:
  
 
print 'Your choices are:'
 
print 'Your choices are:'
 
 
for index, item in enumerate(choices):
 
for index, item in enumerate(choices):
 
+
print index+1, item
    print index+1, item
 
 
 
 
</pre>
 
</pre>
  
 
* Zip
 
* Zip
 
 
** It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.
 
** It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.
 
 
** Zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
 
** Zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
 
 
** Zip can handle three or more lists as well!
 
** Zip can handle three or more lists as well!
 
 
<pre>
 
<pre>
  
 
list_a = [3, 9, 17, 15, 19]
 
list_a = [3, 9, 17, 15, 19]
 
 
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
 
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]
  
 
for a, b in zip(list_a, list_b):
 
for a, b in zip(list_a, list_b):
 
+
# Add your code here!
    # Add your code here!
+
print a, b
 
 
    print a, b
 
 
 
 
</pre>
 
</pre>

Revision as of 18:08, 8 April 2013

  • Comment
    • Single-line comment
# Hello World
    • Multiple-line comment
""""Hello
World"""
  • Functions
.isalpha()	# Check if alpha characters
<pre>
* Create a function
<pre>
def <function_name> ():

def <function_name> (arg):

def <function_name> (arg1, arg2):

def <function_name> (*args): # Multiple/unknown # of arguments, arbitrary number of arguments

sum(args)  # You add arguments up
  • Import defined functions
from <module> import <function>
Sample:
import math  		#  Import all, use math.sqrt 
math import sqrt  	# Import only sqrt, no need to qualify
from math import *	# Just import metadata??

import this 		# Easter Egg - The Zen of Python
  • If-then-else on one line
Boolean = True if (1 == 2) else False

if    :
elif   :
else:
  • List
<list_name> = []   # Empty list
<list_name>.append(<item>)
  • List samples
my_list.index("dog")  # Return the first index that contains the string “dog”
my_list.insert(4,"cat") # Add item “cat” at index 4 and bump the rest forward
  • For loop the list
my_list = [1,9,3,8,5,7]
for number in my_list:
	print number * 2

my_list.sort()
  • Remove item from the list
    • n.pop(index) will remove the item at index from the list and return it to you:
n = [1, 3, 5]
n.pop(1)
# Returns 3 (the item at index 1)
print n
# prints [1, 5]
    • n.remove(item) will remove the actual item if it finds it:
n.remove(1)
# Removes 1 from the list,
# NOT the item at index 1
print n
# prints [3, 5]
    • del(n[1] is like .pop in that it will remove the item at the given index, but it won't return it:
del(n[1])
# Doesn't return anything
print n
# prints [1, 5]
  • Dictionary
d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
  • Dictionary sample
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair

def plane_ride_cost(city):
    data = {"Charlotte": 183, "Tampa": 220, "Pittsburgh": 222, "Los Angeles": 475}
    return data[city]
  • Remove item in dictionary
    • del deletes a key and its value based on the key you tell it to delete
del dict_name[key_name]
    • .remove() removes a key and its value based on the value you tell it to delete.
my_list.remove(value)
  • More dictionary samples
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}

# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']

# Sorting the list found under the key 'pouch'
inventory['pouch'].sort()
# Here the dictionary access expression takes the place of a list name

inventory['pocket'] = ['seashell', 'strange berry', 'lint']
inventory['backpack'].sort()

inventory['backpack'].remove('dagger')

inventory['gold'] = inventory['gold']+50
  • Dictionaries are unordered
d => {"foo" : "bar"}

for key in d: 
    print d[key]  # prints "bar" 
  • Print vertically
for letter in "Codecademy":
	print letter

C
o
d
e
c
a
d
e
m
y
def average(alist):
	return sum(alist)/len(alist)

score = round(score)
  • Random modul
from random import randrange

# Generate a 
random_number = randrange(1, 10)
  • Enumerate

choices = ['pizza', 'pasta', 'salad', 'nachos']

print 'Your choices are:'
for index, item in enumerate(choices):
	print index+1, item
  • Zip
    • It's also common to need to iterate over two lists at once. This is where the built-in zip function comes in handy.
    • Zip will create pairs of elements when passed two lists, and will stop at the end of the shorter list.
    • Zip can handle three or more lists as well!

list_a = [3, 9, 17, 15, 19]
list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90]

for a, b in zip(list_a, list_b):
	# Add your code here!
	print a, b