用户打开/关闭功能

时间:2018-10-02 23:37:27

标签: python python-3.x function user-interface optional

我有一个使用某些功能的代码:

def 1(...):
    return ....

def 2(...):
    return ....

def 3(...):
    return ....

在程序结尾,我们有一个方程式,其中使用了上述函数。我们如何为用户提供类似于以下内容的选项,以选择应使用的功能?

我想要这样的东西

#for using a function write T and for stopping its usage write F
Use 1 = F
Use 2 = T
Use 3 = T

因此功能1被关闭,功能2和3被打开并在代码中使用。

非常感谢您。

2 个答案:

答案 0 :(得分:2)

您可以使用词典并允许用户选择功能

def vash(x):
    return x + 1
def the(x):
    return x * 2
def stampede(x):
    return pow(x, 3)

d = {'vash': vash, 'the': the, 'stampede': stampede}     
x = 2

print('Which functions to turn on: \n\tvash: add 1 \n\tthe: double, \n\tstampede: raise to 3rd power')
on = []
while True:
    choice = input('Enter function to turn on ("exit" when finished): ')
    if choice == 'exit':
        break
    if choice not in d.keys():
        print('Not a valid function.')
        continue
    on.append(choice)

for i in on:
    x = d[i](x)
    print(x)
Which functions to turn on: 
  vash: add 1 
  the: double, 
  stampede: raise to 3rd power
Enter function to turn on ("exit" when finished): vash
Enter function to turn on ("exit" when finished): blah
Not a valid function.
Enter function to turn on ("exit" when finished): the
Enter function to turn on ("exit" when finished): exit
3
6

答案 1 :(得分:1)

首先,您需要使用input()从用户那里获得每个函数的答案 然后,您需要为每个函数使用布尔值,以允许或禁止使用该函数:

我认为您正在寻找类似的东西:

def function1():
   return 2
def function2():
   return 4
def function3():
   return 6  
use_1 = input("Type T to use 1 ")
use_2 = input("Type T to use 2 ")
use_3 = input("Type T to use 3 ")
x=(use_1=='T')*function1()+(use_2=='T')*function2()+(use_3=='T')*function3()
print(x)
相关问题