简体   繁体   中英

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__'

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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