函数定义
def hello():#函数没有大括号,但是结尾必须使用: 冒号。
print 'hello world'
def param_function(param1,param2):#函数的参数没有类型。
print param1,
print param2
def return_function(param1,param2):#带单个返回值的。
return param1 + param2
def return_mul(param1,param2):
sum1 = param1 + param2
mult = param1 * param2
pow1 = param1 ** param2 #** 相当于pow(param1,param2)
return sum1,mult,pow1
#对于有初始值的参数,必须放到最右边。在调用的时候可以为其赋值,也可以不用
def defalt_value(param1,param2,param3=12):
return param1 + param2 + param3
print 'Entry Programming'
hello()
param_function(12,18)
param_function('hello','world')
s = return_function(12,13)
print 's=',s
#对于有多个返回值的函数,可以用多个表量一起来接收。
sum1,mult,pow1 = return_mul(3,5)
print sum1,mult,pow1
#也可以使用一个变量来接收,类似于数组的形式
re = return_mul(3,5)
print re[0],re[1],re[2]
#对于有多个参数的函数,对其进行赋值的时候,不必一定要顺序对应,只要
#使用参数名=值 的形式即可。
sum1 = defalt_value(param2=12,param1=11,param3=22)
print 'sum1=',sum1
If语句
#强制类型转换为int类型
record = int(raw_input("Please input you record : "))
print record
#对于if 分支语句,后面也需要 冒号(:),字符串也可以使用==表示相等。
if record >= 90:
print 'A'
elif record >= 80:
print 'B'
elif record >= 70:
print 'C'
elif record >= 60:
print 'D'
else:
print'No Pass'
#该处的条件只要是非0,均表示True。
if "simadaxia":
print "IsTrue"
else :
print "IsFalse"
#字符串进行比较的时候也是按照ASCll 码表来进行比较的。
# 还可以使用 and or not
if "simadaxia" > "huangdaxia":
print "True Too"
else:
print "False Too"
if "simadaxia" > "huang" and "rui" < "huang":
print "hhh"
while语句
count = 0
#对于while 也可以使用and or not 还有 > < ! ...
while True:
print count,'test'#【,】号相当于Java中的连接符
count = count + 1#python 中没有自增。。
if count == 10:
break
else:
print "else statement"
示例:
import webbrowser as web
import os
import time
count = 0
while count <= 10:
i=0
while i < 3:
web.open_new_tab("http:www.google.com")
i = i + 1
time.sleep(0.8)
else:
os.system("taskkill /F /IM chrome.exe")
count = count + 1
for循环
#得到某一个范围内的数。
flag = range(1,10,2)
for i in flag:
print "count:" ,i
#将字符串转换为单个的字符。
flag2 = list("www.google.com")
for j in flag2:
print j
#遍历文件的内容。并进行复制操作。a+表示添加但是不覆盖原来的内容。
for f in open('for.py','r').readlines():
open('temp.txt','a+').write(f)
else:
print "end of file"
字符串:
s1="sima\ndaxia":输出的时候会对\n进行转义。
若不希望进行转义,使用s1=r"sima\ndaxia"就可以。
字符串格式化:
s1="I am %s,%d years old,money is %.1f"%("sima",21,23.3)
输出的时候:I am sima,21 years old,money is 23.3.类似于C语言的printf函数。
字符串的操作:
取出某一个:s[i].当i是-1,表示最后一个,以此类推。
连接:+."sima" + "ronnie" --> "simaronnie"
"sima " + str(12) + " ronnie"-->"sima 12 ronnie":对于数字的,要进行类型转换才可以进行连接。
重复:*."sima" * 3 ----> "simasimasima"
截取:"www.google.com"[0:3] --->"www":包含头,不包含尾。(s1[:n],s1[2:]从头开始或者到最后结束)
"www.google.com"[8:3:-1]---->"googl",表示从8往3的方向走,所以是减一。
文件操作
#对于open(filename,model),model可以取r,w,a,+,b,model="a+",
#那么若指定的文件不存在的话,会自动创建该文件,而且可读可写。
file_obj = open("temp.txt",'r')
#readline----->String + \n,而且读完一行之后会自动跳转到下一行。
#rstrip:表示去掉读取回来的\n
result = file_obj.readline().rstrip("\n")
print result,"line1"