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