(最近由于IDA Pro中需要使用脚本,而自带的IDC貌似不怎么好用,所以就学习了下Python的基本语法。)
一、经典程序Hello world
print "Hello world!" raw_input("P...By betabin.");
二、中文编码使用
# -*- coding:GBK -*- print "你好,中国" raw_input("Press enter key to close this window...");
三、List数据结构
word="abcdefg" a=word[2] print "a is: "+a b=word[1:3] print "b is: "+b # index 1 and 2 elements of word. c=word[:2] print "c is: "+c # index 0 and 1 elements of word. d=word[0:] print "d is: "+d # All elements of word. e=word[:2]+word[2:] print "e is: "+e # All elements of word. f=word[-1] print "f is: "+f # The last elements of word. g=word[-4:-2] print "g is: "+g # index 3 and 4 elements of word. h=word[-2:] print "h is: "+h # The last two elements. i=word[:-2] print "i is: "+i # Everything except the last two characters l=len(word) print "Length of word is: "+ str(l)
四、条件语句
# Multi-way decision x=int(raw_input("Please enter an integer:")) if x<0: x=0 print "Negative changed to zero" elif x==0: print "Zero" else: print "More"
五、循环语句
# Loops List a = ['beta', 'bin', 'betabin'] for x in a: print x, len(x)
六、函数定义
# Define and invoke function. def sum(a,b): return a+b func = sum r = func(5,6) print r # Defines function with default argument def add(a,b=2): return a+b r=add(1) print r r=add(1,5) print r
七、文件I/O
spath="D:/WorkSpace/Python/t.txt" f=open(spath,"w") # Opens file for writing.Creates this file doesn't exist. f.write("First line 1.\n") f.writelines("First line 2.") f.close() f=open(spath,"r") # Opens file for reading for line in f: print line f.close()
八、异常处理
s=raw_input("Input your age:") if s =="": raise Exception("Input must no be empty.") try: i=int(s) except ValueError: print "Could not convert data to an integer." except: print "Unknown exception!" else: # It is useful for code that must be executed if the try clause does not raise an exception print "You are %d" % i," years old" finally: # Clean up action print "Goodbye!"
九、类与继承
class Base: def __init__(self): self.data = [] self.x = 23 def add(self, x): self.data.append(x) def addtwice(self, x): self.add(x) self.add(x) #Child extends Base class Child(Base): def plus(self, a, b): return a + b + self.x oChild = Child() oChild.add("str1") print oChild.data print oChild.x print oChild.plus(2, 3)
十、包
# apacket.py def add_func(a, b): return a + b
# bpacket.py from apacket import add_func # Also can be: import apacket print "Import function:" print add_func(1,2) # If using "import apacket", then here should be "apacket.add_func"