Python: Basics

From Ittichai Chammavanijakul's Wiki
Jump to navigation Jump to search
  • Single-line comment
# Hello World
  • Multiple-line comment
""""Hello
World"""
  • Functions
.isalpha()	# Check if alpha characters
  • Create a function
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 module
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