是否可以让用户输入元组以在 Python 中输出数据?



我正在做一个小型的python项目,在那里我正在制作一个化学计算器。 首先,开始制作由所有元素组成的一系列元组,因为元组无法更改。 我希望能够输入单数和多个元素,但由于某种原因,在当前的形状中,它似乎只能使用多个输入。我不得不在这里将evalinput结合使用,以便将输入作为元组拾取,尽管我听说eval通常被认为是不好的做法,因为它允许用户输入所有类型的输入,甚至是有害的输入

#snippet of element list data in order of name, electrons and atomic weight, hydrogen and oxygen are use in examples.
Hydrogen = ("Hydrogen" , 1 , 1.008)
Helium = ("Helium" , 2 , 4.003)
Lithium = ("Lithium", 2 , 6.941)
Beryllium = ("Berylium" , 4 , 9.0122)
Boron = ("Boron" , 5 , 10.811)
mollmass = eval(input( "Enter atoms in the molecule: ")) #input needs a comma (,) or plus sign(+) to work
#outputs every element entered, can't multiply values, recurring elements need to be enterd multiple times
for elements in mollmass:
print(f"atomic weight of the element", elements[0] , "is", elements[2]) 
elemental_sum  = 0
#calculates total weight of the molecule
for atomic_weight in mollmass:
elemental_sum = elemental_sum + atomic_weight[2]
print("The mollmass of this molecule is", elemental_sum)

其输出为

atomic weight of the element Hydrogen is 1.008
atomic weight of the element Oxygen is 15.999
The mollmass of this molecule is 17.007

但是当我只输入一个元素时,我得到:

TypeError: 'int' object is not subscriptable

一旦我开始添加一些基本的 UI 元素,情况就会变得更糟,因为我正在使用 QlineEdit,我为我的输入区域使用了一个self.line.text,但是在那里input会彻底崩溃我的程序(Windows 错误提示(,并且只有eval结果TypeError: eval() arg 1 must be a string, bytes or code object但是这是目前以后的问题,因为我首先想弄清楚如何在没有 UI 的情况下让程序正常工作。 这里有人知道如何解决这个问题,或者有指向我正确方向的指针吗?

考虑到这是我的第一个"真正的"项目,所有的帮助都非常感谢!

  • 如果用户键入2, 3,则eval('2, 3')解析为(2, 3)
  • 如果用户键入5,则eval('5')解析为5

不同之处在于(2, 3)是整数元组,而5只是一个整数 -而不是tuple。您循环期望mollmass是某种可迭代的,但是当它是单个int值时,它会引发TypeError

相反,您可以使mollmass始终解析为可迭代,并在此过程中摆脱eval

raw_mollmass = input("Enter atoms in the molecule: ")
mollmass = [int(x) for x in raw_mollmass.split(",")]

为了检查一些输出,我在pythonrepl(控制台(中运行了这个:

# Testing to see if this works
def get_mollmass_input():
raw_mollmass = input("Enter atoms in the molecule: ")
mollmass = [int(x) for x in raw_mollmass.split(",")]
return mollmass
>>> get_mollmass_input()
Enter atoms in the molecule: 5, 4, 3, 2, 1
[5, 4, 3, 2, 1]
>>> get_mollmass_input()
Enter atoms in the molecule: 3
[3]

最新更新