Python 如何将输入读取为数字?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20449427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I read inputs as numbers?
提问by
Why are xand ystrings instead of ints in the below code?
为什么在下面的代码中是x和y字符串而不是整数?
(Note: in Python 2.x use raw_input(). In Python 3.x use input(). raw_input()was renamed to input()in Python 3.x)
(注意:在 Python 2.x 中使用raw_input(). 在 Python 3.x 中使用input().在 Python 3.xraw_input()中重命名为input())
play = True
while play:
x = input("Enter a number: ")
y = input("Enter a number: ")
print(x + y)
print(x - y)
print(x * y)
print(x / y)
print(x % y)
if input("Play again? ") == "no":
play = False
采纳答案by thefourtheye
TLDR
TLDR
- Python 3 doesn't evaluate the data received with
inputfunction, but Python 2'sinputfunction does (read the next section to understand the implication). - Python 2's equivalent of Python 3's
inputis theraw_inputfunction.
- Python 3 不会评估使用
input函数接收到的数据,但 Python 2 的input函数会评估(阅读下一节以了解其含义)。 - Python 2 相当于 Python 3 的
input是raw_input函数。
Python 2.x
蟒蛇 2.x
There were two functions to get user input, called inputand raw_input. The difference between them is, raw_inputdoesn't evaluate the data and returns as it is, in string form. But, inputwill evaluate whatever you entered and the result of evaluation will be returned. For example,
有两个函数来获取用户输入,调用input和raw_input。它们之间的区别在于,raw_input不评估数据并以字符串形式按原样返回。但是,input将评估您输入的任何内容,并将返回评估结果。例如,
>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)
The data 5 + 17is evaluated and the result is 22. When it evaluates the expression 5 + 17, it detects that you are adding two numbers and so the result will also be of the same inttype. So, the type conversion is done for free and 22is returned as the result of inputand stored in datavariable. You can think of inputas the raw_inputcomposed with an evalcall.
对数据5 + 17进行评估,结果为22。当它计算表达式时5 + 17,它会检测到您正在添加两个数字,因此结果也将是相同的int类型。因此,类型转换是免费完成的,并22作为结果返回input并存储在data变量中。你可以把它想象input成raw_input一个eval电话的组合。
>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)
Note:you should be careful when you are using inputin Python 2.x. I explained why one should be careful when using it, in this answer.
注意:input在 Python 2.x中使用时应该小心。我在这个答案中解释了为什么在使用它时应该小心。
But, raw_inputdoesn't evaluate the input and returns as it is, as a string.
但是,raw_input不评估输入并按原样返回,作为字符串。
>>> import sys
>>> sys.version
'2.7.6 (default, Mar 22 2014, 22:59:56) \n[GCC 4.8.2]'
>>> data = raw_input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <type 'str'>)
Python 3.x
蟒蛇 3.x
Python 3.x's inputand Python 2.x's raw_inputare similar and raw_inputis not available in Python 3.x.
Python 3.xinput和 Python 2.xraw_input类似,raw_input在 Python 3.x 中不可用。
>>> import sys
>>> sys.version
'3.4.0 (default, Apr 11 2014, 13:05:11) \n[GCC 4.8.2]'
>>> data = input("Enter a number: ")
Enter a number: 5 + 17
>>> data, type(data)
('5 + 17', <class 'str'>)
Solution
解决方案
To answer your question, since Python 3.x doesn't evaluate and convert the data type, you have to explicitly convert to ints, with int, like this
要回答您的问题,由于 Python 3.x 不评估和转换数据类型,您必须显式转换为ints, with int,像这样
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
You can accept numbers of any base and convert them directly to base-10 with the intfunction, like this
您可以接受任何基数并使用int函数将它们直接转换为基数 10 ,如下所示
>>> data = int(input("Enter a number: "), 8)
Enter a number: 777
>>> data
511
>>> data = int(input("Enter a number: "), 16)
Enter a number: FFFF
>>> data
65535
>>> data = int(input("Enter a number: "), 2)
Enter a number: 10101010101
>>> data
1365
The second parameter tells what is the base of the numbers entered and then internally it understands and converts it. If the entered data is wrong it will throw a ValueError.
第二个参数告诉输入的数字的基数是什么,然后它在内部理解并转换它。如果输入的数据有误,会抛出一个ValueError.
>>> data = int(input("Enter a number: "), 2)
Enter a number: 1234
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 2: '1234'
For values that can have a fractional component, the type would be floatrather than int:
对于可以具有小数部分的值,类型将是float而不是int:
x = float(input("Enter a number:"))
Apart from that, your program can be changed a little bit, like this
除此之外,你的程序可以稍微改变一下,像这样
while True:
...
...
if input("Play again? ") == "no":
break
You can get rid of the playvariable by using breakand while True.
您可以play使用breakand来摆脱变量while True。
回答by Martijn Pieters
input()(Python 3) and raw_input()(Python 2) alwaysreturn strings. Convert the result to integer explicitly with int().
input()(Python 3) 和raw_input()(Python 2)总是返回字符串。使用 将结果显式转换为整数int()。
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
回答by Martijn Pieters
In Python 3.x, raw_inputwas renamed to inputand the Python 2.x inputwas removed.
在 Python 3.x 中,raw_input重命名为input并input删除 了 Python 2.x。
This means that, just like raw_input, inputin Python 3.x always returns a string object.
这意味着,就像raw_input,input在 Python 3.x 中总是返回一个字符串对象。
To fix the problem, you need to explicitly make those inputs into integers by putting them in int:
要解决这个问题,您需要通过将这些输入明确地将它们放入整数int:
x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
回答by Aravind
I encountered a problem of taking integer input while solving a problem on CodeChef, where two integers - separated by space - should be read from one line.
我在解决CodeChef上的一个问题时遇到了输入整数的问题,其中两个整数 - 由空格分隔 - 应该从一行读取。
While int(input())is sufficient for a single integer, I did not find a direct way to input two integers. I tried this:
虽然int(input())对于单个整数就足够了,但我没有找到直接输入两个整数的方法。我试过这个:
num = input()
num1 = 0
num2 = 0
for i in range(len(num)):
if num[i] == ' ':
break
num1 = int(num[:i])
num2 = int(num[i+1:])
Now I use num1 and num2 as integers. Hope this helps.
现在我使用 num1 和 num2 作为整数。希望这可以帮助。
回答by gumboy
Multiple questions require input for several integers on single line. The best way is to input the whole string of numbers one one line and then split them to integers. Here is a Python 3 version:
多个问题需要在一行上输入多个整数。最好的方法是将整串数字一行一行输入,然后将它们拆分为整数。这是一个 Python 3 版本:
a = []
p = input()
p = p.split()
for i in p:
a.append(int(i))
Also a list comprehension can be used
也可以使用列表理解
p = input().split("whatever the seperator is")
And to convert all the inputs from string to int we do the following
并将所有输入从 string 转换为 int 我们执行以下操作
x = [int(i) for i in p]
print(x, end=' ')
shall print the list elements in a straight line.
应以直线打印列表元素。
回答by user1341043
回答by Sanyal
def dbz():
try:
r = raw_input("Enter number:")
if r.isdigit():
i = int(raw_input("Enter divident:"))
d = int(r)/i
print "O/p is -:",d
else:
print "Not a number"
except Exception ,e:
print "Program halted incorrect data entered",type(e)
dbz()
Or
num = input("Enter Number:")#"input" will accept only numbers
回答by Hemanth Savasere
Convert to integers:
转换为整数:
my_number = int(input("enter the number"))
Similarly for floating point numbers:
同样对于浮点数:
my_decimalnumber = float(input("enter the number"))
回答by Tobias Kienzler
While in your example, int(input(...))does the trick in any case, python-future's builtins.inputis worth consideration since that makes sure your code works for both Python 2 and 3 anddisables Python2's default behaviour of inputtrying to be "clever" about the input data type (builtins.inputbasically just behaves like raw_input).
虽然在您的示例中,int(input(...))在任何情况下都有技巧,python-future'sbuiltins.input值得考虑,因为这可以确保您的代码适用于 Python 2 和 3并禁用 Python2 的默认行为,即input尝试对输入数据类型“聪明”(builtins.input基本上只是表现得像raw_input)。
回答by ravi tanwar
n=int(input())
for i in range(n):
n=input()
n=int(n)
arr1=list(map(int,input().split()))
the for loop shall run 'n' number of times . the second 'n' is the length of the array. the last statement maps the integers to a list and takes input in space separated form . you can also return the array at the end of for loop.
for 循环应运行“n”次。第二个“n”是数组的长度。最后一条语句将整数映射到一个列表,并以空格分隔的形式接受输入。您还可以在 for 循环结束时返回数组。

