[英]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.