Skip to content

Instantly share code, notes, and snippets.

@blzaugg
Created March 18, 2014 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blzaugg/9628581 to your computer and use it in GitHub Desktop.
Save blzaugg/9628581 to your computer and use it in GitHub Desktop.

Basic Syntax

Comments

age = 31 #this is a comment
"""How do these "comments" work? Are they comments?"""

Variables

Data Types

name = 'Byran Zaugg' #string
newline =  "Line one\nLine Two" #string with escape characters
multiline = """
I can have as many line in here
as I want. Just keep "typing" away,
as much as you want.
"""

age = 31 #int
temperature = 98.6 #float

male = True #boolean

###Type Casting

print int("34")
print repr("34")

Operators

print 1 + 1
print 1 - 2
print 4 * 2
print 4 / 2
print i += 1
print 1 % 5 # mod

Escape Codes

print "\tTab"
print "New\nLine"
print "Escaped\\Slash"

Scope


Input

Internal

print "How old are you?",
age = raw_input()
print "You are %s years old." % age

age = raw_input("How old are you? ")
print "You are %s years old." % age

print "How old are you?"
input_with_prompt = raw_input("> ")
print "You are %s years old." % input_with_prompt

External

from sys import argv
script, first, second, third, = argv

print "The script is called:", script
print "Your first argument is:", first
print "Your second argument is:", second
print "Your third argument is", third

file = open(filename, "w") # write
file2 = open(filename, "r") #read
file_data = file.read()
file.close()

print file_data

Output (write, print, etc)

print "Let's talk about %s." % name

print "one line"

print "one",
print "line"

print "two"
print "lines"

file = open(filename, "w") # write
file.truncate()
file.write("line 1")
file.write("\n")
file.write("line 2\n")
file.write("line 3")
file.close()

Conditionals

if 1 > 10:
    print "Test"
elif 3 == 5:
    print "Foo"
else:
    print "all done"

Operators

print 1 == 1
print 2 > 1
print 3 >= 3
print 4 < 5
print 5 <= 5
print 6 != 7

Lists

from sys import argv

print argv[0]
print argv[1]
print argv[2]
print argv[3]

for i in argv:
    print i

list = "one", "two", "three"

numbers = []
numbers.append(2)
numbers.append("three") # ???
print len(numbers)

list = string.split(' ')
print string.pop()

' '.join(list)

Dictionaries

states = {'CA': 'Califonia',
'UT', 'Utah',
'ID', 'Idaho'}

states['AZ'] = 'Arizona'

state = 'AZ'
if state in states:
print states[state]

def my_function(dict, key):
return dict[key]

states['_some_funciton'] = my_function

print states['_some_funciton'](states, 'CA')

#or

return_funciton = states['_some_funciton']
print return_funciton(states, 'CA')

Loops

list = "one", "two", "three"
for i in list:
    print list + "\n"

while i < 6:
    print "At the top of the list is %d" % i
    i = i + 1

Break

while True:
    # ...
    break

Continue


Functions

def function_name():
    """We can have descriptions of functions inline"""
    print "This is a function"

Arguments

def function_name2(*args):
    arg1, arg2, arg3 = args
    print arg1

def function_name3(arg1, arg2):
    print arg1

function_name3("test", "foo")

Return

def add(a, b):
    return a + b

print add(2, 4)

String Manipulation

print "Let's talk about %s." % name
print "I am %d years old." % 31
print "He's got %s eyes and %s hair." % (eyes_color, "brown")
print "If I add %d, %d, and %d I get %d." % (
    age, height, weight, age + height + weight)
print "one " + "two " + three #contationation
print "Here are the days:", days #spaced contationation
print "." * 10 #repeats string 10 times

print('%(language)s has %(number)03d quote types.' %
    {'language': "Python", "number": 2})

###Formatter

formatter = "%r %r %r %r"

print formatter % (1, 2, 3, 4)
print formatter % ("one", "two", "three", "four")
print formatter % (True, False, False, True)
print formatter % (formatter, formatter, formatter, formatter)
print formatter % (
    "I had this thing.",
    "That you could type up, right.",
    "But it didn't sing.",
    "So I said goodnight."
)

###String Formatting/Interpolation

print repr("hi") # $r - formal representation
print str("hi") # %s - informal representation

Libraries

import sys
print sys.argv

from sys import argv
print argv

import python_file # python_file.py
print python_file.method_name("test")

Classes

class MyClass(object):
    def __init__(self):
        self.number = 0

a = MyClass()

Methods

class MyClass(object):
    def __init__(self):
        self.number = 0

    def some_funct(self):
        print "I got called."

    def add_me_up(self, more):
        self.number += more
        return self.number

a = MyClass()
b = MyClass()

a.some_funct()
b.some_funct()

print a.add_me_up(20)
print a.add_me_up(20)
print b.add_me_up(30)
print b.add_me_up(30)

print a.number
print b.number

Properties

Private vs Public


Objects

Methods

Properties


Errors


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment