0% found this document useful (0 votes)
8 views

Python Python Dictionary Cover All Essential Python Syntaxes B09NFLK1YS

Uploaded by

lsbexcel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Python Python Dictionary Cover All Essential Python Syntaxes B09NFLK1YS

Uploaded by

lsbexcel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

Python

Syntax Book

( Cover All Essential


Python Syntaxes )

Ray Yao
About This Book

This book covers all essential Python syntaxes. We can quickly reference the
most helpful programming syntaxes, such as common command syntax,
string function syntax, collection function syntax, class & object syntax……;
all these syntaxes are very useful for programming.

We can take this book as a small programming dictionary, because its entries
are arranged alphabetically, so that we can easily reference the important
syntax.

Nowadays or in the future, the Python Syntax Book can provide great help
for coding both in our study and our work.
Table of Contents

Syntax Chart
# symbol syntax:
* symbol syntax:
** symbol syntax:
+ symbol syntax:
symbol syntax:
>>> symbol syntax:
''' symbol syntax:
""" symbol syntax:
abs() syntax:
add() syntax:
all() syntax:
and syntax:
any() syntax:
append syntax:
append() syntax:
as syntax:
ascii() syntax:
assert() syntax:
bin() syntax:
bool() syntax:
break syntax:
bytearray() syntax:
bytes() syntax:
calendar syntax:
callable() syntax:
capitalize() syntax:
casefold() syntax:
casting syntax:
ceil() syntax:
center() syntax:
character syntax:
character syntax:
chdir syntax:
chr() syntax:
class syntax:
class BaseClass syntax:
clear() syntax:
close syntax:
command prompt syntax:
comment syntax:
compile() syntax:
compile() syntax:
complex() syntax:
connect lists syntax:
connect strings syntax:
continue syntax:
convert data type syntax:
copy() syntax:
count() syntax:
count() syntax:
decode() syntax:
def functionName( ) syntax:
def functionName(arguments) syntax:
del syntax:
delattr() syntax:
def main( )syntax:
del myVariable syntax:
demjson.decode(json) syntax:
demjson.encode(data) syntax:
dict() syntax:
dictionary syntax:
difference() syntax:
difference_update() syntax:
dir() syntax:
directory syntax:
directory syntax:
directory syntax:
discard() syntax:
divmod() syntax:
double quotes syntax:
dumps() syntax:
elif syntax:
else syntax:
encode() syntax:
endwith() syntax:
enumerate() syntax:
environment variable syntax:
environment variable syntax:
evel() syntax:
except syntax:
exception syntax:
exception syntax:
exception syntax:
exec() syntax:
expandtabs() syntax:
extend() syntax:
file syntax:
file.close() syntax:
fileno() syntax:
filter() syntax:
finally syntax:
find() syntax:
findall() syntax:
finditer() syntax:
float() syntax:
floor() syntax:
flush() syntax:
for syntax:
for var in range(n1, n2) syntax:
format() syntax:
format() syntax:
format printing syntax:
from anotherFile import* syntax:
from module import * syntax:
fromkeys() syntax:
frozenset() syntax:
function syntax:
function with arguments syntax:
get() syntax:
getattr() syntax:
getcwd() syntax:
global syntax:
global() function syntax
hasattr() syntax
hash() syntax:
help() syntax:
header syntax:
hex() syntax:
http syntax:
id() syntax:
if syntax:
if syntax:
if-elif syntax:
if / else syntax:
import syntax:
import calendar syntax:
import json syntax:
import module syntax:
import os syntax:
import re syntax:
import smtplib syntax:
import time syntax:
import webbrowser syntax:
in syntax:
index syntax:
index1 : index2 syntax:
index() syntax:
inherit syntax:
input syntax:
insert() syntax:
int() syntax
intersection() syntax:
intersection_update() syntax:
is syntax:
isalnum() syntax:
isalpha() syntax:
isascii() syntax:
isatty() syntax:
isdecimal() syntax:
isdigit() syntax:
isdisjoint() syntax:
isidentifier() syntax:
isinstance() syntax:
islower() syntax:
isnumeric() syntax:
isprintable() syntax:
isspace() syntax:
issubclass() syntax:
issubset() syntax:
issuperset() syntax:
istitle() syntax:
isupper() syntax:
items() syntax:
iter() syntax:
join() syntax:
json syntax:
json syntax:
json syntax
json syntax:
keys() syntax:
lambda syntax:
len() syntax:
list syntax:
list syntax:
list() syntax:
listdir() syntax:
ljust() syntax:
locals() syntax:
localtime syntax:
loads syntax:
lower() syntax:
lstrip() syntax:
main() syntax:
maketran() syntax:
map() syntax:
match() syntax:
match() syntax:
math.ceil( ) syntax:
math.floor( ) syntax:
math.max( ) syntax:
math.min( ) syntax:
math.pow( ) syntax:
math.sqrt( ) syntax:
max() syntax:
memoryview() syntax:
min() syntax:
mkdir syntax:
module syntax:
module syntax:
module syntax:
nesting while loop syntax:
next() syntax:
None syntax:
nonlocal syntax:
not syntax:
not in syntax:
object creating syntax:
object() syntax:
oct() syntax:
open(“fileName”, “a”) syntax:
open(“fileName”, “r”) syntax:
open(“fileName”, “w”) syntax:
open(filename, “argument”) syntax:
or syntax:
ord() syntax:
os.chdir(path) syntax:
os.getcwd() syntax:
os.listdir(path) syntax:
overriding syntax:
parser() syntax:
partition() syntax:
pass syntax:
pattern syntax:
pattern.match(string) syntax:
pop() syntax:
pop() syntax:
popitem() syntax:
pow() syntax:
print() format syntax:
print() syntax:
property() syntax:
raise syntax:
range syntax:
range syntax:
randrange() syntax:
read() syntax:
readable() syntax:
readline() syntax:
readlines() syntax:
reload() syntax:
remove() syntax:
remove() syntax:
rename() syntax:
repeat symbol syntax:
replace() syntax:
repr() syntax:
return syntax:
reverse() syntax:
reversed() syntax:
rfind() syntax:
rindex() syntax:
rjust() syntax:
rmdir() syntax:
round() syntax:
rpartition() syntax:
rsplit() syntax:
rstrip() syntax:
search() syntax:
seek() syntax:
seekable() syntax:
sendmail() syntax:
separator.join() syntax:
set environment variable syntax:
set syntax:
set() syntax:
setattr() syntax:
set-cookie syntax:
setdefault() syntax:
single quotes syntax:
slice() syntax:
slicing syntax:
smtp syntax:
smtp.sendmail( ) syntax:
socket() syntax:
sort() syntax:
sorted() syntax:
split() syntax:
splitlines() syntax:
sqrt() syntax:
startwith() syntax:
staticmethod() syntax:
str() syntax:
strftime() syntax:
str = ‘string’ syntax:
str = "string" syntax:
str = ‘‘‘strings’’’ syntax:
str.swapcase() syntax:
str.zfill(length) syntax:
string[index] syntax:
string[index1: index2] syntax:
strip() syntax:
sub syntax:
substring syntax:
sum() syntax:
supper() syntax:
swapcase() syntax:
symmetric_difference() syntax:
symmetric_difference_update() syntax:
tell() syntax:
thread syntax:
time.strftime( ) syntax:
timestamp syntax:
translate() syntax:
triple quotes syntax:
truncate() syntax:
try - except syntax:
tuple() syntax:
tuple creating syntax:
type() syntax:
union() syntax:
unpack a collection syntax:
update() syntax:
update() syntax:
upper() syntax:
url syntax:
values() syntax:
variable assignment syntax:
variable define syntax:
variable delete syntax:
vars() syntax:
webbrowser syntax:
while loop syntax:
while loop syntax:
with syntax:
write() syntax:
writable() syntax:
writelines() syntax:
xml.sax.make_parser() syntax:
yield syntax:
zfill() syntax:
zip() syntax:
Appendix
Arithmetic Operator Chart
Assignment Operators Chart
Comparison Operators Chart
Logical Operators Chart
Bitwise Operators
Convert Data Type Chart
Math Function Chart
List Functions Chart
Tuple Functions Chart
Set Functions Chart
Dictionary Functions Chart
Data Structure Difference Chart
Escape Characters Chart
Operation Strings Chart
Testing Functions Chart
Formatting Functions Chart
Stripping Functions Chart
Splitting Functions Chart
Searching Functions Chart
String Functions (1) Chart
String Functions (2) Chart
Regular Expressions Chart
Format String Chart
Open File’s Mode Chart

Recommended Books
Syntax Chart

------------------------------------------------------------------------------
# symbol syntax:
#
# This symbol is used as a comment symbol.
e.g.
print("Hello World! ")
# print() is used to output contents
------------------------------------------------------------------------------

* symbol syntax:
*
# This symbol is used in regex to repeat a string
e.g.
re*
# matche 0 or more expressions
------------------------------------------------------------------------------

** symbol syntax:
**
# Exponentiation
e.g.
a=2
b=3
print(a ** b) # just like 2*2*2
# Output: 8
------------------------------------------------------------------------------
+ symbol syntax:
+
# Concatenate two strings together
e.g.
myString = "Python "+ "is a good language"
# Output: Python is a good language
------------------------------------------------------------------------------
// symbol syntax:
//
# Floor division: rounds the result down to the closest number
e.g.
a = 17
b=2
print(a // b)
# Output: 8
------------------------------------------------------------------------------
>>> symbol syntax:
>>>
# This symbol is the Python interactive command shell prompt, requests the
input from the user.
e.g.
>>> " Hello " + " World! "
# Output: Hello World!
------------------------------------------------------------------------------
''' symbol syntax:
'''
# Three single quotes are used for multi-line string
e.g.
'''
We are a multi-line string,
which contains more than one line strings.
The multi-line string can also work as a comment sometimes.
'''
------------------------------------------------------------------------------
""" symbol syntax:
"""
# Three double quotes are used for multi-line string
e.g.
"""
We are a multi-line string,
which contains more than one line strings.
The multi-line string can also work as a comment sometimes.
"""
------------------------------------------------------------------------------
abs() syntax:
abs( )
# Return an absolute value of a number.
e.g.
print("abs(-100) =", abs(-100))
# Output: abs(-100) = 100
------------------------------------------------------------------------------
add() syntax:
set.add("element")
# Add an element to the unsorted set
e.g.
mySet = {"ant", "bee", "cat"}
mySet.add("dog")
print(mySet)
# Output: {'cat', 'dog', 'ant', 'bee'}
------------------------------------------------------------------------------
all() syntax:
all()
# Return true if all elements in a collection are true
e.g.
mylist = [True, False, True]
print(all(mylist))
# Output: False
------------------------------------------------------------------------------
and syntax:
operand1 and operand2
# Return true if its both operands are true.
e.g.
b = (6<10 and 10>8)
print(b)
# Output: True
------------------------------------------------------------------------------
any() syntax:
any()
# Return true if any element in a collection is true
e.g.
mylist = [True, False, True]
print(any(mylist))
# Output: True
------------------------------------------------------------------------------
append syntax:
open(“fileName”, “a”)
write( “text” )
# Open a file by using “a” mode for appending text
# write( “text” ) writes text to the file
e.g.
f = open("myFile.txt", "a")
f.write(" This is the appended text.")
------------------------------------------------------------------------------
append() syntax:
append(element)
# Append an element at the end of the list
e.g.
animals = ["ass", "bat", "cow"]
animals.append("dog")
print(animals)
# Output: ['ass', 'bat', 'cow', 'dog']
------------------------------------------------------------------------------
as syntax:
import module as alias
# Create an alias of the module
e.g.
import calendar as c
print(c.month_name[8])
# Output: August

------------------------------------------------------------------------------
ascii() syntax:
ascii()
# Returns a readable text by escaping none-ascii characters
e.g.
text = ascii("This village is called Båtåky")
print(text)
# Output: 'This village is called B\xe5t\xe5ky'
------------------------------------------------------------------------------
assert() syntax:
assert (test-expression), error-message
# In assert statement, if test-expression returns false, an error message will
appear.
e.g.
myArr = ["a", "b", "c", "d", "e"]
assert (index > 6), "Index out of range!"
------------------------------------------------------------------------------
bin() syntax:
bin()
# Return a binary number starting with 0b.
e.g.
num = bin(9)
print(num)
# Output: 0b1001
------------------------------------------------------------------------------
bool() syntax:
bool(value)
# Check if the value is true or false
e.g.
print(bool(0))
print(bool(100))
print(bool(None))
# Output: False, True, False
------------------------------------------------------------------------------
break syntax:
break
# Stop running of a loop according to the condition.
e.g.
if num==5:
break
------------------------------------------------------------------------------
bytearray() syntax:
bytearray()
# Return a array with a specified byte's length.
e.g.
n= bytearray(2) # set 2 bytes' length
print(n)
# Output: bytearray(b'\x00\x00)
------------------------------------------------------------------------------
bytes() syntax:
bytes()
# Return a byites object
e.g.
n = bytes(6)
print(n)
# Output: b'\x00\x00\x00\x00\x00\x00'
------------------------------------------------------------------------------
calendar syntax:
import calendar
cal = calendar.month(year, month)
# Get a calendar of the year and month
e.g.
import calendar
cal = calendar.month(2020, 1)
# Returns a calendar in Jan, 2020
------------------------------------------------------------------------------
callable() syntax:
callable()
# Return true if a function is callable
e.b.
def func():
print(10)
print(callable(func))
# Output: True
------------------------------------------------------------------------------
capitalize() syntax:
capitalize()
# Change the first letter to uppercase
e.g.
str = "jQuery"
print(str.capitalize())
# Output: Jquery
------------------------------------------------------------------------------
casefold() syntax:
string.casefold()
# convert a string to lower case
e.g.
str = "JQuery in 8 Hours"
s = str.casefold()
print(s)
# Output: jquery in 8 hours
------------------------------------------------------------------------------
casting syntax:
int(), str(), float()
# convert type to int, str, float respectively
e.g.
x = str(8) # x will be '8'
y = int(8) # y will be 8
z = float(8) # z will be 8.0
------------------------------------------------------------------------------
ceil() syntax:
math.ceil( );
# Return an integer that is greater than or equal to its argument.
e.g.
import math
print(math.ceil(9.5))
# Output: 10
------------------------------------------------------------------------------
center() syntax:
center(w, f)
# Center the string with width w and fill with f
e.g.
str = "this is a center example"
print(str.center(35, '$'))
# Output: $$$$$$this is a center example$$$$$
------------------------------------------------------------------------------
character syntax:
string[index]
# Return a character of the string at the specified index
e.g.
str = "Python"
print(str[2])
# Output: t
------------------------------------------------------------------------------
character syntax:
string[index1: index2]
# Return characters from index1 to index2-1
e.g.
myString = "Python is a good language"
print(myString[7:16])
# Output: is a good
------------------------------------------------------------------------------
chdir syntax:
import os
os.chdir(path)
# Change a directory
e.g.
os.chdir("/home/mydir")
# set “mydir” as a current working directory
------------------------------------------------------------------------------
chr() syntax:
chr()
# Return a character from an Unicode code
e.g.
c = chr(86)
print(c)
# Ourput: V
------------------------------------------------------------------------------
class syntax:
class ClassName: # define a class
classVariable = value # declare a class variable
def __init__(self): # declare a constructor,
def classMethod(self): # define a class method
e.g.
class Animal: # define a class
count = 0
def __init__(self):
self.name = value 1
self.size = value2
def show(self):
print(self.name)
print(self.size)
------------------------------------------------------------------------------
class BaseClass syntax:
class BaseClass: # define a base class
……
class DerivedClass (BaseClass): # define a derived class
……
# The derived class inherits all members of the base class.
e.g.
class Computer:
…..
class Desktop(Computer):
------------------------------------------------------------------------------
clear() syntax:
clear()
# Clear all elements of a collection
e.g.
animals = ["ass", "bat", "cow"]
animals.clear()
print(animals)
# Output: [ ]
------------------------------------------------------------------------------
close syntax:
file.close()
# Close a file
e.g.
myfile.close()
------------------------------------------------------------------------------
command prompt syntax:
>>>
# This symbol is the Python interactive command shell prompt, requests the
input from the user.
e.g.
>>> " Hello " + " World! "
# Output: Hello World!
------------------------------------------------------------------------------
comment syntax:
#
# This symbol is used as a comment symbol.
e.g.
print("Hello World! ")
# print() is used to output contents
------------------------------------------------------------------------------
compile() syntax:
import re
re.compile( regular expression)
# Return a pattern object by compiling the regular expression.
e.g.
import re
pattern = re.compile("^(\d{3})-(\d{3})-(\d{4})$")
# Returns a telephone number format of USA
------------------------------------------------------------------------------
compile() syntax:
compile('object','filename', 'exec')
# Return a code by compiling a string and using exec()
e.g.
str = 'print(168)'
code = compile(str, 'filename', 'exec')
exec(code)
# Output: 168
------------------------------------------------------------------------------
complex() syntax:
complex(x,y)
# Convert the real number x and imaginary number y into a complex number
e.g.
n = complex(6, 8)
print(n)
# Output: (6+8j)
------------------------------------------------------------------------------
connect lists syntax:
list1 + list2
# Connect two lists
e.g.
lst1 = [0, 1, 2]
lst2 = [3, 4, 5]
myList = lst1 + lst2
------------------------------------------------------------------------------
connect strings syntax:
+
# Concatenate two strings together
e.g.
myString = "Python "+ "is a good language"
print(myString)
# Output: Python is a good language
------------------------------------------------------------------------------
continue syntax:
continue
# Skip the next command and continue the next loop.
e.g.
if num==5:
continue
------------------------------------------------------------------------------
convert data type syntax:

type_keyword()
# convert to a specified type based on type_keyword
e.g.
str("Golang in 8 Hours") # convert to str type
int(10.68) # convert to int type
float(10) # convert to float type
complex(1j) # convert to complex
list(("red", "yellow", "green")) # convert to list type
tuple(("red", "yellow", "green")) # convert to tuple typ
range(8) # convert to range type
dict(name="Smith", age=18) # convert to dict type
set(("red", "yellow", "green")) # convert to set type
frozenset(("red", "yellow", "green")) # convert to frozenset
bool(10) # convert to bool type
bytes(10) # convert to bytes type
bytearray(10) # convert to bytearray
type

memoryview(bytes(10)) # convert to memoryview type


------------------------------------------------------------------------------
copy() syntax:
copy()
# Return a copy of a collection
e.g.
animals = ["ass", "bat", "cow"]
animals.copy()
print(animals)
# Output: ['ass', 'bat', 'cow']
------------------------------------------------------------------------------
count() syntax:
count(ch)
# Count the number of the specified character
e.g.
str = "jQuery is a great language!"
print(str.count("a"))
# Output: 4
------------------------------------------------------------------------------
count() syntax:
collection.count(value)
# Count the number a specified value in a collection
e.g.
myTuple = (3, 8, 6, 5, 9, 2, 7, 6, 1, 6, 8)
print(myTuple.count(6))
# Output: 3
------------------------------------------------------------------------------
decode() syntax:
demjson.decode(json)
# Decode Json string, return Python data
e.g.
json = '{"a":10,"b":20,"c":30,"d":40,"e":50}';
data = demjson.decode(json)
------------------------------------------------------------------------------
def functionName( ) syntax:
def functionName( ): # define a function
function body
……
functionName( ) # call a function
e.g.
def myFunction( ):
print("This is a custom function.")
myFunction( )
# Output: This is a custom function.
------------------------------------------------------------------------------
def functionName(arguments) syntax:
def functionName(arguments):
function body
……
functionName(arg)
# Define a function with arguments
# Call a function with argument
e.g.
def userName(name):
print( "My name is " + name)
userName("Andy")
# Output: My name is Andy
------------------------------------------------------------------------------
del syntax:
del Class/object
# Delete a class or an object
e.g.
class MyClass:
name = "Andy"
del MyClass
# Delete MyClass
------------------------------------------------------------------------------
delattr() syntax:
delattr(class, attribute)
# Delete an attribute from a class
e.g.
class Student:
name = "Andy"
id = "0026"
delattr(Student, 'id')
# Delete the attribute 'id' from the class 'Student'
------------------------------------------------------------------------------
def main( )syntax:
def main ():
function body
# The main( ) function is a default start point of the whole program.
e.g.
def main():
print("Very good!")
------------------------------------------------------------------------------
del myVariable syntax:
del myVariable
# Delete a variable
e.g.
del myVar
-------------------------------------------------------------------------------
demjson.decode(json) syntax:
demjson.decode(json)
# Decode Json string, return Python data
e.g.
json = '{"a":10,"b":20,"c":30,"d":40,"e":50}';
data = demjson.decode(json)
-------------------------------------------------------------------------------
demjson.encode(data) syntax:
demjson.encode(data)
# Encode Python data, return Json string
e.g.
data = [ { 'a' : 10, 'b' : 20, 'c' : 30, 'd' : 40, 'e' : 50 } ]
json = demjson.encode(data)
------------------------------------------------------------------------------
dict() syntax:
dict()
# Return a dictionary
e.g.
d = dict(name = "Andy", id = "0026", age = 18)
print(d)
# Output: {'name': 'Andy', 'id': '0026', 'age': 18}
------------------------------------------------------------------------------
dictionary syntax:
dictionaryName = { key1: val1, key2:val2, key3:val3 }
# Define a dictionary
e.g.
light = {0:"red", 1:"yellow", 2:"green"} # create a dictionary
print(light) # show all keys:values in “light”
# Output: {0: 'red', 1: 'yellow', 2: 'green'}
------------------------------------------------------------------------------
difference() syntax:
set1.difference(set2)
# Return the difference between two sets
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ant", "bee", "cow"}
diff = set1.difference(set2)
print(diff)
# Output: {'cat'}
------------------------------------------------------------------------------
difference_update() syntax:
set1.difference_update(set2)
# Remove the same elements existing in both sets
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ant", "bee", "cow"}
set1.difference_update(set2)
print("Now the set1 is:")
print(set1)
# Output: Now the set1 is: {'cat'}
------------------------------------------------------------------------------
dir() syntax:
dir(object)
# List all functions or attribute in the specified object.
e.g.
import math
print(dir(math))
------------------------------------------------------------------------------
directory syntax:
os.chdir(path)
# Change a directory
e.g.
os.chdir("/home/mydir")
# Set “mydir” as a current working directory
------------------------------------------------------------------------------
directory syntax:
path = os.getcwd()
# Return the current working directory
e.g.
import os
print(os.getcwd())
# Returns current working directory
------------------------------------------------------------------------------
directory syntax:
os.listdir(path)
# List anything in the current directory
e.g.
import os
print(os.listdir(path))
# Returns files and sub directories in the directory
------------------------------------------------------------------------------
discard() syntax:
set.discard('element')
# Remove the specified element from a set
e.g.
mySet = {"ant", "bee", "cat"}
mySet.discard("bee")
print(mySet)
# Output: {'ant', 'cat'}
------------------------------------------------------------------------------
divmod() syntax:
divmod(x, y)
# Return a quotient and a remainder of x divided by y
e.g.
n = divmod(11, 3)
print(n)
# Output: (3,2)
------------------------------------------------------------------------------
double quotes syntax:
str = "string"
# Define a string using a pair of double quotes
e.g.
str = "I am a string enclosed by a pair of double quotes"
------------------------------------------------------------------------------
dumps() syntax:
import json
json.dumps(data)
# Encode python data, return Json string
e.g.
data = [ { 'a' : 10, 'b' : 20, 'c' : 30, 'd' : 40, 'e' : 50 } ]
json = json.dumps(data)
------------------------------------------------------------------------------
elif syntax:
elif condition
# same as 'else if'
e.g.
if n == 1:
print("1")
elif n == 2:
print("2")
else:
print("3")
------------------------------------------------------------------------------
else syntax:
else:
# Otherwise
e.g.
if n == 1:
print("1")
else:
print("0")
------------------------------------------------------------------------------
encode() syntax:
demjson.encode(data)
# Encode Python data, return Json string
e.g.
data = [ { 'a' : 10, 'b' : 20, 'c' : 30, 'd' : 40, 'e' : 50 } ]
json = demjson.encode(data)
------------------------------------------------------------------------------
endwith() syntax:
endwith(param)
# Check if the string ends with the param.
e.g.
str = "Perl in 8 Hours!"
s = str.endswith("!")
print(s)
# Output: True
------------------------------------------------------------------------------
enumerate() syntax:
enumerate(collection)
# Convert a collection to an enumerate object
e.g.
m = ('ant', 'bee', 'cat')
n = enumerate(m)
print(list(n))
# Output: [(0, 'ant'), (1, 'bee'), (2, 'cat')]
------------------------------------------------------------------------------
environment variable syntax:
set PYTHONPATH=path
# Set environment variable in Unix
e.g.
set PYTHONPATH=/usr/local/lib/python
------------------------------------------------------------------------------
environment variable syntax:
set PYTHONPATH=path;
# Set environment variable in Windows
e.g.
set PYTHONPATH=c:\python30\lib;
------------------------------------------------------------------------------
evel() syntax:
evel(expression)
# Evaluate the expression
e.g.
n = 'print(68)'
eval(n)
# Output: 68
------------------------------------------------------------------------------
except syntax:
except:
# Used in exceptions
e.g.
try:
n = 100/0
except:
print("Error Occurs!")
------------------------------------------------------------------------------
exception syntax:
finally:
# In “try/except” block, “finally” statement is the code that must be executed.
e.g.
finally:
print("Remind: please input number only.")
------------------------------------------------------------------------------
exception syntax:
raise Exception("message”)
# After the exception is raised, the subsequent code will not be executed.
e.g.
if status < 10:
raise Exception("Invalid status!", status)
------------------------------------------------------------------------------
exception syntax:
try:
……
except XxxError as message:
……
# “try block” contains the code that may cause an exception.
# “except block” catches the error, and handles the exception.
e.g.
try:
int(100/0)
except ValueError as message:
print("Exception occurs!", message)
------------------------------------------------------------------------------
exec() syntax:
exec(code)
# Execute the specified code
e.g.
c = 'name = "Ray Yao"\nprint(name)'
exec(c)
# Output: Ray Yao
------------------------------------------------------------------------------
expandtabs() syntax:
string.expandtabs()
# Expand the tabs some whitespaces
e.g.
str = "J\tA\tV\tA"
s = str.expandtabs(3) # three whitespaces
print(s)
# Output: J A V A
------------------------------------------------------------------------------
extend() syntax:
list1.extend(list2)
# Extend one list with another list
e.g.
list1 = ["ass", "bat", "cow"]
list2 = ["ant", "bee", "cat"]
list1.extend(list2)
print(list1)
# Output: ['ass', 'bat', 'cow', 'ant', 'bee', 'cat']
------------------------------------------------------------------------------
file syntax:
open(filename, “mode”)
# Open a file with mode
e.g.
f = open("tryFile.txt", "w")
# Open a file “tryFiel.txt” with “w” mode

------------------------------------------------------------------------------
file.close() syntax:
file.close()
# Close a file
e.g.
myfile.close()
------------------------------------------------------------------------------
fileno() syntax:
file.fileno()
# Return the file descriptor and the number of the stream
e.g.
print(fileObj.fileno())
------------------------------------------------------------------------------
filter() syntax:
filter(function, collection)
# Filter the numbers in the collection by running the function.
e.g.
collection = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
def func(number):
if number % 2 == 0:
return True
return False
evenNum = list(filter(func, collection)) # convert to list
print(evenNum)
# Output: [2,4,6,8,10]
------------------------------------------------------------------------------
finally syntax:
finally:
# In “try/except” block, “finally” statement is the code that must be executed.
e.g.
finally:
print("Remind: please input number only.")
------------------------------------------------------------------------------
find() syntax:
find(c)
# Return the index of first occurrence, or -1
e.g.
str = "JavaScript"
print(str.find("v"))
# Output: 2
------------------------------------------------------------------------------
findall() syntax:
findall(string[, pos, endpos)
# Find all the substrings that the regular expression matches in the string and
returns a list
# pos: start position
# endops: ending position
e.g.
import re
pattern = re.compile(r'\d+') # only find digital number
list = pattern.findall('ok23vary168good333', 0, 30)
print(list)
# Output: ['23', '168', '333']
------------------------------------------------------------------------------
finditer() syntax:
import re
re.finditer(pattern, string)
# Find all the substrings that the regular expression matches in the string, and
returns an iterator
e.g.
import re
iter = re.finditer(r"\d+","10a30bc50jf90")
for match in iter:
print(match.group())
# Output: 10 30 50 90
------------------------------------------------------------------------------
float() syntax:
float(number)
# Convert an integer number to a floating point number.
e.g.
n = float(10)
print(n)
# Outut: 10.0
------------------------------------------------------------------------------
floor() syntax:
math.floor( );
# Return an integer that is less than or equal to its argument.
e.g.
import math
print(math.floor(9.5))
# Output: 9
------------------------------------------------------------------------------
flush() syntax:
file.flush()
# Clear the buff before writing the file
e.g.
f.flush()
f.write(" Now let's begin to write! ")
------------------------------------------------------------------------------
for syntax:
for <variable> in <sequence> :
<statements>
# Repeats a given block of codes by specified number of times.
e.g.
for str in 'Good':
print(str)
# Outut: G o o d
------------------------------------------------------------------------------
for var in range(n1, n2) syntax:
for var in range(n1, n2)
# Generate a sequence from n1 to n2-1.
e.g.
for num in range(3,10) :
print(num)
# Output: 3,4,5,6,7,8,9
------------------------------------------------------------------------------
format() syntax:
format(value, type)
# Format a specified value
e.g.
n = format(0.85, '%')
print(n)
# Output: 85.000000%
------------------------------------------------------------------------------
format() syntax:
string.format(number)
# format() can format a number, and put the number in {} to combine a
string.
e.g.
n = 100
s = "My score in the test is {}"
print(s.format(n))
# Output: My score in the test is 100
------------------------------------------------------------------------------
format printing syntax:
print( " %s %d %c %f %h %o" % ('string', digit, ascii, float, hex, oct ))
# Output a formatted string
e.g.
print("My name is %s and age is %d" % ('Ray', 38))
# Output: My name is Ray and age is 38
-----------------------------------------------------------------------------
from anotherFile import* syntax:
from anotherFile import*
# Import anything from another file
e.g.
from support import *
# Import anything from the support file
------------------------------------------------------------------------------
from module import * syntax:
from module import *
# Imports a module to current file.
e.g.
from support import *
# Import anything from the support module
------------------------------------------------------------------------------
fromkeys() syntax:
dict.fromkeys(key, value)
# Create a dictionary containing the keys and value
e.g.
k = ('key1', 'key2', 'key3', 'key4')
v = 10
myDict = dict.fromkeys(k, v)
print(myDict)
# Output: {'key1': 10, 'key2': 10, 'key3': 10, 'key4': 10}
------------------------------------------------------------------------------
frozenset() syntax:
frozenset(collection)
# freeze the collection, make it unmutable.
e.g.
mylist = ['ant', 'bee', 'cat']
print(frozenset(mylist))
# Output: frozenset({'ant', 'bee', 'cat'})
------------------------------------------------------------------------------
function syntax:
def functionName( ):
function body
……
functionName( )
# Define a function
# Call a function
e.g.
def myFunction( ):
print("This is a custom function.")
myFunction( )
# Output: This is a custom function.
------------------------------------------------------------------------------
function with arguments syntax:
def functionName(arguments):
function body
……
functionName(arg)
# Define a function with arguments
# Call a function with argument
e.g.
def userName(name):
print( "My name is " + name)
userName("Andy")
# Output: My name is Andy
------------------------------------------------------------------------------
get() syntax:
get("key")
# Return a value of the specified key in dictionary
e.g.
student = {
"name": "Andy",
"id": "0026"
}
print(student.get("id"))
# Output: 0026
------------------------------------------------------------------------------
getattr() syntax:
getattr(object)
# get the attribute of the specified object
e.g.
class Student:
name = "Andy"
id = "0026"
print(getattr(Student, 'id'))
# Output: 0026
------------------------------------------------------------------------------
getcwd() syntax:
import os
print os.getcwd()
# Get current working directory
e.g.
import os
print(os.getcwd()) # return current working directory
# Output: C:\Python35
------------------------------------------------------------------------------
global syntax:
global variable
# To define a global variable inside a function, we need to use "global"
keyword
e.g.
def myFunc():
global myVar
# myVar becomes a global variable now
------------------------------------------------------------------------------
global() function syntax
global()
# The globals() function returns a dictionary containing the variables defined
in the global namespace.
e.g.
print(globals())
# Output: {'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__': ……}
------------------------------------------------------------------------------
hasattr() syntax
hasattr(object, attribute)
# Return true if the object has the specified attribute
e.g.
class Student:
name = "Andy"
id = "0026"
print(hasattr(Student, 'id'))
# Output: True
------------------------------------------------------------------------------
hash() syntax:
hash(object)
# Return a hash value of the specified object
e.g.
str = 'Scala in 8 Hours'
print(hash(str))
# Output: 160379786619873168
------------------------------------------------------------------------------
help() syntax:
help(object)
# Reference the built-in Python help system about the object
e.g.
help(list)
# Output:
Help on class list in module builtins:
class list(object)
| list(iterable=(), /)
| Built-in mutable sequence.
……
------------------------------------------------------------------------------
header syntax:
HTTP fieldName: field contents
# Specify the format of http header
e.g.
Content-type: text/html
# The "content-type :text/ html" is the part of the HTTP header that tells the
browser the Content type of the file.
------------------------------------------------------------------------------
hex() syntax:
hex(number)
# Converts a number to a hexadecimal value
e.g.
print(hex(168))
# Output: 0xa8
------------------------------------------------------------------------------
http syntax:
HTTP fieldName: field contents
# Specify the format of http header
e.g.
Content-type: text/html
# The "content-type :text/ html" is the part of the HTTP header that tells the
browser the Content type of the file.
------------------------------------------------------------------------------
id() syntax:
id(object)
# Return an id of the specified object or return a random memory address of
the specified object
e.g.
str = "Pandas in 8 Hours"
print(id(str))
# Output: 139680528469008
# This result will be different every time the program runs
------------------------------------------------------------------------------
if syntax:
if test-expression:
statements
# Execute statement only if a specified condition is true, does not execute any
statement if the condition is false.
e.g.
if a > b:
print("a is greater than b.")
------------------------------------------------------------------------------
if syntax:
if test-expression:
statements # run when text-expression is true
else:
statements # run when text-expression is false
e.g.
if a > b:
print("a is greater than b.")
else:
print("a is less than b")
------------------------------------------------------------------------------
if-elif syntax:
if condition1:
run statement1……
elif condition2:
run statement2……
elif condition3:
run statement3……
else:
run statement4……
# If a condition is satisfied, its statement will run, otherwise, run next elif.
e.g.
if num == 59:
print 'fail'
elif num == 60:
print 'pass'
elif num == 100:
print 'excellent'
elif num < 0:
print 'error'
else:
print 'nothing’
------------------------------------------------------------------------------
if / else syntax:
(if-true-do-this) if (test-expression) else (if-false-do-this)
# If true does the first part. If false does the last part.
e.g.
a=100
b=200
result = "apple" if (a<b) else "banana"
print(result)
# Output: apple
------------------------------------------------------------------------------
import syntax:
from anotherFile import*
# Import anything from another file
e.g.
from support import *
# Import anything from the support module
------------------------------------------------------------------------------
import calendar syntax:
import calendar
cal = calendar.month(year, month)
# Get a calendar of the year and month
e.g.
import calendar
cal = calendar.month(2020, 1)
# Returns a calendar on Jan. 2020
------------------------------------------------------------------------------
import json syntax:
import json
# Import Json
e.g.
import json
data = [ { 'a' : 10, 'b' : 20, 'c' : 30, 'd' : 40, 'e' : 50 } ]
json = json.dumps(data)
------------------------------------------------------------------------------
import module syntax:
import module
moduleName.function()
# “import module” imports an external module to current file.
# “moduleName.function()” calls the functions in the module file.
e.g.
import support
support.myfunction()
------------------------------------------------------------------------------
import os syntax:
import os
os.mkdir("mydir")
# Import os
e.g.
import os
os.mkdir("/tmp/home/mydir”)
# You can use getcwd() to check it.
------------------------------------------------------------------------------
import re syntax:
import re
re.compile( regular expression)
# Import re
e.g.
import re
pattern = re.compile("^(\d{3})-(\d{3})-(\d{4})$")
# returns a telephone number format of USA
------------------------------------------------------------------------------
import smtplib syntax:
import smtplib
# Import smtplib
e.g.
import smtplib
obj = smtplib.SMTP('localhost')
obj.sendmail(sender, receivers, message.as_string())
# obj.sendmail() sends email
------------------------------------------------------------------------------
import time syntax:
import time
# Import time
e.g.
import time
local_time = time.asctime( time.localtime(time.time()) )
print "The local time is :", local_time
# Get local time
------------------------------------------------------------------------------
import webbrowser syntax:
import webbrowser
webbrowser.open(“URL”)
# Open a specified web page
e.g.
import webbrowser
url = "http://www.amazon.com"
webbrowser.open(url)
------------------------------------------------------------------------------
in syntax:
in
# check a character existing in a string
e.g.
str = "C programing"
if ( "C" in str ):
print ("C is in the string")
# Output: C is in the string
------------------------------------------------------------------------------
index syntax:
string[index]
# Return a character of the string at the specified index
e.g.
str = "Python"
print(str[2])
# Output: t
------------------------------------------------------------------------------
index1 : index2 syntax:
string[index1: index2]
# Return characters from index1 to index2-1
e.g.
myString = "Python is a good language"
print(myString[7:16])
# Output: is a good
------------------------------------------------------------------------------
index() syntax:
index(character)
# Return the character index of first occurrence, or alert error
e.g.
str = "abec"
print(str.index("e"))
# Output: 2
------------------------------------------------------------------------------
inherit syntax:
class BaseClass: # define a base class
……
class DerivedClass (BaseClass): # define a derived class
……
# The derived class inherits all members of the base class.
e.g.
class Computer:
…..
class Desktop(Computer):
……
------------------------------------------------------------------------------
input syntax:
variable = input(“prompt”)
# Users need to input some text by keyboard.
e.g.
age = input("Please input your age: ")
print("Your age is: " + age )
------------------------------------------------------------------------------
insert() syntax:
list.insert(position, element)
# Insert an element to specified position of a list
e.g.
animals = ["ass", "bat", "cow"]
animals.insert(2,"bufflo")
print(animals)
# Output:['ass', 'bat', 'bufflo', 'cow']
------------------------------------------------------------------------------
int() syntax
int(number)
# Convert a floating point number to an integer number
e.g.
print(int(3.14))
# Output: 3
------------------------------------------------------------------------------
intersection() syntax:
set1.intersection(set2)
# Return the same elements both in two sets
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ant", "bee", "cow"}
same = set1.intersection(set2)
print(same)
# Output: {'ant', 'bee'}
------------------------------------------------------------------------------
intersection_update() syntax:
set1.intersection_update(set2)
# Remove the different elements both in two sets
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ant", "bee", "cow"}
set1.intersection_update(set2)
print("Now the set1 is:")
print(set1)
# Output: Now the set1 is: {'ant', 'bee'}
------------------------------------------------------------------------------
is syntax:
a is b
# Chect if two variables are equal
e.g.
a = 'Ruby in 8 Hours'
b = 'Perl in 8 Hours'
print(a is b)
# Output: False
------------------------------------------------------------------------------
isalnum() syntax:
isalnum()
# Return true if all characters are numbers or letters
e.g.
str = "year2018";
s = str.isalnum();
print(s)
# Output: True
------------------------------------------------------------------------------
isalpha() syntax:
isalpha()
# Return true if all characters are letters
e.g.
str = "year2018";
s = str.isalpha();
print(s)
# Output: False
------------------------------------------------------------------------------
isascii() syntax:
isascii()
# Return true if all characters in a string are scii characters
e.g.
str = "Hero007"
s = str.isascii()
print(s)
# Output: True
------------------------------------------------------------------------------
isatty() syntax:
file.isatty()
# Check if the file stream is interactive or connected to a terminal device
e.g.
f = open("myFile.txt", "r")
print(f.isatty())
------------------------------------------------------------------------------
isdecimal() syntax:
isdecimal()
# Return true if all characters are decimal number
# u“number” defines a decimal number
e.g.
str = u"12345678";
s = str.isdecimal();
print(s)
# Output: True
------------------------------------------------------------------------------
isdigit() syntax:
isdigit()
# Return true if all characters are digits
e.g.
str = "123456";
s = str.isdigit();
print(s)
# Output: True
------------------------------------------------------------------------------
isdisjoint() syntax:
set1.isdisjoint(set2)
# Return true if any items in set1 is unrelated with any items in set2. e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ass", "bat", "cow"}
unrelated = set1.isdisjoint(set2)
print(unrelated)
# Output: True
------------------------------------------------------------------------------
isidentifier() syntax:
isidentifier()
# Returns True if the string is a valid identifier
e.g.
str = "100percent"
s = str.isidentifier()
print(s)
# Output: False
------------------------------------------------------------------------------
isinstance() syntax:
isinstance(object, instance)
# Return true if the object is the specified instance
e.g.
print(isinstance(3.14, float))
# Output: True
------------------------------------------------------------------------------
islower() syntax:
islower()
# Return true if all characters are lowercase
e.g.
str = "abcde"
s = str.islower();
print(s)
# Output: True
------------------------------------------------------------------------------
isnumeric() syntax:
isnumeric()
# Return true if the string is numeric.
e.g.
str = "168168"
s = str.isnumeric()
print(s)
# Output: True
------------------------------------------------------------------------------
isprintable() syntax:
isprintable()
# Return true if the string is printable.
e.g.
str = "Scala in 8 Hours!"
s = str.isprintable()
print(s)
# Output: True
------------------------------------------------------------------------------
isspace() syntax:
isspace()
# Return true if the string is only whitespace
e.g.
str = " "
s = str.isspace();
print(s)
# Output: True
------------------------------------------------------------------------------
issubclass() syntax:
issubclass(subclass, class)
# Return true if the one class is another class's subclass
e.g.
class Building:
high = 100
class Room(Building):
high = 5
print(issubclass(Room, Building))
# Output: True
------------------------------------------------------------------------------
issubset() syntax:
set1.issubset(set2)
# Return true if set1 is a sub set of set2
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ant", "bee", "cat", "dog", "ewe"}
ss = set1.issubset(set2)
print(ss)
# Output: True
------------------------------------------------------------------------------
issuperset() syntax:
set1.issuperset(set2)
# Return true if set1 is a supper set of set2
e.g.
set1 = {"ant", "bee", "cat", "dog", "ewe"}
set2 = {"ant", "bee", "cat"}
ss = set1.issuperset(set2)
print(ss)
# Output: True
------------------------------------------------------------------------------
istitle() syntax:
istitle()
# Return true if the string is title-case string
e.g.
str = "We Like Python"
s = str.istitle();
print(s)
# Output: True
------------------------------------------------------------------------------
isupper() syntax:
isupper()
# Return true if all characters are uppercase
e.g.
str = "VERY GOOD"
s = str.isupper();
print(s)
# Output: True
------------------------------------------------------------------------------
items() syntax:
dictionary.items()
# Return the key-value pairs of a dictionary
e.g.
student = {
"name": "Andy",
"id": "0026"
}
print(student.items())
# Output: dict_items([('name', 'Andy'), ('id', '0026')])
------------------------------------------------------------------------------
iter() syntax:
iter()
# Create an iterator object
e.g.
iterator = iter(["ant", "bee", "cat"])
print(next(iterator))
print(next(iterator))
print(next(iterator))
# Output: ant bee cat
# next(iterator) returns one of the items in collection.
------------------------------------------------------------------------------
join() syntax:
separator.join()
# Join the strings by separator
e.g.
separator = "-";
str = ("x", "y", "z");
print(separator.join( str ));
# Output: x-y-z
------------------------------------------------------------------------------
json syntax:
import json
json.dumps(data)
# Encode Python data, return a Json string
e.g.
import json
data = [ { 'a' : 10, 'b' : 20, 'c' : 30, 'd' : 40, 'e' : 50 } ]
jsonString = json.dumps(data)
------------------------------------------------------------------------------
json syntax:
demjson.decode(json)
# Decode Json string, return Python data
e.g.
import json
json = '{"a":10,"b":20,"c":30,"d":40,"e":50}';
data = demjson.decode(json)
------------------------------------------------------------------------------
json syntax:
demjson.encode(data)
# Encode the Python data, return a Json string
e.g.
import json
data = [ { 'a' : 10, 'b' : 20, 'c' : 30, 'd' : 40, 'e' : 50 } ]
jsonString = demjson.encode(data)
------------------------------------------------------------------------------
json syntax:
import json
json.loads
# Decode Json string, return Python data.
e.g.
import json
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
data = json.loads(json)
------------------------------------------------------------------------------
keys() syntax:
dictionary.keys()
# Return all keys of a dictionary
e.g.
student = {
"name": "Andy",
"id": "0026"
}
print(student.keys())
# Output: dict_keys(['name', 'id'])
------------------------------------------------------------------------------
lambda syntax:
lambda arg1 arg2, arg3,… : expression
# Define a lambda, create an anonymous function
e.g.
sum = lambda num1, num2 : num1 + num2
# num1, num2 are parameters.
# num1+ num2 is an expression
------------------------------------------------------------------------------
len() syntax:
len (param)
# Return the length of the param
e.g.
myList = [3, 4, 5]
print(len(myList))
# Output: 3
------------------------------------------------------------------------------
list syntax:
list1 + list2
# Connect two lists
e.g.
lst1 = [0, 1, 2]
lst2 = [3, 4, 5]
print( lst1 + lst2 )
# Output: [0, 1, 2, 3, 4, 5]
------------------------------------------------------------------------------
list syntax:
list = ['string1', 'string2', ‘string3’]
# Create a list
e.g.
mylist = ["a", "b", "c", "d"]
------------------------------------------------------------------------------
list() syntax:
list(param)
# Return a list
e.g.
myList = list("R in 8 Hours")
print(myList)
# Output: ['R', ' ', 'i', 'n', ' ', '8', ' ', 'H', 'o', 'u', 'r', 's']
------------------------------------------------------------------------------
listdir() syntax:
os.listdir(path)
# List anything in the current directory
e.g.
path = "/home/mydir"
print(os.listdir(path))
# Return anything in the current directory
------------------------------------------------------------------------------
ljust() syntax:
ljust(w,f)
# Left adjust string with width w and fill with f
e.g.
str = "This is a left-adjust example:"
print(str.ljust(40, '$'))
# Output: This is a left-adjust example: $$$$$$$$$$$
------------------------------------------------------------------------------
locals() syntax:
locals()
# Returns a dictionary containing the local symbol table
e.g.
print(locals())
# Output: {'__name__': '__main__', '__doc__': None, '__package__': None,
'__loader__',:……}
------------------------------------------------------------------------------
localtime syntax:
import time
local_time = time.asctime( time.localtime(time.time()) )
# Get local time
e.g.
import time
local_time = time.asctime( time.localtime(time.time()) )
print (local_time)
# Output: Sun Oct 17 23:36:28 2020
------------------------------------------------------------------------------
loads syntax:
import json
json.loads
# Decode Json string, return Python data
e.g.
import json
json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
data = json.loads(json)
------------------------------------------------------------------------------
lower() syntax:
lower()
# Convert a string to lower case
e.g.
str = "JQuery in 8 Hours"
print(str.lower())
# Output: jquery in 8 hours
------------------------------------------------------------------------------
lstrip() syntax:
lstrip()
# Remove leading spaces or characters
e.g. print str.lstrip(' ');
str = " This is a lstrip sample! ";
print(str.lstrip( ))
# Output: This is a lstrip sample!
------------------------------------------------------------------------------
main() syntax:
def main ():
function body
# The main( ) function is a default start point of the whole Python program.
e.g.
def main():
print("Very good!")
------------------------------------------------------------------------------
maketran() syntax:
mytable = txt.maketrans(m, n)
print(txt.translate(mytable))
# Create m table by replacing m with n, and use translate() to translate the
table.
e.g.
str = "The num is: 123456789"
m = "123456789"
n = "987654321"
mytable = str.maketrans(m, n)
print(str.translate(mytable))
# Output: The num is: 987654321
------------------------------------------------------------------------------
map() syntax:
list(map(function, param))
# The param is a collection (list, tuple, set, dictionary).
# Call the function and run each items of the colletion, return a new list.
e.g.
def mul(n):
return n*10
p = [1,2,3]
print(list(map(mul, p)))
# Output: [10, 20, 30]
------------------------------------------------------------------------------
match() syntax:
import re
re.match(pattern, string)
# Matche a pattern from the beginning of the string, return an object if true.
Otherwise, return noon.
# span() returns the start index and ending index of the match.
# Note: match() only makes a match from the beginners
e.g.
import re
print(re.match('ray', '[email protected]').span())
# Output: (0, 3)
------------------------------------------------------------------------------
match() syntax:
pattern.match(string)
# Match the pattern with string, return true or false
e.g.
import re
pattern = re.compile("^(\d{3})-(\d{3})-(\d{4})$")
phoneNumber = input("Enter your phone number:")
valid = pattern.match(phoneNumber)
------------------------------------------------------------------------------
math.ceil( ) syntax:
math.ceil( );
# Return an integer that is greater than or equal to its argument.
e.g.
import math
print(math.ceil(9.5))
# Output: 10
------------------------------------------------------------------------------
math.floor( ) syntax:
math.floor( );
# Return an integer that is less than or equal to its argument.
e.g.
import math
print(math.floor(9.5))
# Output: 9
------------------------------------------------------------------------------
math.max( ) syntax:
math.max( );
# Return the greater one between two numbers.
e.g.
print(max(4,2))
# Output: 4
------------------------------------------------------------------------------
math.min( ) syntax:
math.min( );
# Return the less number between two numbers.
e.g.
print(min(4,2))
# Output: 2
------------------------------------------------------------------------------
math.pow( ) syntax:
math.pow( );
# Return the first argument raised to the power of the second argument.
e.g.
import math
print (math.pow(4,2))
# Output: 16.0
------------------------------------------------------------------------------
math.sqrt( ) syntax:
math.sqrt( );
# Return the square root of the argument.
e.g.
import math
print (math.sqrt(4))
# Output: 2.0
------------------------------------------------------------------------------
max() syntax:
math.max( );
# Return the greater one between two numbers.
e.g.
print(max(4,2))
# Output: 4
------------------------------------------------------------------------------
memoryview() syntax:
memoryview(binary)
# Return a memoryview view of a binary object
e.g.
m = memoryview(b"1001")
print(m)
# Output: <memory at 0x7fdaddb7b580>
# b"object" defines a binary object.
------------------------------------------------------------------------------
min() syntax:
math.min( );
# Return the less number between two numbers.
e.g.
print(min(4,2))
# Output: 2
------------------------------------------------------------------------------
mkdir syntax:
os.mkdir("mydir")
# Create a new directory mydir
e.g.
import os
os.mkdir("/tmp/home/mydir”)
# You can use getcwd() to check it.
------------------------------------------------------------------------------
module syntax:
dir(module)
# List all functions in the specified module.
e.g.
import math
print(dir(math))
------------------------------------------------------------------------------
module syntax:
from module import *
# Imports a module to current file.
e.g.
from support import *
myfunction()
# call the function in support module
------------------------------------------------------------------------------
module syntax:
import module
# “import module” imports a module to the current file.
e.g.
import support
support.myfunction()
# “support.function()” calls the functions in the module file.
------------------------------------------------------------------------------
nesting while loop syntax:
while expression:
while expression:
statement(s)
statement(s)
# “while loop” is used to execute blocks of code repeatedly.
# This is a nesting while loop
e.g.
n=2
while(n < 100):
m=2
while(m <= (n/m)):
if not(n%m): break
m=m+1
------------------------------------------------------------------------------
next() syntax:
next(item)
# Returns one item in an iterable collection
e.g.
iterator = iter(["ant", "bee", "cat"])
print(next(iterator))
print(next(iterator))
print(next(iterator))
# Output: ant bee cat
------------------------------------------------------------------------------
None syntax:
None
# Represent a null value
e.g.
v = None
print(v)
# Output: None
------------------------------------------------------------------------------
nonlocal syntax:
nonlocal variable
# Declare a non-local variable in an nested function
# The nonlocal variable does not belong to the inner function.
e.g.
def fun1():
v = "Andy"
def fun2(): # inner function
nonlocal v
v = "Rose" # v does not belong to the inner function
fun2()
return v
print(fun1())
# Output: Rose
------------------------------------------------------------------------------
not syntax:
not operand
# Return true if the operand is false
e.g.
v = False
print(not v)
# Output: True
------------------------------------------------------------------------------
not in syntax:
text not in string
# Check if the text is not in a string
e.g.
str = "Hello World!"
print("Hi" not in str)
# Output: True
------------------------------------------------------------------------------
object creating syntax:
objectName = ClassName(args)
# Create an object
e.g.
tiger = Animal("Tiger", "100")
# tiger is an object
------------------------------------------------------------------------------
object() syntax:
object()
# Create a featureless object.
e.g.
myObj = object()
print(dir(myObj))
# Output: ['__class__', '__delattr__', '__dir__', '__doc__', '__eq__',
'__format__', '__ge__', ……]
------------------------------------------------------------------------------
oct() syntax:
oct(number)
# Convert the number to an octal value
e.g.
print(oct(18))
# Output: 0o22
------------------------------------------------------------------------------
open(“fileName”, “a”) syntax:
open(“fileName”, “a”)
write( “text” )
# Open a file by using “a” mode for appending text
# write( “text” ) writes text to the file
e.g.
f = open("myFile.txt", "a")
f.write(" This is the appended text.")
------------------------------------------------------------------------------
open(“fileName”, “r”) syntax:
open(“fileName”, “r”)
read( )
# Open a file by using “r” mode for reading file
# f.read( ) reads the contents of the file
e.g.
f = open("myFile.txt", "r")
print(f.read())
------------------------------------------------------------------------------
open(“fileName”, “w”) syntax:
open(“fileName”, “w”)
write( “text” )
# Open a file by using “w” mode for writing file
# f.write( “text” ) writes text to the file
e.g.
f = open("myFile.txt", "w")
f.write("I want to write something to the file.")
------------------------------------------------------------------------------
open(filename, “argument”) syntax:
open(filename, “mode”)
# Open a file with a specified mode
e.g.
f = open("tryFile.txt", "w")
# open a file “tryFiel.txt” with “w” mode
------------------------------------------------------------------------------
or syntax:
operand1 or operand2
# Return true if one of the operands is true
e.g.
x = (6<10 or 8>9)
print(x)
# Output: True
------------------------------------------------------------------------------
ord() syntax:
ord('character')
# Return a Unicode code of a specific character.
e.g.
print(ord('A'))
# Output: 65
------------------------------------------------------------------------------
os.chdir(path) syntax:
os.chdir(path)
# Set the path as the current directory
# Change a directory
e.g.
import os
os.chdir("/home/mydir")
# set “mydir” as a current working directory
-----------------------------------------------------------------------------
os.getcwd() syntax:
path = os.getcwd()
# Get current working directory
e.g.
import os
print(os.getcwd())
# return a current working directory
------------------------------------------------------------------------------
os.listdir(path) syntax:
os.listdir(path)
# List anything in the current directory
e.g.
import os
path = "/home/mydir"
print(os.listdir(path))
------------------------------------------------------------------------------
overriding syntax:
class BaseClass
def methodName(): # base method
……
class DerivedClass(BaseClass):
def methodName(): # derived method
……
# When a method name in the derived class is the same as the method name
in base class, it is known as “overriding base method”
e.g.
class Computer:
def capacity(self, harddrive, memory):
……
class Laptop(Computer):
def capacity(self, harddrive, memory):
……
------------------------------------------------------------------------------
parser() syntax:
xml.sax.make_parser( [parser_list] )
# Create a new parser object
e.g.
parser = xml.sax.make_parser()
------------------------------------------------------------------------------
partition() syntax:
str.partition(text)
# Using the parameter 'text' to seperate the string into three parts, return a
tuple: (head, text, tail)
e.g.
str = "Visual Basic in 8 Hours"
s = str.partition("in")
print(s)
# Output: ('Visual Basic ', 'in', ' 8 Hours')
------------------------------------------------------------------------------
pass syntax:
pass
# This is a null operation; it means “do nothing”.
e.g.
if condition:
pass
------------------------------------------------------------------------------
pattern syntax:
re.match(pattern, string)
# Matche a pattern from the beginning of the string, return an object if true.
Otherwise, return noon.
# span() returns the start index and ending index of the match.
# Note: match() only makes a match from the beginners
e.g.
import re
print(re.match('ray', '[email protected]').span())
# Output: (0, 3)
------------------------------------------------------------------------------
pattern.match(string) syntax:
pattern.match(string)
# Match the pattern with string, return true or false
e.g.
pattern = re.compile("^(\d{3})-(\d{3})-(\d{4})$")
phoneNumber = input("Enter your phone number:")
valid = pattern.match(phoneNumber)
------------------------------------------------------------------------------
pop() syntax:
set.pop()
# Remove a random item from the set
e.g.
animals = {"ass", "bat", "cow"}
animals.pop()
print(animals)
# Output: {'ass', 'cow'}
------------------------------------------------------------------------------
pop() syntax:
list.pop(index)
# Remove the element of a list at specified index
e.g.
animals = ["ass", "bat", "cow"]
animals.pop(1)
print(animals)
# Output: ['ass', 'cow']
------------------------------------------------------------------------------
popitem() syntax:
dictionary.popitem()
# Remove the last item of a dictionary
e.g.
student = {
"name": "Andy",
"id": "0026" # this is the last item
}
print("The removed item is:")
print(student.popitem())
# Output: The removed item is: ('id', '0026')
------------------------------------------------------------------------------
pow() syntax:
math.pow( );
# Return the first argument raised to the power of the second argument.
e.g.
import math
print math.pow(4,2)
# Output: 16.0
------------------------------------------------------------------------------
print() format syntax:
print( " %s %d %c %f %h %o" % ('string', digit, ascii, float, hex, oct ))
# Return a formatted string
e.g.
print ("My name is %s and age is %d" % ('Ray', 38))
# Output: My name is Ray and age is 38
------------------------------------------------------------------------------
print() syntax:
print( )
# Print content or string to the screen
e.g.
print("Hello World!")
# Output: Hello World!
------------------------------------------------------------------------------
property() syntax:
property(getProperty, setProperty, delProperty)
# Get property, Set progerty, Delete property
e.g.
def getProperty(self):
return self.property # get property
def setProperty(self, value):
self.Property = value # set property
def delProperty(self):
del self.Property # delete property
property(getProperty, setProperty, delProperty)
------------------------------------------------------------------------------
raise syntax:
raise Exception('message')
# Raise an exception and stop running the program
e.g.
if x = 100/0:
raise Exception("Error! Divided by zero")
# Output: Error message…
------------------------------------------------------------------------------
range syntax:
for var in range(n)
# Generate a sequence from 0 to n-1.
e.g.
for var in range(6):
print(var)
# Output: 0,1,2,3,4,5.
------------------------------------------------------------------------------
range syntax:
for var in range(n1, n2)
# Generates a sequence from n1 to n2-1.
e.g.
for num in range(3,10) :
print(num)
Output: 3,4,5,6,7,8,9.
------------------------------------------------------------------------------
randrange() syntax:
randange(num1, num2)
# Specify a random number from num1 to num2
e.g.
import random
print(random.randrange(0, 8))
------------------------------------------------------------------------------
read() syntax:
fileObj = open(“fileName”, “r”)
fileObj.read( )
# Open a file by using “r” mode for reading file
# read( ) reads the contents of the file
e.g.
f = open("myFile.txt", "r")
print(f.read())
------------------------------------------------------------------------------
readable() syntax:
fileObj.readable()
# Return true if the file is readable
e.g.
f = open("myFile.txt", "r")
print(f.readable())
# Output: True
------------------------------------------------------------------------------
readline() syntax:
fileObj.readline()
# Read one line from the file
e.g.
f = open("myFile.txt", "r")
print(f.readline())
------------------------------------------------------------------------------
readlines() syntax:
fileObje.readlines()
# Read all lines of the file and return a list containing the lines
e.g.
f = open("myFile.txt", "r")
print(f.readlines())
------------------------------------------------------------------------------
reload() syntax:
reload(module_name)
# Reload a module
e.g.
reload(mymodule)
------------------------------------------------------------------------------
remove() syntax:
os.remove("file")
# Remove a file
e.g.
import os
os.remove("myfile.txt")
------------------------------------------------------------------------------
remove() syntax:
collection.remove(element)
# Remove a specified element of a collction
e.g.
animals = ["ass", "bat", "cow"]
animals.remove("bat")
print(animals)
# Output: ['ass', 'cow']
------------------------------------------------------------------------------
rename() syntax:
os.rename( "file1", "file2" )
# Rename a file name file1 as file2
e.g.
import os
os.rename( "file1.txt", "file2.txt" )
# change the file name of file1 as file2
------------------------------------------------------------------------------
repeat symbol syntax:

*
# This symbol is used in regex to repeat a string
e.g.
re*
# matche 0 or more expressions
------------------------------------------------------------------------------
replace() syntax:
replace(old, new)
# Replace old character with new character
e.g.
str = "Python is great!"
s = str.replace("great","very good")
print(s)
# Output: Python is very good
------------------------------------------------------------------------------
repr() syntax:
repr(object)
# Return a printable representation
e.g.
myList = [1, 2, 3, 4, 5]
print(repr(myList))
# Output: [1, 2, 3, 4, 5]
------------------------------------------------------------------------------
return syntax:
return
# Specify a value to be returned to the caller.
e.g.
def multiply ( n, m ) :
return n*m
print(multiply( 2,100 ))
# Output: 200
------------------------------------------------------------------------------
reverse() syntax:
list.reverse()
# Reverse the element's sequence of a list
e.g.
animals = ["ass", "bat", "cow"]
animals.reverse()
print(animals)
# Output: ['cow', 'bat', 'ass']
------------------------------------------------------------------------------
reversed() syntax:
reversed(object)
# Reverse the sequence of an object's elements
e.g.
str = "ABC"
r = reversed(str)
print(list(r))
# Output: ['C', 'B', 'A']
------------------------------------------------------------------------------
rfind() syntax:
rfind(c)
# Same as find(), but find character from right to left
e.g.
s = "JavaScript"
print(s.rfind("a"))
# Output: 3
------------------------------------------------------------------------------
rindex() syntax:
rindex(c)
# Same as index(), but find character from right to left
e.g.
s = "total"
print(s.rindex("t"))
# Output: 2
------------------------------------------------------------------------------
rjust() syntax:
rjust(w,f)
# Right adjust string with width w and fill with f
str = " This is a right-adjust example"
print(str.rjust(40, '$'))
# Output: $$$$$$$$$$$ This is a right-adust example
------------------------------------------------------------------------------
rmdir() syntax:
os.rmdir( "/path/directory" )
# Remove "/path/directory"
e.g.
import os
os.rmdir( "/tmp/mydir" )
------------------------------------------------------------------------------
round() syntax:
round(float, decimal)
# Round a floating number
e.g.
print(round(0.555,2))
# Output: 0.56
------------------------------------------------------------------------------
rpartition() syntax:
str.rpartition("text")
# Search for the last occurrence of the parameter "text", and return a tuple
with three parts: (head, text, tail)
e.g.
str = "JAVA in 8 Hours books in Amazon"
s = str.rpartition("in")
print(s)
# Output: ('JAVA in 8 Hours books', 'in', ' Amazon')
------------------------------------------------------------------------------
rsplit() syntax:
rsplit()
# Separate each word of a string with commas, return a list
e.g.
str = "R in 8 Hours"
s = str.rsplit(" ")
print(s)
# Output: ['R', 'in', '8', 'Hours']
------------------------------------------------------------------------------
rstrip() syntax:
rstrip()
# Remove trailing spaces
e.g.
str = " This is a rstrip sample! "
print(str.rstrip( ))
# Output: This is a rstrip sample!
------------------------------------------------------------------------------
search() syntax:
re.search(pattern, string, flags=0)
# Scan the entire string and return the first successful match
# span() returns the start index and ending index of the match.
e.g.
import re
print(re.search('yahoo', '[email protected]').span())
# Output: (4, 9)
------------------------------------------------------------------------------
seek() syntax:
seek(index)
# Set the pointer to the specified index
e.g.
f = open("myFile.txt", "r+") # use “r+” mode
f.seek(10) # Set the pointer to the index 10
------------------------------------------------------------------------------
seekable() syntax:
fileObj.seekable()
# Return true if the file is seekable. ("seekable" means that the reading
position of the file can be changed.)
e.g.
f = open("myFile.txt", "r")
print(f.seekable())
# Output: True
------------------------------------------------------------------------------
sendmail() syntax:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options,
rcpt_options])
# Send email by using SMTP
e.g.
obj = smtplib.SMTP('localhost')
obj.sendmail(sender, receivers, message.as_string())
# obj.sendmail() sends email
------------------------------------------------------------------------------
separator.join() syntax:
separator.join()
# Join the strings by separator
e.g.
separator = "-";
str = ("x", "y", "z");
print (separator.join( str ))
# Output: x-y-z
------------------------------------------------------------------------------
set environment variable syntax:
set PYTHONPATH=path
# Set environment variable in Unix
e.g.
set PYTHONPATH=/usr/local/lib/python
# Set environment variable in Windows
e.g.
set PYTHONPATH=c:\python30\lib;
------------------------------------------------------------------------------
set syntax:
setName = {“val1”, “val2”, “val3”}
# Define a set, which is unordered, unchangeable, and unindexed
animal = { "ass", "bat", "cow"}
print(animal)
# Output: {'cow', 'ass', 'bat'}
------------------------------------------------------------------------------
set() syntax:
set(collection)
# Return an unsorted set
e.g.
s = set(["ant", "bee", "cat"])
print(s)
# Output: {'cat', 'ant', 'bee'}
------------------------------------------------------------------------------
setattr() syntax:
setattr(Class, object, attribute)
# Set an attribute of an object in a class
e.g.
class Student:
name = "Andy"
setattr(Student, 'score', 100) # set attribute
a = getattr(Student, 'score') # get attribute
print(a)
# Output: 100
------------------------------------------------------------------------------
set-cookie syntax:
set-cookie: name=name; expires=date; path=path; domain=domain;
secure
# HTTP cookies are sent via http headers, it used to pass files. The following
is the syntax of the http header set-cookie
e.g.
Set-Cookie: name="myCookie";expires=Wed, 28 Aug 2020 18:30:00 GMT
------------------------------------------------------------------------------
setdefault() syntax:
dict.setdefault(key, None)
# Return default value "None" if the key is not found in dictionary
e.g.
dict = {'name': 'Andy', 'id': '0026'}
print ("age : %s" % dict.setdefault('age', None))
# Output: age : None
------------------------------------------------------------------------------
single quotes syntax:
str = ‘string’
# Define a string by using a pair of single quotes
e.g.
str = 'I am a string enclosed by a pair of single quotes'
------------------------------------------------------------------------------
slice() syntax:
slice(start, end, step)
# Return a sliced object
e.g.
list = ("a", "b", "c", "d", "e", "f", "g", "h")
items = slice(0, 7, 2)
print(list[items])
# Output: ('a', 'c', 'e', 'g')
------------------------------------------------------------------------------
slicing syntax:
str[index1: index2]
# Return a range of characters from index1 to index2-1
e.g.
myStr = "Shell Scripting in 8 Hours"
print(myStr[ 6 : 12 ]) # Output: Script
e.g.
myStr = "Shell Scripting in 8 Hours"
print(myStr[ -6 : -1 ]) # Output: Hour
# Using negative index starts slice from the end of string
------------------------------------------------------------------------------
smtp syntax:
smtpObj = smtplib.SMTP( [host])
# Create smtp object
e.g.
import smtplib
obj = smtplib.SMTP('localhost')
obj.sendmail(sender, receivers, message.as_string())
# obj.sendmail() sends email
------------------------------------------------------------------------------
smtp.sendmail( ) syntax:
SMTP.sendmail(from_addr, to_addrs, msg[, mail_options,
rcpt_options])
# Send email by using SMTP
e.g.
import smtplib
obj = smtplib.SMTP('localhost')
obj.sendmail(sender, receivers, message.as_string())
# obj.sendmail() sends email
------------------------------------------------------------------------------
socket() syntax:
socket.socket()
# Create a socket object
e.g.
import socket
obj = socket.socket()
------------------------------------------------------------------------------
sort() syntax:
list.sort()
# Sort all elements of a list
e.g.
animals = ["ass","cow","bat", "cat", "ant", "bee"]
animals.sort()
print(animals)
# Output: ['ant', 'ass', 'bat', 'bee', 'cat', 'cow']
------------------------------------------------------------------------------
sorted() syntax:
sorted(list)
# Return a sorted list
e.g.
list = ("f", "e", "h", "c", "a", "g", "d", "b")
sl = sorted(list)
print(sl)
# Output: ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
------------------------------------------------------------------------------
split() syntax:
split(separator)
# Split a string by a separator. (whitespace is a separator by default)
e.g.
str = "Python is a very good language"
print(str.split())
# Output: ['Python', 'is', 'a', 'very', 'good', 'language']
------------------------------------------------------------------------------
splitlines() syntax:
splitlines()
# Separate a string with commas based on the "\n", return a list
e.g.
str = "Html Css\n in 8 Hours\n Book"
s = str.splitlines()
print(s)
# Output: ['Html Css', ' in 8 Hours', ' Book']
------------------------------------------------------------------------------
sqrt() syntax:
math.sqrt( );
# Return the square root of the argument.
e.g.
import math
print(math.sqrt(4))
# Output: 2.0
------------------------------------------------------------------------------
startwith() syntax:
startwith()
# Returns true if the string starts with the specified character
e.g.
str = "Pandas in 8 Hours"
s = str.startswith("Pandas")
print(s)
# Output: True
------------------------------------------------------------------------------
staticmethod() syntax:
staticmethod(Class.method)
# Converts a regular method to a static method
# Static methods are referenced by a class rather than its object.
e.g.
class Calculate:
def add(n1, n2):
return n1 + n2
Calculate.add = staticmethod(Calculate.add)
sum = Calculate.add(100, 68)
print('Sum:', sum)
# Output: Sum: 168
------------------------------------------------------------------------------
str() syntax:
str(number)
# Covert a number to a string
e.g.
print(str(128))
# Output: 128
------------------------------------------------------------------------------
strftime() syntax:
time.strftime(format[, t])
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# Return a formatted date
e.g.
from datetime import datetime
obj = datetime.now()
year = obj.strftime("%Y")
print("year:", year)
# Output: year: 2018
------------------------------------------------------------------------------
str = ‘string’ syntax:
str = ‘string’
# Define a string by using a pair of single quotes
e.g.
str = 'I am a string enclosed by a pair of single quotes'
------------------------------------------------------------------------------
str = "string" syntax:
str = "string"
# Define a string by using a pair of double quotes
e.g.
str = "I am a string enclosed by a pair of double quotes"
------------------------------------------------------------------------------
str = ‘‘‘strings’’’ syntax:
str = ‘‘‘strings’’’
# Define a string by using a pair of triple quotes, triple quotes are used to
display multiple lines of text.
e.g.
multiString = '''I am a string
enclosed by
a pair of triple quotes!'''
------------------------------------------------------------------------------
str.swapcase() syntax:
str.swapcase()
# Swap the letter case of the string
e.g.
str = "jQUERY"
print(str.swapcase())
# Output: Jquery
------------------------------------------------------------------------------
str.zfill(length) syntax:
str.zfill(length)
# Add zeros to the left of the string with length
e.g.
str = "Python"
print(str.zfill(10))
# 0000Python
------------------------------------------------------------------------------
string[index] syntax:
string[index]
# Return a character of the string at the specified index
e.g.
str = "Python"
print(str[2])
# Output: t
------------------------------------------------------------------------------
string[index1: index2] syntax:
string[index1: index2]
# Return characters from index1 to index2-1
e.g.
myString = "Python is a good language"
print(myString[7:16])
# Output: is a good
------------------------------------------------------------------------------
strip() syntax:
strip()
# Remove leading and trailing spaces
e.g.
str = " This is a strip sample! ";
print(str.strip( ))
# Output: This is a strip sample!
------------------------------------------------------------------------------
sub syntax:
re.sub(pattern, replace, string)
# Substitute a match in a string
e.g.
import re
tel = "123-456-7890"
num = re.sub(r'\D', "", tel) # remove "-"
print ("The phone is : ", num)
# Output: The phone is : 1234567890
------------------------------------------------------------------------------
substring syntax:
string[index1: index2]
# Subtract a substring from index1 to index2
e.g.
myString = "Python is a good language"
print(myString[7:16])
# Output: is a good
------------------------------------------------------------------------------
sum() syntax:
sum(collection)
# sum all items of a collection
e.g.
list = (2, 3, 4, 5, 6)
print(sum(list))
# Output: 20
------------------------------------------------------------------------------
supper() syntax:
supper().parent_method
# Return an object that can access the method of parent class
e.g.
class Parent:
def __init__(self, word):
self.greeting = word
def say(self):
print(self.greeting)
class Child(Parent):
def __init__(self, word):
super().__init__(word)
obj = Child("How are you doing!")
obj.say()
# Output: How are you doing!
------------------------------------------------------------------------------
swapcase() syntax:
str.swapcase()
# Swap the letter case of the string
e.g.
str = "jQUERY"
print(str.swapcase())
# Output: Jquery
------------------------------------------------------------------------------
symmetric_difference() syntax:
set1.symmetric_difference(set2)
# Return the different items from both set1 and set2
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ass", "bat", "cat"}
diff = set1.symmetric_difference(set2)
print(diff)
# Output: {'bat', 'ant', 'ass', 'bee'}
------------------------------------------------------------------------------
symmetric_difference_update() syntax:
set1.symmetric_difference_update(set2)
# Remove the same elements in both set1 and set2
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ass", "bat", "cat"}
set1.symmetric_difference_update(set2)
print("Now there are following items in both set1 and set2:")
print(set1)
# Output:
Now there are following items in both set1 and set2:
{'ass', 'bee', 'bat', 'ant'}
------------------------------------------------------------------------------
tell() syntax:
fileObj.tell()
# Return the current position of the file read/write pointer
e.g.
f = open("myFile.txt", "r")
print(f.tell())
# Output: 28
------------------------------------------------------------------------------
thread syntax:
thread.start_new_thread(function, args)
# Create a new thread
e.g.
thread.start_new_thread( func, "myThread" )
# create a new thread
------------------------------------------------------------------------------
time.strftime( ) syntax:
print time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# Return a formatted date
e.g.
from datetime import datetime
obj = datetime.now()
year = obj.strftime("%Y")
print("year:", year)
# Output: year: 2018
------------------------------------------------------------------------------
timestamp syntax:
timestamp = time.time()
# Returns the time in seconds since the Epoch(January 1, 1970)
e.g.
import time
timestamp = time.time()
print ("The timestamp is:", timestamp)
# Output: The timestamp is: 1639573176.0768983
------------------------------------------------------------------------------
translate() syntax:
translate()
# Return a translated string
e.g.
dict = {80: 83} # replaces ascii 80(P) with ascii 83(S)
str = "Hi, Peter!"
print(str.translate(dict))
# Output: Hi, Seter!
------------------------------------------------------------------------------
triple quotes syntax:
str = ‘‘‘strings’’’
# Define a string by using a pair of triple quotes, triple quotes are used to
display multiple lines of text.
e.g.
multiString = '''I am a string
enclosed by
a pair of triple quotes!'''
------------------------------------------------------------------------------
truncate() syntax:
fileObj.truncate(bytes)
# Truncate the file to the specified bytes.
e.g.
f = open("myFile.txt", "a")
f.truncate(28)
# The file only has 28 bytes contents after truncated
------------------------------------------------------------------------------
try - except syntax:
try:
……
except XxxError as message:
……
# “try block” contains the code that may cause an exception.
# “except block” catches the error, and handles the exception.
e.g.
try:
int(100/0)
except ValueError as message:
print("Exception occurs!", message)
------------------------------------------------------------------------------
tuple() syntax:
tuple(collection)
# Return a tuple
e.g.
t = tuple(("ant", "bee", "cat"))
print(t)
# Output: ('ant', 'bee', 'cat')
------------------------------------------------------------------------------
tuple creating syntax:
tupleName = (val1, val2, val3)
# Define a tuple
e.g.
tpl = ("Mon", "Tue", "Wed", "Thu")
------------------------------------------------------------------------------
type() syntax:
type()
# Return the data type of a variable
e.g.
s = "Shell Scripting in 8 Hours"
print(type(s))
# Output: <class 'str'>
------------------------------------------------------------------------------
union() syntax:
set1.union(set2)
# Return a union set from two sets
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ass", "bat", "cow"}
u = set1.union(set2)
print(u)
# Output: {'cow', 'bat', 'ant', 'ass', 'bee', 'cat'}
------------------------------------------------------------------------------
unpack a collection syntax:
collection = ["element1", "element2", "element3"]
var1, var2, var3 = collection
# Extract the collection's values into variables.
e.g.
colors = ["red", "yellow", "green"]
x, y, z = colors
------------------------------------------------------------------------------
update() syntax:
set1.update(set2)
# Add all items from set2 to set1
e.g.
set1 = {"ant", "bee", "cat"}
set2 = {"ass", "bat", "cow"}
set1.update(set2)
print(set1)
# Output: {'bee', 'ant', 'bat', 'ass', 'cat', 'cow'}
------------------------------------------------------------------------------
update() syntax:
dictionary.update(key, value)
# Update a dictionary by adding a key/value pairs
e.g.
Student = {
"name": "Andy",
"id": "0026",
}
Student.update({"score": "100"})
print(Student)
# {'name': 'Andy', 'id': '0026', 'score': '100'}
------------------------------------------------------------------------------
upper() syntax:
upper()
# Convert a string to upper case
e.g.
str = "Hello, World!"
print(str.upper())
# Output: HELLO, WORLD!
------------------------------------------------------------------------------
url syntax:
webbrowser.open(“URL”)
# Open a specified web page
e.g.
import webbrowser
url = "http://www.amazon.com"
webbrowser.open(url)
------------------------------------------------------------------------------
values() syntax:
dictionary.values()
# Return all values of a dictionary
e.g.
Student = {
"name": "Andy",
"id": "0026",
"score":"100"
}
print(Student.values())
# Output: dict_values(['Andy', '0026', '100'])
------------------------------------------------------------------------------
variable assignment syntax:
var1 = var2 =var3 = value
var1, var2, var3 = value1, value2, value3
# Multi variables assignment
e.g.
a = b = c = 100
a, b, c = 'A', 'B', 'C'
------------------------------------------------------------------------------
variable define syntax:
variableName = value
variableName1 = variableName2 = value
variableName1, variableName2 = value1, value2
# Define variable
e.g.
var = 10
var1 = var2 = 20
var1, var2 = 100, 200
------------------------------------------------------------------------------
variable delete syntax:
del myVariable
# Delete a variable
e.g.
del myVar
------------------------------------------------------------------------------
vars() syntax:
vars(object)
# Return the atributes of an object
e.g.
class Example:
def __init__(self, a = 10, b = 20):
self.a = a
self.b = b
obj = Example()
print(vars(obj))
# Output: {'a': 10, 'b': 20}
------------------------------------------------------------------------------
webbrowser syntax:
webbrowser.open(“URL”)
# Open a specified web page
e.g.
import webbrowser
url = "http://www.amazon.com"
webbrowser.open(url)
------------------------------------------------------------------------------
while loop syntax:
while <test-expression> :
<statement>
# “while loop” is used to execute blocks of code repeatedly.
e.g.
while n < 100:
print(n)
------------------------------------------------------------------------------
while loop syntax:
while expression:
while expression:
statement(s)
statement(s)
# “while loop” is used to execute blocks of code repeatedly.
# This is a nesting while loop
e.g.
n=2
while(n < 100):
m=2
while(m <= (n/m)):
if not(n%m): break
m=m+1
------------------------------------------------------------------------------
with syntax:
with statement
# Make it handy to process a file or exception.
e.g.
with open('myFile.txt', 'w') as f:
f.write('Pandas in 8 Hours!')
------------------------------------------------------------------------------
write() syntax:
open(“fileName”, “w”)
fileObj.write( “text” )
# Open a file by using “w” mode for writing file
# write( “text” ) writes text to the file
e.g.
f = open("myFile.txt", "w")
f.write("I want to write something to the file.")
------------------------------------------------------------------------------
writable() syntax:
fileObj.witable()
# Return true if the file is writable
e.g.
f = open("myFile.txt", "w")
print(f.writable())
# Output: True
------------------------------------------------------------------------------
writelines() syntax:
fileObj.writelines(list)
# Write a few lines of content to the file
e.g.
f = open("myFile.txt", "w")
f.writelines(["Hello", "My friends", "Thanks"])
------------------------------------------------------------------------------
xml.sax.make_parser() syntax:
xml.sax.make_parser( [parser_list] )
# Create a new parser object
e.g.
parser = xml.sax.make_parser()
------------------------------------------------------------------------------
yield syntax:
yield variable
# Suspend the current function's execution and sends a geberator back to the
caller.
e.g.
def myGenerator():
n = 100
yield n
------------------------------------------------------------------------------
zfill() syntax:
str.zfill(length)
# Add zeros to the left of the string with length
e.g.
str = "Python"
print(str.zfill(9))
# Output: 000Python
------------------------------------------------------------------------------
zip() syntax:
zip(collection1, collection2, …)
# Returns one tuple composed from some collections
e.g.
a = ("ant", "bee", "cat")
b = ("ass", "bat", "cow")
z=(zip(a, b))
print(tuple(z))
# Output: (('ant', 'ass'), ('bee', 'bat'), ('cat', 'cow'))
------------------------------------------------------------------------------
Appendix

Arithmetic Operator Chart

Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
% Remainder
// Integer Division
** Exponentiation
Assignment Operators Chart

“x += y” equals “x = x + y”, please see the following chart:


Operators Examples: Equivalent:
+= x+=y x=x+y
-= x-=y x=x-y
*= x*=y x=x*y
/= x/=y x=x/y
%= x%=y x=x%y
//= x//=y x=x//y
**= x**=y x=x**y
Comparison Operators Chart

Operators Running
> greater than
< less than
>= greater than or equal
<= less than or equal
== equal
!= not equal
After using comparison operators, the result will be true or false.
Logical Operators Chart

Operators Equivalent
and logical AND
or logical OR
not logical NOT
After using logical operators, the result will be True or False.

Explanation:
True and True True and False False and False
returns true returns False returns False
True or True True or False False or False
returns True returns True returns False
not False not True
returns True returns False
Bitwise Operators

Operator Name Description

& AND return 1 if two bits are 1

| OR return 1 if one of two bits is 1

^ XOR return 1 if both bits are different

~ NOT Inverts 1 to 0 or 0 to1

Bits are shifted to left by number of bits


<< left shift
stipulated by second operand .
Bits are shifted to right by number of bits
>> right shift
stipulated by second operand .
Convert Data Type Chart

Function Operation
int(x) convert x to an integer number
str(x) convert x to a string
chr(x) convert x to a character
float(x) convert x to a floating point number
hex(x) convert x to a hexadecimal string
oct(x) convert x to a an octal string
round(x) round a floating-point number x.
type(x) detect x data type
Math Function Chart

name Description
abs(n) absolute value of n
round(n) round off a floating number n
ceil(n) ceiling of n
floor(n) flooring of n
max(n, m) largest of n and m
min(n, m) smallest of n and m
degrees(n) convert n from radians to degrees
log(n) base e logarithm of n
log(n, m) base m logarithm of n
pow(n, m) n to the power of m
sqrt(n) square root of n
sin(n) sine of n
cos(n) cosine of n
tan(n) tangent of x
List Functions Chart

Function Operation
list.append(n) Append n to the end of list
list.count(n) Count how many n
list.index(n) Return the index of n
list.insert(i,n) Insert n before index i
list.pop(i) Remove & return the item at index i
list.remove(n) Remove the n
list.reverse() Reverse the sequence of list
list.sort() Sort the element of list increasingly
list extend(lst) Append each item of lst to list
Tuple Functions Chart

Function Operation
x in tpl return true if x is in the tuple
len(tpl) return length of the tuple
tpl.count(x) count how many x in tuple
tpl.index(x) return the index of x
Set Functions Chart

Function Operation
set.add(n) Add x to the set
set.update(a, b, c) Add a, b, c to the set
set.copy( ) Copy the set
set.remove(n) Remove the item n
set.pop( ) Remove one random item
set1.intersection(set2) Return items in both sets
set1.difference(set2) Return items in set1 not in set2
Dictionary Functions Chart

Function Operation
d.items( ) return key:value pairs of d
d.keys() return keys of d
d.values() return values of d
d.get(key) return the values with specified key
d.pop(key) remove key and return its value
d.clear() remove all items of d
d.copy() copy all items of d
d.setdefault(k,v) set key:value to d
d1.update(d2) add key:value in d1 to d2
Data Structure Difference Chart

Structures Descriptions
List store multiple changeable values
Tuple store multiple unchangeable values
Set store multiple unique values
Dictionary store multiple key:value pairs

Escape Characters Chart

Characters Description
\\ escape backslash
\’ escape single quote
\” escape double quote
\n new line
\r return
\t tab
Operation Strings Chart

Operator Description
+ concatenate strings together
* repeat a string
[key] return a character of the string
[key1: key2] return characters from key1 to key2-1
in check a character existing in a string
not in check a character not existing in a string
’’’ ’’’ describe a function, class, method…
Testing Functions Chart

Testing Functions return either True or False.


Functions Return True if…
isalpha() return true if all characters are letters
isdigit() return true if all characters are digits
isdecimal() return true if all characters are decimals
isalnum() return true if all characters are numbers or letters
islower() return true if all characters are lowercase
isupper() return true if all characters are uppercase
istitle() return true if the string is title-case string
isspace() return true if the string contains only whitespace
Formatting Functions Chart

Functions Returned String


center(w, f) center string with width w and fill with f
ljust(w,f) left adjust string with width w and fill with f
rjust(w,f) right adjust string with width w and fill with f

Stripping Functions Chart

Functions Returned String


strip() remove leading and trailing spaces
lstrip() remove leading spaces
rstrip() remove trailing spaces
Splitting Functions Chart

Functions Returned String


split a string by a separator. (default
split(separator)
whitespace as a separator)
partition a string with a separator into
partition(separator)
three parts. (head, separator, tail)

Searching Functions Chart

Functions Return
find(c) return the index of first occurrence, or -1
rfind(c) same as find(), but find from right to left
index(c) return the index of first occurrence, or alert error
rindex(c) same as index(), but find from right to left
String Functions (1) Chart

Functions Returned Strings


replace(old, new) replace every old with new
count(ch) count the number of the characters
capitalize() change the first letter to uppercase

String Functions (2) Chart

Functions Returned Strings


separater.join() join the strings by separator
str.swapcase() swap the letter case of the string
str.zfill(length) add zeros to the left of the string with length
Regular Expressions Chart

Operators Matches
^ Matches beginning of the line.
$ Matches end of line.
. Matches any single character.
[...] Matches any single character in brackets.
[^...] Matches any single character not in brackets
? Matches 0 or 1 occurrence
+ Matches 1 or more occurrence
* Matches 0 or more occurrences
{ n} Matches exactly n number of occurrences
{ n, m} Matches at least n and at most m occurrences
a|b Matches either a or b.
(re) Groups regular expressions
Format String Chart

The string output can be formatted as following chart.


Specifier Description
d digital integer
f float
s string
o octal value
x hexadecimal value
e exponential
% “%formatted value” from %original value
Open File’s Mode Chart

The syntax to open a file looks like this:


open(filename, “mode”)

The modes are listed as follows:


modes actions
r open file for reading (default)
w open file for writing
a open file for appending
+ open file for reading & writing
b open file in binary mode
t open file in text mode
Copyright © 2015 by Ray Yao
All Rights Reserved
Neither part of this book nor whole of this book may be reproduced or
transmitted in any form or by any means electronic, photographic or
mechanical, including photocopying, recording, or by any information
storage or retrieval system, without prior written permission from the author.
All rights reserved!
Ray Yao's Team

About the Author: Ray Yao's Team


Certified PHP engineer by Zend, USA
Certified JAVA programmer by Sun, USA
Certified SCWCD developer by Oracle, USA
Certified A+ professional by CompTIA, USA
Certified ASP. NET expert by Microsoft, USA
Certified MCP professional by Microsoft, USA
Certified TECHNOLOGY specialist by Microsoft, USA
Certified NETWORK+ professional by CompTIA, USA
www.amazon.com/author/ray-yao
Recommended Books

"In 8 Hours" Series Books by Ray Yao


Advanced C++ in 8 Hours
Advanced Java in 8 Hours
AngularJs in 8 Hours
Asp.Net in 8 Hours
C# Examples
C# in 8 Hours
C++ Examples
C++ in 8 Hours
Dart in 8 Hours
Data Science in 8 Hours
Django in 8 Hours
Git Github in 8 Hours
Go in 8 Hours
Haskell in 8 Hours
Html Css Examples
Html Css in 8 Hours
Java Examples
Java in 8 Hours
JavaScript Examples
JavaScript in 8 Hours
JQuery Examples
JQuery in 8 Hours
Jsp Servlets in 8 Hours
Kotlin in 8 Hours
Linux Command Line
Linux Examples
Lua in 8 Hours
Machine Learning in 8 Hours
Matlab in 8 Hours
Matplotlib in 8 Hours
MySql in 8 Hours
Node.Js in 8 Hours
Numpy in 8 Hours
Pandas in 8 Hours
Perl in 8 Hours
Php Examples
Php MySql in 8 Hours
PowerShell in 8 Hours
Python Examples
Python in 8 Hours
R in 8 Hours
React.Js in 8 Hours
Ruby in 8 Hours
Rust in 8 Hours
Scala in 8 Hours
Shell Scripting in 8 Hours
Swift in 8 Hours
TypeScript in 8 Hours
Visual Basic Examples
Visual Basic in 8 Hours
Vue.Js in 8 Hours
Xml Json in 8 Hours

You might also like