Python 3 中的输入变量
对于涉及化学元素的任务,是否可以让用户输入等于变量。
例如,碳的分子量为12,但我不希望用户输入12,他们应该输入“C”。但当输入将其转换为字符串时,不可能将其与变量 C = 12 相匹配。
有什么方法可以输入变量而不是字符串吗?
如果没有,我可以将字符串设置为变量吗?
示例:
C = 12
element = input('element symbol:')
multiplier = input('how many?')
print(element*multiplier)
这只是返回一个错误,指出您不能乘以字符串。
Is it possible to have a user input equal to a variable for tasks that involve chemical elements.
For example, Carbon has the molecular mass 12, but i do not want the use to input 12, They should input 'C'. but as the input turns this into a string, it is not possible to lik this to the variable C = 12.
Is there any way to input a variable istead of a string?
If not, could i set a string as a variable.
example:
C = 12
element = input('element symbol:')
multiplier = input('how many?')
print(element*multiplier)
This just returns an error stating that you can't multiply by a string.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
element = eval(input("element symbol: "))
是最简单的,但不一定是最安全的。另外,您的符号需要位于本地范围内,
您可能更喜欢有一个字典对象
element = eval(input("element symbol: "))
would be the simplest, but not necessarily the safest. Plus, your symbol needs to be in the local scope
you might prefer to have a dictionary object
您可以像这样更改您的代码:
You could change your code like this:
Python 3.x 中的
input
是等效的到Python 2.x中的raw_input
,即它返回一个字符串。要像 Python 2.x 的
input
一样计算该表达式,使用eval
,如 文档所示从 2.x 更改为 3.0。但是,
eval
允许执行任何 Python 代码,因此这可能非常危险(而且速度很慢)。大多数时候,您不需要eval
的强大功能,包括这一点。由于您只是获得一个全局符号,因此您可以使用 globals() 字典,并将字符串转换为整数,请使用int
函数。但是当无论如何都需要字典时,为什么不重构程序并将所有内容存储在字典中呢?
input
in Python 3.x is equivalent toraw_input
in Python 2.x, i.e. it returns a string.To evaluate that expression like Python 2.x's
input
, useeval
, as shown in the doc for changes from 2.x to 3.0.However,
eval
allows execution of any Python code, so this could be very dangerous (and slow). Most of the time you don't need the power ofeval
, including this. Since you are just getting a global symbol, you could use theglobals()
dictionary, and to convert a string into an integer, use theint
function.but when a dictionary is needed anyway, why not restructure the program and store everything in a dictionary?
由于输入总是返回字符串类型。不允许与字符串相乘。
因此,在获取
input
后,如果在 python 中使用int
类型,则需要键入强制转换。试试这个:
Since input always return string type. Multiplication to the string is not allowed.
So after taking the
input
, you need to type cast if usingint
type in python .Try this: