簡體   English   中英

我如何允許用戶選擇他們想要使用的 def function... 通過使用主要 function

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

我想我應該使用__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)

編寫一個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