python例子

例一:for循环

for i in range(1,100):

        if i==23:

            print "great,%s you got your lucky number:" %(i)

            break

        else:

            print 'the number is :',i

 运行:windows下 切换到目录下 Python xunhuan.py

          linux 下      cd到目录下  Python xunhuan.py

例二:阶乘的例子

n=int(input('Enter an integer >=0:'))

fact=1

for i in range(2,n+1):

    fact=fact*i;

print(str(n)+'factorial is'+str(fact))

 例三:while循环

total=0

s=raw_input('Enter a number(or done):')

while s !='done':

    num=int(s)

    total=total+num

    s=raw_input('Enter a number(or done):')

print('The sum is '+str(total))

 例四:九九乘法表

for i in range(1,10):

    for j in range(1,i+1):

        print j, 'x', i, '=', j*i, '\t',

    print '\n'

print 'done'

        

 例五、函数定义

import math

def move(x,y,step,angle=0):

    nx=x+step*math.cos(angle)

    ny=y+step*math.sin(angle)

    return nx,ny

x, y = move(100, 100, 60, math.pi / 6)

print x,y

 例六、可变参数函数

import math

def calc(*numbers):

    sum = 0

    for n in numbers:

        sum = sum + n * n

    return sum

y=calc(1, 2,3,4)

print y

 例七:递归函数

def fact(n):

    if n==1:

        return 1

    return n*fact(n-1)

    

y=fact(5)

print y

 例八:尾递归的递归函数

只返回函数本身

def fact(n):

    return fact_iter(1, 1, n)



def fact_iter(product, count, max):

    if count > max:

        return product

    return fact_iter(product * count, count + 1, max)

    

y=fact(5)

print y

 例九:高阶函数

def add(x, y, f):

    return f(x) + f(y)

print add(-5, 6, abs)

 把函数作为参数传入,这样的函数称为高阶函数,函数式编程就是指这种高度抽象的编程范式。

例十:字典

color={'red':1,'blue':2,'gree':3}

print color['gree']

color['gree']=0

print color

 例十一:一个ping程序

import subprocess



cmd="cmd.exe"

begin=50

end=54

while begin<end:



    p=subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,

                   stdin=subprocess.PIPE,

                   stderr=subprocess.PIPE)

    p.stdin.write("ping 10.10.0."+str(begin)+"\n")



    p.stdin.close()

    p.wait()

    begin=begin+1



    print "execution result: %s"%p.stdout.read()

 例十二:os模块

#!/usr/bin/env python

# -*- coding:gbk -*-

import os  

for fileName in os.listdir ( 'd:\\' ):                

    print fileName

 例十三:创建目录

#!/usr/bin/env python

# -*- coding:gbk -*-

#Python对文件系统的操作是通过os模块实现

import os  

for fileName in os.listdir ( 'd:\\' ):                

    print fileName

print "**************"

os.mkdir("d:\\dgx")

for fileName in os.listdir ( 'd:\\' ):                

    print fileName

 例十四:写入读取的内容到文件

#!/usr/bin/env python

import os

ls=os.linesep

while True:

    fname = raw_input('Enter file name: ')

    if os.path.exists(fname):

        print "Error:%s already exists " 

    else:

        break

all = []



print "\nEnter lines('.'by itself to quit)"



while True:

    entry=raw_input('>')

    if entry =='.':

        break

    else:

        all.append(entry)



fobj=open(fname,'w')

fobj.write('\n'.join(all))

fobj.close()

print 'Done'

        

例十五:读取文件内容

#!/usr/bin/env python



fname=raw_input('Enter filename:')





try:

    fobj=open(fname,'r')

except IOError,e:

    print "*******file open error:",e

else:

    for eachLine in fobj:

        print eachLine,

    fobj.close()

 例十六:第一个main

#-*-coding:utf-8-*-

import sys

def Main():  

    sys.stdout.write("开始程序\n")

    str1='i am "python"\n'

    str2="i am 'python'\r"

    str3="""

            i'm "python",

            <a href="http://www.sina.com.cn"></a>

            """

    print str1,str2,str3

if  __name__ == '__main__':

    Main()







    

               

 例十七:函数的默认参数与返回值

#-*-coding:utf-8-*-

import sys

def arithmetic(x=1,y=1,operator="+"):

    result={

        "+":x+y,

        "-":x-y,

        "*":x*y,

        "/":x/y         

    }

    return result.get(operator)

if __name__=="__main__":

    print arithmetic(1, 2)

    print arithmetic(1, 2, "/")

 

你可能感兴趣的:(python)