[英]I'm trying to make a bmi calculator in python and I don't know what I'm doing wrong
[英]I'm trying to make a basic calculator in python. I'm including an index of functions
我還應該注意我使用的是 python 3.6。
funcs = [add,sub,mult,div,power]
以上是功能索引。
chosenfunc = chooseFunc()
for i in funcs:
if i == chosenfunc:
i(x,y)
以上就是我嘗試訪問它的方式。 所以它基本上運行add()
。 如果相關,我的 add 函數寫為:
def add(x,y):
print(f"Result of {x} + {y}: {(float(x)) + (float(y))}")
我如何讓它運行我的功能? 它目前沒有做任何事情。
import fractions
funcs = [add,sub,mult,div,power]
def chooseFunc():
return input("Choose a function from between Add, Subtract, Multiply, Divide, power: ")
def numtofloat(num):
return float(num)
def add(x,y):
print(f"Result of {x} + {y}: {(numtofloat(x)) + (numtofloat(y))}")
def sub(x,y):
print(f"Result of {x} - {y}: {(numtofloat(x)) - (numtofloat(y))}")
def mult(x,y):
print(f"Result of {x} * {y}: {(numtofloat(x)) * (numtofloat(y))}")
def div(x,y):
print(f"Result of {x} / {y}: {(numtofloat(x)) / (numtofloat(y))}")
def power(x,y):
print(f"Result of {x} ^ {y}: {(numtofloat(x)) ^ (numtofloat(y))}")
chosenfunc = chooseFunc()
for i in funcs:
if i == chosenfunc:
i()
編輯以添加完整代碼。
這是您可以這樣做的方法...
def add(x, y):
print(x + y)
funcs = [add, ]
def chooseFunc():
# take input here for function by index or something
return 0
chosenfunc = chooseFunc()
for i in range(len(funcs)):
if i == chosenfunc:
funcs[i](2, 3)
編輯:問題已更改:)
import fractions
def numtofloat(num):
return float(num)
def add(x, y):
print(f"Result of {x} + {y}: {(numtofloat(x)) + (numtofloat(y))}")
def sub(x, y):
print(f"Result of {x} - {y}: {(numtofloat(x)) - (numtofloat(y))}")
def mult(x, y):
print(f"Result of {x} * {y}: {(numtofloat(x)) * (numtofloat(y))}")
def div(x, y):
print(f"Result of {x} / {y}: {(numtofloat(x)) / (numtofloat(y))}")
def power(x, y):
print(f"Result of {x} ^ {y}: {(numtofloat(x)) ^ (numtofloat(y))}")
funcs = {"add": add, "sub": sub, "mult": mult, "div": div, "power": power}
def chooseFunc():
return input("Choose a function from between add, sub, mult, div, power: ")
x, y = 2, 3
chosenfunc = chooseFunc()
for i in funcs.keys():
if i == chosenfunc:
funcs[i](x, y)
添加 x, y 以使用 dict 傳遞給函數以保持函數映射,還在映射之前移動函數 def
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.