我想将两个变量相乘。它们是原始输入,但它总是给我那个错误。
no1 = raw_input('Your first number')
no2 = raw_input('Your second number')
answer = no1 * no2
我想将两个变量相乘。它们是原始输入,但它总是给我那个错误。
no1 = raw_input('Your first number')
no2 = raw_input('Your second number')
answer = no1 * no2
raw_input
返回一个字符串,首先将它们转换为整数或浮点数以执行数字运算。
no1 = float(raw_input('Your first number'))
no2 = float(raw_input('Your second number'))
在 py2.x 上,您还可以使用input
if which 会自动将输入字符串转换为数字。但如果输入源未知,则不安全。
帮助raw_input
:
>>> print raw_input.__doc__
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
帮助input
:
>>> print input.__doc__
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
您正在尝试将 2 个字符串相乘,因此您需要通过在结果上调用float
函数将它们手动转换为浮点数。raw_input
在 python 2 中,您也可以使用input
函数代替raw_input
- 它会自动执行。
警告- 这个函数是完全不安全的 - 它将输入字符串作为 python 代码执行(与eval
函数相同)。除非您信任用户,否则不要使用它