introduction
Python is a interpreting script language, which is very popular these years. This post will summarize some fundamentals of this language.I installed python(x,y) as my python environment. To run a python script, type in “python xx.py”, or run it in IDE, just same as running matlab script in matlab IDE.
fundamental syntax:
http://wiki.woodpecker.org.cn/moin/PyAbsolutelyZipManual
import (same as Java)
string <=> int
str(i)
string.atoi(s,[,base]) #convert to int, base is the base of the number, 10, 16, or 8
string.atof(s) #convert to float
change dir:
import os
chdir(strDir)
statement (loop/if/else)
if x<0:
x++ # note that all code-block structure is defined by indent
else:
x–
no end
for i in range(10,0,-3): # range(10,0,-3) means 10:-3:0, while 0 is excludedprint “the output num is %d”%(i)
read/write file:
http://www.cnblogs.com/allenblogs/archive/2010/09/13/1824842.html
fid = open(“xx.txt”,”r”)
line = fid.readline()
fid.close()
fid = open(“xx.txt”,”w+”)
fid.write(line) # automatically return to a new line
fid.close()
List if mutable, while tuple is immutable.
How to check the structure of a variable?
You can call type(var) to know the type of the variable. Then dir() and getattr() to check the structure.
List comprehensions
x = list([0 1 2 3 4 5])
y = [x_i for x_i in x]
y = [x_i+1 for x_i in x if x>1]
y = [x_i+1 if x_i%2==0 else x_i for x_i in x if x>1]
how to sum up a list?
sum(x)
pandas DataFrame
Written with StackEdit.