首页 > 解决方案 > 是否可以让用户输入元组以在 python 中输出数据?

问题描述

我正在做一个小型 python 项目,我正在制作一个化学计算器。对于初学者开始制作由所有元素组成的一系列元组,因为元组无法更改。我希望能够输入单个元素和多个元素,但在它的当前形状中,由于某种原因,它似乎只能与多个输入一起使用。我不得不在eval这里结合使用input,以便将输入作为元组拾取,尽管我听说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 我使用 aself.line.text作为我的输入区域,但是在input那里完全崩溃了我的程序(Windows 错误提示)并且只有eval结果TypeError: eval() arg 1 must be a string, bytes or code object但是这是一个由于我首先想弄清楚如何让程序在没有UI 的情况下正常工作,因此目前会在以后发布。这里的任何人都知道如何解决这个问题,或者有一个指向正确方向的指针吗?

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

标签: pythonpython-3.xtuplesuser-inputqlineedit

解决方案


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

不同之处在于 the(2, 3)是一个整数元组,而 the5只是一个整数——而不是 atuple。您的循环期望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]

推荐阅读