python的模块代码调用

来源:互联网 发布:api python 编辑:程序博客网 时间:2024/06/13 23:39

一、模块GCDFunction.py,用来求两个数的最大公约数

def  gcd(n1,n2):     gcd=1     k=2     while k<=n1 and k<=n2:            if n1%k==0 and n2%k==0:                gcd=k            k+=1     return gcdprint "Finishing calculating greatest common divisor"


二、下面,运用模块GCDFunction.py,实现功能:输入两个整数,求它们的最大公约数

1.  方法1:从模块GCDFunction.py导入函数gcd

from GCDFunction import gcd # Import the module# Prompt the user to enter two integersn1 = eval(input("Enter the first integer: "))n2 = eval(input("Enter the second integer: "))print("The greatest common divisor for", n1,    "and", n2, "is", gcd(n1, n2))

结果为:

Finishing calculating greatest common divisorenter the first number: 45enter the second number: 75the divisor for 45 and 75 is 15

2.  方法2:直接导入模块GCDFunction.py

import GCDFunctionn1 = eval(raw_input("enter the first number: "))n2 = eval(raw_input("enter the second number: "))n1n2gcd = GCDFunction.gcd(n1,n2)print "the divisor for %i and %i is %i" %(n1,n2,n1n2gcd)
结果为:
Finishing calculating greatest common divisorenter the first number: 45enter the second number: 75the divisor for 45 and 75 is 15


三、下面,运用模块GCDFunction.py,实现功能:输入两个整数,求它们的最大公约数,循环做3次

1.  方法1:从模块GCDFunction.py导入函数gcd

from  GCDFunction  import gcdfor i in range(3):    n1 = eval(raw_input("enter the first number: "))    n2 = eval(raw_input("enter the second number: "))    print "the divisor for %i and %i is %i" %(n1,n2,gcd(n1,n2))    print
结果为:

Finishing calculating greatest common divisorenter the first number: 15enter the second number: 75the divisor for 15 and 75 is 15enter the first number: 16enter the second number: 48the divisor for 16 and 48 is 16enter the first number: 17enter the second number: 51the divisor for 17 and 51 is 17

2.  方法2:直接导入模块GCDFunction.py

import GCDFunctionfor i in range(3):    n1 = eval(raw_input("enter the first number: "))    n2 = eval(raw_input("enter the second number: "))    n1n2gcd = GCDFunction.gcd(n1,n2)    print "the divisor for %i and %i is %i" %(n1,n2,n1n2gcd)    print
结果为:

Finishing calculating greatest common divisorenter the first number: 15enter the second number: 75the divisor for 15 and 75 is 15enter the first number: 16enter the second number: 48the divisor for 16 and 48 is 16enter the first number: 17enter the second number: 51the divisor for 17 and 51 is 17