简体   繁体   English

我如何允许用户选择他们想要使用的 def function... 通过使用主要 function

[英]How do I allow the user to choose which def function they want to use… by using a main function

I think I am supposed to use __name__='__main__'我想我应该使用__name__='__main__'

def rec(a,b):
    if b == 0:
        return a
    else:
        return rec(b,a%b)

a = int(input("please enter the 1st number_"))
b = int(input("please enter the 2nd number_"))

ans=rec(a,b)
print("The greatest common divisor is:",ans)

#calculating gcd using iteration:
def iter(a, b):
   while(b):
       a, b = b, a % b

   return a

a = int(input("please enter the 1st number_"))
b = int(input("please enter the 2nd number_"))
ans=iter(a,b)
print("gcd is",ans)

Write a main() function that prompts for the choice and uses an if statement.编写一个main() function 提示选择并使用if语句。

def rec(a,b):
    if b == 0:
        return a
    else:
        return rec(b,a%b)

def iter(a, b):
   while(b):
       a, b = b, a % b

   return a

def main():
    while True:
        choice = int(input("Select the GCD function to use: 1. Recursive 2. Iterative:"))
        if choice == 1 or choice == 2:
            break
        print("Please enter 1 or 2")

    a = int(input("please enter the 1st number_"))
    b = int(input("please enter the 2nd number_"))

    if choice == 1:
        ans = rec(a, b)
    elif choice == 2:
        ans = iter(a, b)

    print("The greatest common divisor is:",ans)

if __name__ == '__main__':
    main()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM