有没有可能让用户在python中为数据输出输入元组?

2024-05-16 18:31:48 发布

您现在位置: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的情况下正常工作。 这里有人知道怎么解决这个问题,或者有人给我指明了正确的方向吗

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


Tags: ofthein元素inputisevalelements
1条回答
网友
1楼 · 发布于 2024-05-16 18:31:48
  • 如果用户键入2, 3eval('2, 3')解析为(2, 3)
  • 如果用户键入5eval('5')解析为5

区别在于(2, 3)是整数的元组,而5只是一个整数–不是tuple。循环期望mollmass是某种类型的iterable,但是当它是一个int值时,它会引发一个TypeError

相反,您可以使mollmass始终解析为iterable,并在过程中除去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]

相关问题 更多 >