【问题标题】:How to change this data input type in python? [duplicate]如何在python中更改此数据输入类型? [复制]
【发布时间】:2016-05-17 15:18:24
【问题描述】:

我的程序中有这条线-

num = int(input("Enter a number: "))

现在输入类型是 int,我不能使用任何指数。如何将数据输入类型从 int 更改为其他类型,以便可以输入像 2**4 (= 2^4) 这样的指数?

【问题讨论】:

  • 您需要一个能够理解此类输入的解析器。你想接受什么输入?
  • 您可以将输入作为字符串,然后根据需要进行拆分
  • 如果您只想接受两个数字的幂的表达式,您可以在** 上拆分输入。

标签: python python-3.x


【解决方案1】:

不要使用 int() :)

>>> x = input("Enter a number:")
Enter a number:2**3
>>> print x
8

可以通过文档解释(https://docs.python.org/2/library/functions.html#input):

input([prompt]) 

相当于eval(raw_input(prompt))

此函数不会捕获用户错误。如果输入在语法上无效,则会引发 SyntaxError。 Other exceptions may be raised if there is an error during evaluation.

...

考虑将 raw_input() 函数用于用户的一般输入。

python3 中发生了一些变化,因此以下替代方案将起作用:

x = eval(input("Enter a value"))
print(x) 

【讨论】:

  • 当然。这就是输入的工作原理。可能你想过 raw_input()?
  • 请注意,这在 Python 3 中发生了变化。
【解决方案2】:

您总是可以接受一个字符串,然后按您选择的分隔符拆分,^ 或 **。

如果我没记错的话,eval 是不安全的,不应该使用(如果我错了,请纠正我)。

【讨论】:

猜你喜欢
  • 2016-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-27
  • 1970-01-01
  • 2021-10-30
  • 1970-01-01
相关资源
最近更新 更多