Skip to content

Instantly share code, notes, and snippets.

@khanhtran3005
Last active September 15, 2018 07:59
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 khanhtran3005/4de955776d8a6575852849947f76c2d3 to your computer and use it in GitHub Desktop.
Save khanhtran3005/4de955776d8a6575852849947f76c2d3 to your computer and use it in GitHub Desktop.
Learning Python's notes

String Formatting

# Basic usage
print('We are the {} who say "{}!"'.format('knights', 'Ni'))

# Using index of the passed object
print('Low limit: {0}, high limit: {1}'.format(10, 200))

# using the name of the argument.
print('Low limit: {low:.2f}, high limit: {high:.2f}'.format(low=10.0, high=200.3256))

# String format using dictionary 
data = {'low': low, 'high': high}
print('Low limit: {low}, high limit: {high}'.format(**data))

Loops

  • for item in array
  • "else" clause for loops
count=0
while(count<5):
    print count
    count +=1
else:
    print "count value reached %d" %(count)

Classes and Objects

class MyClass:
variable = "blah"

def function(self):
    print "This is a message inside the class."
    
# create an object
myobjectx = MyClass()

#  access to a variable
print myobjectx.variable

Dictionaries

phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}
for name, number in phonebook.items():
    print "Phone number of %s is %d" % (name, number)

# Removing a value
del phonebook["John"]

There is no switch-case in Python, so we can use dictionaries as switch-case alternative.

{
    "Charlotte": 183,
    "Tampa": 220,
    "Pittsburgh": 222,
    "Los Angeles": 475,
}.get(city, 300)       # Default value is 300

Generator "yield"

  • Return an iterable set of items
  • Once the generator's function code reaches a "yield" statement, the generator yields its execution back to the for loop, returning a new value from the set

Simplify codes

for word in words:
    if word != "the":
        word_lengths.append(len(word))
        
###############

word_lengths = [len(word) for word in words if word != "the"]

Multiple Function Arguments

  • *therest receive a variable number of arguments
  • **options send functions arguments by keyword
def bar(first, second, third, **options):
    if options.get("action") == "sum":
        #do something
    if options.get("number") == "first":
        #do something

bar(1, 2, 3, action = "sum", number = "first")

Regex

pattern = re.compile(r"your pattern here")

#return search object or None
re.search(pattern, "I'm KT") 
re.match(pattern, email)

Set

Sets are lists with no duplicate entries.

print set("my name is Eric and Eric is my name".split())

Result:

set(['and', 'is', 'my', 'name', 'Eric'])

  • a.intersection(b) find out which items in both list
  • a.symmetric_difference(b) find out which items in only one list
  • a.difference(b) find out which items only in a and not in b
  • a.union(b) merge 2 sets without duplications.

Serialization

json and cPickle are the popular libs for serialize data in Python

  • To serialize: a.dumps([list])
  • To unserialize: a.loads([list])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment