Python:如何为变量分配功能?

时间:2019-12-01 17:19:17

标签: python python-3.x function variables

我创建了一个数据量计算器。我想要输入一个数字并将数字分配给一个函数。例如:input选择您的输入1,我得到位计算器。输入(“选择您的计算器”),然后将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()

1 个答案:

答案 0 :(得分:0)

我相信您的目标是接受输入并调用函数。您可以通过稍微修改输入语句并使用字典来做到这一点。

例如

# your input is 6 in your example
myInput = input(...)
# dictionary of functions
myFunctions = {6: tebi, 7: someOtherFun}

本质上,输入就是字典的键,以获取您想要的功能

chosenFunc = myFunctions[myInput]
chosenFunc()  # call my function