# Single line remark
""" Multi-line strings can use
three quotation marks to pack, which can also be regarded as
multi-line remarks
"""
####################################################
## 1. Raw Data Types & Operators
####################################################
# Number type
3 # => 3
# Simple operations
1 + 1 # => 2
8 - 1 # => 7
10 * 2 # => 20
35 / 5 # => 7
# The division of integer will automatically have integer numbers
5 / 2 # => 2
# If we want to perform a precise division operation, we need to introduce the float
2.0 # the float
11.0 / 4.0 # => 2.75 more precise
# The grouping operator can bring the highest precedence
(1 + 3) * 2 # => 8
# Boolean value is also a basic data type
True
False
# Use not to perform the Logical NOT operation
not True # => False
not False # => True
# Equality
1 == 1 # => True
2 == 1 # => False
# Inequality
1 != 1 # => False
2 != 1 # => True
# More comparison operators
1 < 10 # => True
1 > 10 # => False
2 <= 2 # => True
2 >= 2 # => True
# Comparison operations can be chained together to write
1 < 2 < 3 # => True
2 < 3 < 2 # => False
# Use " or ' to pack the strings
"This is a string."
'This is also a string.'
# Use + to connect strings
"Hello " + "world!" # => "Hello world!"
# A string can be regarded as a list of characters
"This is a string"[0] # => 'T'
# Use % to format strings
"%s can be %s" % ("strings", "interpolated")
# You can also use the "format" method to format the strings
# The method is recommended
"{0} can be {1}".format("strings", "formatted")
# You can also use the variable name to replace the number
"{name} wants to eat {food}".format(name="Bob", food="lasagna")
# None is a object
None # => None
# Do not use the equality mark `==` to compare with None
# but use `is` to compare
"etc" is None # => False
None is None # => True
# 'is' can be used to compare the equality of objects
# this operator is not very useful when comparing raw data, but it is necessary when comparing objects
# None, 0 and null string are all regarded as False
# Others are regarded as True
0 == False # => True
"" == False # => True
####################################################
## 2. Variables & Collections
####################################################
# Convenient Export
print "I'm Python. Nice to meet you!"
# No declaration is needed before the variable assignment
some_var = 5 # It is generally recommended to use a combination of lowercase letters and underscores as variable names
some_var # => 5
# Accessing a unassigned variable will raise an error
# You can read the section of Control Flow to know how to deal with the error
some_other_var # Raise NameError
# The statement of if can be used as an expression
"yahoo!" if 3 > 2 else 2 # => "yahoo!"
# The list is used to save sequences
li = []
# You can directly use the initialized list
other_li = [4, 5, 6]
# You can add elements in the end of the list
li.append(1) # li now is [1]
li.append(2) # li now is [1, 2]
li.append(4) # li now is [1, 2, 4]
li.append(3) # li now is [1, 2, 4, 3]
# Remove the elements in the end of the list
li.pop() # => 3 li now is [1, 2, 4]
# Add again
li.append(3) # li is now [1, 2, 4, 3] again.
# The way of accessing the list is like the way of accessing an array in other languages
li[0] # => 1
# Access the last element
li[-1] # => 3
# Crossing the bounds will cause the exception
li[4] # Raise out of bounds exception
# Slicing needs to be used to the index access of the list
# It can be regarded as the left closed and right open interval in mathematics
li[1:3] # => [2, 4]
# Omit the element at the beginning
li[2:] # => [4, 3]
# Omit the elements in the end
li[:3] # => [1, 2, 4]
# Delete the specified elements
del li[2] # li now is [1, 2, 3]
# Merge lists
li + other_li # => [1, 2, 3, 4, 5, 6] - that will not change the two lists
# Use extend to merge lists
li.extend(other_li) # li is [1, 2, 3, 4, 5, 6]
# Use in to return whether the elements are in the list
1 in li # => True
# Return the list length
len(li) # => 6
# A tuple is similar to a list, but it cannot be modified
tup = (1, 2, 3)
tup[0] # => 1
tup[0] = 3 # type error
# Most list operations are applicable to tuples
len(tup) # => 3
tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6)
tup[:2] # => (1, 2)
2 in tup # => True
# You can unpack the tuple and assign it to multiple variables
a, b, c = (1, 2, 3) # a is 1, b is 2, c is 3
# If the brackets are not added, it will be regarded as tuple automatically
d, e, f = 4, 5, 6
# Now we can see how easy it is to exchange two numbers
e, d = d, e # d is 5, e is 4
# Use dictionary to store the mapping relations
empty_dict = {}
# dictionary initialization
filled_dict = {"one": 1, "two": 2, "three": 3}
# The dictionary also uses square brackets to access elements
filled_dict["one"] # => 1
# Save all keys in the list
filled_dict.keys() # => ["three", "two", "one"]
# The order of keys is not unique, and the obtained order is not necessarily the same
# Save all values in the list
filled_dict.values() # => [3, 2, 1]
# in the same order of the keys
# Judge whether a key exists
"one" in filled_dict # => True
1 in filled_dict # => False
# Querying a non-existing key will raise KeyError
filled_dict["four"] # KeyError
# Use get method to avoid KeyError
filled_dict.get("one") # => 1
filled_dict.get("four") # => None
# get method supports to return a default when the key does not exist
filled_dict.get("one", 4) # => 1
filled_dict.get("four", 4) # => 4
# setdefault is a safer method to add dictionary elements
filled_dict.setdefault("five", 5) # the value of filled_dict["five"] is 5
filled_dict.setdefault("five", 6) # the value of filled_dict["five"] is still 5
# Collect and store non-ordered elements
empty_set = set()
# Initialize a collection
some_set = set([1, 2, 2, 3, 4]) # some_set now is set([1, 2, 3, 4])
# After Python 2.7, braces can be used to express a collection
filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4}
# Add elements in the collection
filled_set.add(5) # filled_set now is {1, 2, 3, 4, 5}
# Use & to calculate the intersection of the collection
other_set = {3, 4, 5, 6}
filled_set & other_set # => {3, 4, 5}
# Use | to calculate the union of the collection
filled_set | other_set # => {1, 2, 3, 4, 5, 6}
# Use - to to calculate the difference of the collection
{1, 2, 3, 4} - {2, 3, 5} # => {1, 4}
# Use in to judge whether the elements are in the collection
2 in filled_set # => True
10 in filled_set # => False
####################################################
## 3. Control Flow
####################################################
# Create a new variable
some_var = 5
# This is a statement of if, indentation is very important in python
# The following code snippet will export "some var is smaller than 10"
if some_var > 10:
print "some_var is totally bigger than 10."
elif some_var < 10: # The elif statement is not necessary
print "some_var is smaller than 10."
else: # else is not necessary either
print "some_var is indeed 10."
"""
Use for loop to traverse the list
exports:
dog is a mammal
cat is a mammal
mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
# You can use % to format the strings
print "%s is a mammal" % animal
"""
`range(number)` returns the list of numbers from 0 to the specified number
exports:
0
1
2
3
"""
for i in range(4):
print i
"""
while loop
exports:
0
1
2
3
"""
x = 0
while x < 4:
print x
x += 1 # Abbreviation of x = x + 1
# use try/except block to handle errors
# Python 2.6 and above are applicable to:
try:
# Use "raise" to throw out an exception
raise IndexError("This is an index error")
except IndexError as e:
pass # pass does nothing, but it usually does some recovery work
####################################################
## 4. Functions
####################################################
# Use def to create a new function
def add(x, y):
print "x is %s and y is %s" % (x, y)
return x + y # Return a value by "return"
# Call a function with parameters
add(5, 6) # => import "x is 5 and y is 6", and return 11
# Use keyword assignment to call a function
add(y=6, x=5) # The order doe not matter
# We can also define a function accepting multiple variables, and those variables are arranged in order
def varargs(*args):
return args
varargs(1, 2, 3) # => (1,2,3)
# We can also define a function accepting multiple variables, and those variables are arranged by keywords
def keyword_args(**kwargs):
return kwargs
# Actual result:
keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"}
# You can also define one function in two forms
def all_the_args(*args, **kwargs):
print args
print kwargs
"""
all_the_args(1, 2, a=3, b=4) prints:
(1, 2)
{"a": 3, "b": 4}
"""
# When call a function, we can also perform the converse operation, and unfold the tuple and dictionary as parameters
args = (1, 2, 3, 4)
kwargs = {"a": 3, "b": 4}
all_the_args(*args) # equal to foo(1, 2, 3, 4)
all_the_args(**kwargs) # equal to foo(a=3, b=4)
all_the_args(*args, **kwargs) # equal to foo(1, 2, 3, 4, a=3, b=4)
# Function is the first class in python
def create_adder(x):
def adder(y):
return x + y
return adder
add_10 = create_adder(10)
add_10(3) # => 13
# Anonymous function
(lambda x: x > 2)(3) # => True
# Built-in higher-order function
map(add_10, [1, 2, 3]) # => [11, 12, 13]
filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7]
# You can use the list method to quote the higher-order function in a smarter way:
[add_10(i) for i in [1, 2, 3]] # => [11, 12, 13]
[x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7]
####################################################
## 5. Class
####################################################
# Our new class is inherited from the object class
class Human(object):
# Class attributes, shared by the objects of all classes
species = "H. sapiens"
# Basic constructors
def __init__(self, name):
# Assign parameters to object member attributes
self.name = name
# Member method; self has to be included in the parameters
def say(self, msg):
return "%s: %s" % (self.name, msg)
# Class methods, shared by all objects of all classes
# When this kind of methods are called, they will pass the class to the first parameter
@classmethod
def get_species(cls):
return cls.species
# Static method needs the quotation of classes and objects to be called
@staticmethod
def grunt():
return "*grunt*"
# Instantiation of a class
i = Human(name="Ian")
print i.say("hi") # export "Ian: hi"
j = Human("Joel")
print j.say("hello") # export "Joel: hello"
# Method of accessing a class
i.get_species() # => "H. sapiens"
# Modifying the shared attribute
Human.species = "H. neanderthalensis"
i.get_species() # => "H. neanderthalensis"
j.get_species() # => "H. neanderthalensis"
# Accessing static variables
Human.grunt() # => "*grunt*"
####################################################
## 6. Module
####################################################
# We can import other modules
import math
print math.sqrt(16) # => 4
# We can also import a specified function from a module
from math import ceil, floor
print ceil(3.7) # => 4.0
print floor(3.7) # => 3.0
# Import all functions from a module
# Warning: it is not recommended
from math import *
# Abbreviation of module name
import math as m
math.sqrt(16) == m.sqrt(16) # => True
# Modules in Python are actually just ordinary python files
# You can also create your own modules and import them
# Module names are the same as the file names
# You can also check the attributes and methods in a module by the following method:
import math
dir(math)