[英]Python: how can I assign a function to a variable?
I created a data quantity calculator.我创建了一个数据量计算器。 I want, that I input a number and the number is assign to a function.
我想要,我输入一个数字并将该数字分配给一个函数。 For example: inputChose your input 1 and I get the bit calculator.
例如:输入选择你的输入 1,我得到位计算器。 input("Choose your calculator") and then 1 is assign to the bit calculator
input("选择你的计算器") 然后 1 分配给位计算器
#Tebibyte Calculator
def tebi():
x = int(input("Please enter number of tebibytes")))
# y = Bit, z = Byte, a = Kibibytes, b = Mebibytes, c = Gibibytes
y = x * 8,796*10**9
z = x * 1.1*10**12
a = x * 1.1*10**9
b = x * 1,1049*10**9
c = x * 1024
# Output of invoices
print(
x, "Tebibyte :", y, "Bits \n",
x, "Tebibyte :", z, "Byte\n",
x, "Tebibyte :", a, "Kibibyte\n",
x, "Tebibyte :", b, "Mebibyte\n",
x, "Tebibyte :", c, "Gibibytes"
)
input("Please choose your converter\n"
"1 - Input in Bit\n"
"2 - Input in Byte\n"
"3 - Input in Kibibyte\n"
"4 - Input in Mebibyte\n"
"5 - Input in Gibibyte\n"
"6 - Input in Tebibyte\n"
"0 - Exit"
)
6 = tebi()
I believe your goal is to take an input and call a function.我相信您的目标是接受输入并调用函数。 You can do this by modifying your input statement a little and using a dictionary.
您可以通过稍微修改输入语句并使用字典来做到这一点。
Eg例如
# your input is 6 in your example
myInput = input(...)
# dictionary of functions
myFunctions = {6: tebi, 7: someOtherFun}
Essentially then the input acts as a key for the dictionary to obtain the function you want as本质上,然后输入充当字典的键以获得您想要的功能
chosenFunc = myFunctions[myInput]
chosenFunc() # call my function
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.