python - 是否可以让用户输入元组以在 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 的情况下正常工作,因此目前会在以后发布。这里的任何人都知道如何解决这个问题,或者有一个指向正确方向的指针吗?
考虑到这是我的第一个“真正”项目,所有帮助都非常感谢!
解决方案
- 如果用户键入
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(",")]
为了检查一些输出,我在python
repl(控制台)中运行了这个:
# 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]
推荐阅读
- nginx - 找不到包 kaltura-nginx
- sql - 我想从字符串中提取卖家 ID 和商家 ID
- powerbi - 模型运行日期的 DateTime 或整数
- python - 如何使用 Django 将搜索查询结果保存到模型中?
- laravel - 如何使用静态值从表中搜索值
- lua - Lua 中的表达式和语句到底是什么?
- typescript - 我正在尝试在 Angular 9/10 中使用输入标签文件类型重置选定的文件,我用谷歌搜索并找到了解决方案,但它不起作用
- javascript - 如何在 cypress 中链接 cy.get
- python - 通过 Python 命令和 dbutils 在 Databricks 上安装 Maven 库
- c++ - 如何在我的安装程序中包含 .NET Core(Windows 和 macOS)