问题:如何将输入读取为数字?

为什么在下面的代码中使用xy字符串而不是整数?

(注意:在Python 2.x中使用raw_input()。在Python 3.x中使用input()。在Python 3.x中raw_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

Why are x and y strings instead of ints in the below code?

(Note: in Python 2.x use raw_input(). In Python 3.x use input(). raw_input() was renamed to input() in Python 3.x)

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

回答 0

TLDR

  • Python 3不会评估input函数接收到的数据,但是Python 2的input函数会评估(阅读下一节以了解含义)。
  • inputraw_input函数相当于Python 2与Python 3 。

Python 2.x

有两个函数用于获取用户输入,分别称为。它们之间的区别是,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'>)

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'>)

注意:input在Python 2.x 中使用时应小心。我在这个答案中解释了为什么在使用它时要小心。

但是,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

Python 3.x 和Python 2.x raw_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'>)

要回答您的问题,由于Python 3.x不会评估和转换数据类型,因此必须使用显式转换为ints int,如下所示

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

您可以接受任意基数的数字,并使用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

第二个参数告诉输入的数字的基础是什么,然后在内部对其进行理解和转换。如果输入的数据有误,将抛出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'

对于可以包含小数部分的值,类型应为float而不是int

x = float(input("Enter a number:"))

除此之外,您的程序可以像这样进行一些更改

while True:
    ...
    ...
    if input("Play again? ") == "no":
        break

您可以play使用break和摆脱变量while True

TLDR

  • Python 3 doesn’t evaluate the data received with input function, but Python 2’s input function does (read the next section to understand the implication).
  • Python 2’s equivalent of Python 3’s input is the raw_input function.

Python 2.x

There were two functions to get user input, called and . The difference between them is, raw_input doesn’t evaluate the data and returns as it is, in string form. But, input will evaluate whatever you entered and the result of evaluation will be returned. For example,

>>> 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 + 17 is 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 int type. So, the type conversion is done for free and 22 is returned as the result of input and stored in data variable. You can think of input as the raw_input composed with an eval call.

>>> 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 input in Python 2.x. I explained why one should be careful when using it, in this answer.

But, raw_input doesn’t evaluate the input and returns as it is, as a string.

>>> 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

Python 3.x’s and Python 2.x’s raw_input are similar and raw_input is not available in 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

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 int function, like this

>>> 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.

>>> 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 float rather than 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 play variable by using break and while True.


回答 1

在Python 3.x中,raw_input已重命名为,inputinput删除了Python2.x 。

这意味着,就像Python 3.x中的一样raw_inputinput总是返回一个字符串对象。

要解决此问题,您需要通过将它们输入以下内容来将这些输入明确地变成整数int

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

In Python 3.x, raw_input was renamed to input and the Python 2.x input was removed.

This means that, just like raw_input, input in Python 3.x always returns a string object.

To fix the problem, you need to explicitly make those inputs into integers by putting them in int:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

回答 2

对于单行中的多个整数,map可能会更好。

arr = map(int, raw_input().split())

如果数字已知(例如2个整数),则可以使用

num1, num2 = map(int, raw_input().split())

For multiple integer in a single line, map might be better.

arr = map(int, raw_input().split())

If the number is already known, (like 2 integers), you can use

num1, num2 = map(int, raw_input().split())

回答 3

input()(Python 3)和raw_input()(Python 2)始终返回字符串。使用显式将结果转换为整数int()

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

input() (Python 3) and raw_input() (Python 2) always return strings. Convert the result to integer explicitly with int().

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))

回答 4

多个问题需要在单行上输入多个整数。最好的方法是一行输入整个数字字符串,然后将它们拆分为整数。这是Python 3版本:

a = []
p = input()
p = p.split()      
for i in p:
    a.append(int(i))

也可以使用列表理解

p = input().split("whatever the seperator is")

并将所有输入从字符串转换为整数,我们执行以下操作

x = [int(i) for i in p]
print(x, end=' ')

应以直线打印列表元素。

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:

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

x = [int(i) for i in p]
print(x, end=' ')

shall print the list elements in a straight line.


回答 5

转换为整数:

my_number = int(input("enter the number"))

对于浮点数类似:

my_decimalnumber = float(input("enter the number"))

Convert to integers:

my_number = int(input("enter the number"))

Similarly for floating point numbers:

my_decimalnumber = float(input("enter the number"))

回答 6

n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

for循环应运行’n’次。第二个“ n”是数组的长度。最后一条语句将整数映射到列表,并以空格分隔的形式接受输入。您还可以在for循环的末尾返回数组。

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.


回答 7

我在解决CodeChef上的问题时遇到了输入整数的问题,该问题应从一行读取两个以空格分隔的整数。

虽然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:])

现在,我将num1和num2用作整数。希望这可以帮助。

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.

While int(input()) is sufficient for a single integer, I did not find a direct way to input two integers. I tried this:

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.


回答 8

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
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

回答 9

尽管在你的榜样,int(input(...))做的伎俩在任何情况下,python-futurebuiltins.input是值得考虑的,因为这可以确保你的代码同时适用于Python 2和3 ,并禁用Python2的违约行为,input努力成为‘聪明的’关于输入数据类型(builtins.input基本上只是的行为类似于raw_input)。

While in your example, int(input(...)) does the trick in any case, python-future‘s builtins.input is worth consideration since that makes sure your code works for both Python 2 and 3 and disables Python2’s default behaviour of input trying to be “clever” about the input data type (builtins.input basically just behaves like raw_input).


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。