如何将用户输入作为功能输入

时间:2018-10-27 04:03:20

标签: python python-3.x

我试图让我的函数从用户那里获得一个名称,该用户将在执行一个函数时检查该名称是否在白名单中,该函数从具有相同名称的预定义列表中提取信息,但是输入的内容是由函数而不是列表名称作为字符串处理。如何获取输入内容作为列表名称?

hydrogen = ["Hydrogen", "H", "1", "1.0"]
helium = ["Helium", "He", "2", "4.0"]

universe = ["hydrogen", "helium"]

elementname_print = "Element Name: "
elementsymbol_print = "Element Symbol: "
atomicnumber_print = "Atomic Number: "
relativeatomicmass_print = "Relative Atomic Mass: "

def printelement(element):
  print(f" \n-------------------------")
  print(elementname_print + element[0])
  print(elementsymbol_print + element[1])
  print(atomicnumber_print + element[2])
  print(relativeatomicmass_print + element[3])
  print("-------------------------")

userinput = input("-->")
if userinput in universe:
  printelement(userinput)
else:
  print("Sorry that element cannot be found.")

结果:

->氢

元素名称:h

元素符号:y

原子数:d

相对原子质量:r

3 个答案:

答案 0 :(得分:3)

您不应在全局范围内将元素定义为hydrogen = ...,而应在以它们的名称为键的字典中定义它们。

elements = {"hydrogen": ["Hydrogen", "H", "1", "1.0"],
            "helium": ["Helium", "He", "2", "4.0"]}

查找变得容易得多。

def print_element(element_name):
    element = elements[element_name]
    # the rest as written

请注意,您可以清理代码很多:

elements = {"hydrogen": ["Hydrogen", "H", "1", "1.0"],
            "helium": ["Helium", "He", "2", "4.0"]}

def print_element(element_name):
    element = elements[element_name]
    name, symbol, number, mass = element

    print(f"""
----------------------
Element Name:         {name}
Element Symbol:       {symbol}
Atomic Number:        {number}
Relative Atomic Mass: {mass}
----------------------""")

userinput = input("-->")
if userinput in elements:
    print_element(userinput)
else:
    print("Sorry that element cannot be found.")

有多种方法可以使您选择的解决方案正常工作(eval可以做到,但是会带来巨大的安全风险。globals()可以做到,但是会带来很大的性能开销),但是它们都是丑陋。从客观上讲,编写丑陋的hack比首先使用正确的方法更糟糕

答案 1 :(得分:0)

您可以评估输入到相应变量的字符串:

printelement(eval(userinput))

其余代码保持不变。

P.S:这是一个快速的技巧,使用eval是不安全的。

答案 2 :(得分:0)

基本上,您需要获取与用户输入相对应的列表。使用globals()

  lst = globals()[userinput]

因此,在您的示例中,如果用户输入'hydrogen',则将提供列表hydrogen。现在开始打印。

完整示例

hydrogen = ["Hydrogen", "H", "1", "1.0"]
helium = ["Helium", "He", "2", "4.0"]
universe = ["hydrogen", "helium"]

elementname_print = "Element Name: "
elementsymbol_print = "Element Symbol: "
atomicnumber_print = "Atomic Number: "
relativeatomicmass_print = "Relative Atomic Mass: "

def printelement(element):
  print(f" \n-------------------------")
  print(elementname_print + element[0])
  print(elementsymbol_print + element[1])
  print(atomicnumber_print + element[2])
  print(relativeatomicmass_print + element[3])
  print("-------------------------")

userinput = input("-->")
if userinput in universe:
  lst = globals()[userinput]
  printelement(lst)
else:
  print("Sorry that element cannot be found.")