python的模块代码调用

一、模块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 gcd


print "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 integers
n1 = 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 divisor
enter the first number: 45
enter the second number: 75
the divisor for 45 and 75 is 15

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

import GCDFunction
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)
结果为:
Finishing calculating greatest common divisor
enter the first number: 45
enter the second number: 75
the divisor for 45 and 75 is 15


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

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

from  GCDFunction  import gcd
for 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 divisor
enter the first number: 15
enter the second number: 75
the divisor for 15 and 75 is 15

enter the first number: 16
enter the second number: 48
the divisor for 16 and 48 is 16

enter the first number: 17
enter the second number: 51
the divisor for 17 and 51 is 17

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

import GCDFunction
for 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 divisor
enter the first number: 15
enter the second number: 75
the divisor for 15 and 75 is 15

enter the first number: 16
enter the second number: 48
the divisor for 16 and 48 is 16

enter the first number: 17
enter the second number: 51
the divisor for 17 and 51 is 17




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值