2009年5月4日 星期一

Define a function and return value

def fun1(a,b):
return abs(a-b)

print(fun1(20,5))
print(fun1(5,30))

結果
15
25

For syntax

定義變數 fruit 為一個 List
fruit=['apple','orange','banana']
for f in fruit:
print(f)

增加一個空白行
print("")

for i in range(10):
print "Eat Fruit"

apple
orange
banana

Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit
Eat Fruit

Defin multiline string with """

string1="""
This world is nice ,
welcome to use python langaue
we will learn to use python to
create function , class and module
"""
print(string1)

結果
This world is nice ,
welcome to use python langaue
we will learn to use python to
create function , class and module

Complex varible real and imag portion

定義complex 變數a
a=2+4j

print("a is "+str(a))

列印 real 及 imag 值
print(a.real)
print(a.imag)

結果
a is (2+4j)
2.0
4.0

Do integer division and get integer result use //

a=8
b=5
print(type(8/5),8/5)
print(type(8//5),8/5)
print(type(8.0/5),(8.0/5))

結果
(type 'int', 1)
(type 'int', 1)
(type 'float', 1.6000000000000001)

Assign values simultaenous

指定變數 x,y,z 均為0
x=y=z=0
print("x now is "+str(x))
print("y now is "+str(y))
print("z now is "+str(z))

定義變數 a,b
a=1
b=2
指定變數值
a,b=b,a

print("a now is "+str(a))
print("b now is "+str(b))

結果
x now is 0
y now is 0
z now is 0
a now is 2
b now is 1

Use python as calculator

定義變數 i 及初始值為4
i=4

加法
i+=4 (or i=i+4)
print("Integer i is "+str(i))

減法
i-=3 (or i=i-3)
print("Integer i is "+str(i))

乘法
i*=3 (or i=i*3)
print("Integer i is "+str(i))

除法
i/=5 (or i=i/5)
print("Integer i is "+str(i))

結果
Integer i is 8
Integer i is 5
Integer i is 15
Integer i is 3

Float to Hexdecimal and Reverse

定義浮點數 f
f=15.75

浮點數 f 轉換成十六進位
fh=f.hex()

反轉 fh 回原來的 f
f=float.fromhex(str(fh))

print("Original f is "+str(f))
print("float f to hexdecimal is :"+str(fh))
print("Reverse f from hexdecimal "+str(f))

結果
Original f is 15.75
float f to hexdecimal is :0x1.f800000000000p+3
Reverse f from hexdecimal 15.75

Integer Conversion Function

定義變數 i 的值
i=100
列印二進位 i 的值
print ("Binary i is "+ str(bin(i)))

列印十六進位 i 的值
print("Hexadecimal i is "+ str(hex(i)))

列印十進位 i 的值
print("Integer i is "+ str(int(i)))

列印八進位 i 的值
print ("Octal i is "+str(oct(i)))

結果
Binary i is 0b1100100
Hexadecimal i is 0x64
Integer i is 100
Octal i is 0144