Output¶
In [2]:
print(123)
printf syntax¶
In [12]:
print("%s" % ("Hello"))
print("%d , %03d" % (1,1))
print("%f, %.3f " % (0.2,0.2))
print("%e, %E" % (300000000,300000000))
print("%.1e, %.0E" % (300000000,300000000))
Format string syntax¶
In [13]:
print("{x:.2f}" .format(x=64.89999)) #{[name a variable]:[assigns a format]}
Type Conversion¶
In [16]:
a = 1
b = 1.0
c = "c"
print(type(a))
print(type(b))
print(type(c))
In [23]:
print(type( str(a) ))
print(type( int(b) ))
print(round(1.89))
print(int(round(1.45)))
Complex Number¶
In [24]:
u = 24 + 2j
In [26]:
u.real
Out[26]:
In [27]:
u.imag
Out[27]:
In [28]:
u.conjugate()
Out[28]:
Differentiation and Integration¶
In [7]:
# displacement = u*t + 1/2*a*t^2; velocity = u + a*t; acceleration = a
from sympy import *
t,a,u=symbols("t a u") # to make python treat those alphabet as symbolic variables
s = u*t+Rational(1,2)*a*t**2
ds= diff(s,t) #1st deriative
print("v = %s" % (ds))
dds = diff(s,t,t) #2nd derivative
print("a = %s" % (dds))
In [8]:
s_ = integrate(ds, t)
print("s = %s" % (s_))
In [9]:
#insert numbers in symbolic expression
v = lambdify([t,u,a], ds)
v(t=1,u=1,a=9.81)
Out[9]:
Solving Equations¶
In [15]:
from sympy import solve
y,k,x = symbols("y k x")
y = x+1
solve(y,x) # solve for x on x+1=0
Out[15]:
In [16]:
solve(y<3) # solve for x on x+1<3
Out[16]:
In [19]:
#do substitution by expression.subs([term], [variable])
print("x+1 = %s when x = 1" % (y.subs(x, 1)))
Input¶
In [183]:
#Reading Keyboard Input
u = input("enter u=...") # use raw_input() for python 2.x
print("I just received %s" % u)
In [191]:
#assigning object with user input
p = eval(input("type what you what: "))
print(p)
print(type(p))
q = eval(input("type what you what: "))
print(q)
print(type(q))
In [194]:
#Reading user input as part of code
string = input("type you code: ")
exec(string)
In [ ]:
#Reading files
data = open('path/fileName.fileType', 'r') #reading line by line
for line in data:
#operations for data
#or
line = data.readlines()
'''
which is the same as
line = []
for l in data:
line.append(l)
and
line = [l for l in data]
'''
In [ ]:
#Other ways to read a file
#1.
data = open('file.txt', 'r')
for line in data:
#do something
data.close()
#2.
with open('file.txt', 'r') as data:
for line in data:
#do something; no need to close the file
#3.
data = open('file.txt', 'r')
while True:
line = data.readline()
if not line:
break
#do something
In [ ]:
# Writing data to a file
data = open('file.txt', 'w')
data.write("your data")
data.close()
Operations¶
While Loop¶
In [28]:
a = 0
b = 10
while a <= 7 and b != 0:
print("a = %d, b = %d" % (a,b))
a += 1
b -= 1
if a == 7:
b == 0
For Loop¶
In [55]:
whatever = [1,2,3,4,5,6]
for itemsInWhatever in whatever:
print(itemsInWhatever)
In [61]:
listForEx = [0]*3 #create a list with 3 zeros. i.e. [0,0,0]
for i in range(-10, 20, 5): #range(start, stop, step)
listForEx.append(i)
print(listForEx)
String Opeation¶
In [201]:
#splitting a string
string = "1 2 3 4 5"
words = string.split()
print(words)
Error Exception¶
In [202]:
try:
#do something that may have errors. e.g. opening a file
file = open('IAmNotExists.txt','r')
except:
print("It doesn't exist")
In [203]:
#if weren't use exception...
file = open('IAmNotExists.txt','r')
print("It really doesn't exit")
In [207]:
#Exeption for specific errors
try:
#do something
list = [1,2]
print(list[int(input())])
except IndexError:
print("Don't have such value")
except ValueError:
print("Please input number")
print("--------------------------------")
try:
#do something
list = [1,2]
print(list[int(input())])
except IndexError:
print("Don't have such value")
except ValueError:
print("Please input number")
print("--------------------------------")
try:
#do something
list = [1,2]
print(list[int(input())])
except IndexError:
print("Don't have such value")
except ValueError:
print("Please input number")
In [215]:
#Raising Exception
try:
l = [1,2]
a = input()
print(l[int(a)])
except IndexError:
raise IndexError\
("Don't have such value")
if int(a) < 0:
raise ValueError("Don't do that")
In [216]:
#more firendly way
try:
l = [1,2]
a = input()
print(l[int(a)])
except IndexError as e:
print(e)
Data Structures¶
List¶
In [44]:
C = [1,2,3,4,5,6,7] #position: [0,1,2,3,4,and so on]
print(C)
for items in C:
print(items)
In [45]:
#add an element in the end of the list
C.append(8)
C
Out[45]:
In [41]:
#adding two lists
C += [1,2,3] # same as C = C + [1,2,3]
C
Out[41]:
In [46]:
#insert an element by assign a position for it
C.insert(2, 100) #assign 100 to position 2
C
Out[46]:
In [47]:
#delete an element such at position 2
del C[2]
C
Out[47]:
In [48]:
#get the length of the list
len(C)
Out[48]:
In [49]:
#get the index of an element
C.index(7) #element 7 locates at position 6
Out[49]:
In [51]:
#Is 9 in the list?
print(9 in C)
#Is 1 in the list?
print(1 in C)
In [52]:
''' PYTHON ALLOWS NEGATIVE INDEX! '''
#negative index = index starting from the right
C[-1] == C[len(C)-1]
Out[52]:
In [53]:
#nameing elements of the list
a,b,c,d,e,f,g,h = C
print("%d,%d,%d,%d,%d,%d,%d,%d" % (a,b,c,d,e,f,g,h))
In [62]:
#another way to create a list
D = [1+i for i in range(3)]
D
Out[62]:
In [63]:
#operating two lists at the same time
list1 = [1,2,3,4]
list2 = [7,8,9]
for elementFrom1, elementFrom2 in zip(list1, list2):
print("%d, %d" % (elementFrom1, elementFrom2))
In [107]:
#nested list (aka. a table)
'''
1 2 3
4 5 6
'''
R = [1,2,3]
C = [4,5,6]
table1 = [R,C]
for r, c in zip(R,C):
print("%d %d"%(r,c))
print("------------------------------------")
for r in range(0, 3):
for c in range (0, 3):
if c == 2:
print(table1[r-1][c-1], end="\n")
else:
print(table1[r-1][c-1], end="")
In [115]:
table2=[[row, column] for row, column in zip(R, C)]
import pprint
pprint.pprint(table2)
In [143]:
#example
L = []
L.append([1,2,3])
L.append([4])
L.append([5,6,7,8,9])
#method 1
for i in range(len(L)):
for j in range(len(L[i])):
print(L[i][j])
print("-----------------")
#method 2
for l in L:
for LElement in l:
print(LElement)
In [126]:
#reading sublists
P = [0,1,2,3,4,5,6,7,8]
print(P[2:]) #print sublist such start at position 2 to the end of the list
print(P[2:4])#print sublist such start at position 2 and end up with position 4-1 (i.e. position 3)
print(P[:4])#print sublist such start at the begining of the list and end up with position 4-1
print(P[:])#the whole lsit
print(P[1:-2])#allow negative index
Tuples¶
In [149]:
t = (1, 2, 3, "a", "b", "c")
for element in t:
print(element)
In [150]:
#adding tuples
t += (-1,-2)
print(t)
In [220]:
#indexing
print(t[0])
print(t[2:])
Functions¶
In [162]:
#define a function
def function(data):
return "I received "+str(data)
print(function("a apple"))
print(function(100))
In [ ]:
#Global Variable and Local Variable
In [165]:
imAGlobalVariable = 10
def abc():
imALocalVariable = 100
print("I can read global variable %d" % imAGlobalVariable)
abc()
print("I can read global variable %d but I cannot read loval variable in function abc" % (imAGlobalVariable))
In [173]:
f = 0
def plusOne():
f = 1 #this is a 'new' local variable
print("f = %d inside function plusOne" % f)
plusOne()
print("f = %d outside function plusOne" % f)
In [175]:
f = 0
def plusOne():
global f
f = 1 #this is the global variable
print("f = %d inside function plusOne" % f)
plusOne()
print("f = %d outside function plusOne" % f)
In [177]:
#defaulting parameters of function
def summation(input1, input2, input3 = 100):
return input1 + input2 + input3
print(summation(1,2)) #1+2+100
print(summation(1,2,3)) #1+2+3
In [179]:
#Lambda Function
f = lambda x: x+1
'''
which is the same as
def f(x):
return x+1
'''
print(f(1))
Modules¶
In [217]:
#import xxx, where xxx is a module
#e.g.
import math
print(math.factorial(3))
'''
same as
from math import factorial
print(factorial(3))
'''
In [ ]:
#supposed there is a module named "IAmAFile" with functions named "abc" and "efg"
import IAmAFile #import both functions "abc" and "efg"
from IAmAFile import * #import both functions "abc" and "efg"
from IAmAFile import abc #import function "abc"
In [219]:
#Test Block
def f1():
return "I am a function in a module"
if __name__ == "__main__":
#do anything
print("Testing Testing...")
print(f1())
Plotting¶
Vector¶
In [ ]:
Arrays¶
In [236]:
#numberical arrays
import numpy as np
ls = [1,2,3,4,5] # a list
n = np.array(ls) # convert a list to an array
print(n)
zn = np.zeros(3) # create an array with length of three and filled with zeros: [0 0 0]
print(zn)
z = np.linspace(1, 5, 10) # create an array with length of 10 and filled with x in [1,5] (uniformly distributed)
print(z)
Curve Plotting¶
In [269]:
#Matlab-style plotting
import numpy as np
import matplotlib.pyplot as plt
from past.builtins import xrange #for python3
def function(x):
return x**2+1
x = np.linspace(0, 5, 100) # 100 points lay on [0, 5]
y = np.zeros(len(x)) # setting y-axis
for i in xrange(len(x)):
y[i] = function(x[i])
#same as y=function(X)
plt.plot(x, y)
plt.xlabel("x")
plt.ylabel("y")
plt.legend(["x^2+1"])
plt.title("Demo")
plt.axis([0, 5, 0, 50]) #[x min, x max, y min, y max]
plt.savefig("picture.png") #generate PNG
plt.show()
In [284]:
#plotting multiple curves
def function1(x):
return x**2
def function2(x):
return x+1
x = np.linspace(0, 5, 100)
y1 = function1(x)
y2 = function2(x)
plt.plot(x, y1, "r-") # 'r' = red, '-' = line
plt.plot(x, y2, "bo")
plt.show()
In [287]:
#putting multiple plots in one figure
plt.figure()
plt.subplot(1, 2, 1) # (rows, cloumns, row-wise counter)
x = np.linspace(0, 5, 100)
y1 = function1(x)
y2 = function2(x)
plt.plot(x, y1, "r-") # 'r' = red, '-' = line
plt.plot(x, y2, "bo")
plt.subplot(1, 2, 2)
x = np.linspace(0, 5, 100) # 100 points lay on [0, 5]
y = np.zeros(len(x)) # setting y-axis
y = function(x)
plt.plot(x, y)
plt.show()
In [9]:
#Plotting with SciTools and Easyviz
from scitools.std import *
import numpy as np
def f(x):
return x*2+x+2
x = np.linspace(0, 5, 100)
y = f(x)
plot(x,y, '-')
#fine
In [3]:
#Making Animation
Dictionaries¶
In [4]:
#Making Dictionaries
dic = {"tom": 100, "jerry": 200}
print(dic["tom"])
#or
dic2 = dict(Tom=100, Jerry=200)
print(dic2["Jerry"])
print(dic)
In [ ]:
#Operation
Class¶
In [25]:
#define a class
class IamAClass:
def __init__(self, a):#__init__ will be called when writing A = IamAClass(3)
self.a = a
def output(self):
print(self.a)
A = IamAClass(3)
A.output()
print(A.a)
In [31]:
#The Call Special Method
class JustAClass:
def __call__(self, a):
return a+1
In [ ]: