如何将输入读为数字?

发布于 2025-02-11 17:17:15 字数 481 浏览 4 评论 0 原文

为什么 x y 字符串而不是以下代码中的ints?

(注意:在Python 2.x中使用 RAW_INPUT()。in Python 3.x使用 input() raw_input()被重命名为 input()在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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

美人骨 2025-02-18 17:17:15

自Python 3以来noreferrer“> int ,这样,

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

您可以接受类似的基础的数字,

>>> 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:"))

Python 2和3

摘要

  • Python 2的 差异>输入函数评估了接收到的数据,将其隐含地转换为整数(请阅读下一节以了解含义),但是Python 3的 input> Input 函数不再执行此操作。
  • Python 2等于Python 3的输入 raw_input 函数。

python 2.x

有两个功能可以获取用户输入,称为 input raw_input 。它们之间的区别是, raw_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 变量中。您可以将输入视为 raw_input est 呼叫。

>>> data = eval(raw_input("Enter a number: "))
Enter a number: 5 + 17
>>> data, type(data)
(22, <type 'int'>)

注意:在Python 2.x中使用输入时,您应该小心。我解释了为什么在使用时应该小心,in 这个答案

但是, 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's 和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'>)

Since Python 3, input returns a string which you have to explicitly convert to int, like this

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

You can accept numbers of any base 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 it the base of the number 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:"))

Differences between Python 2 and 3

Summary

  • Python 2's input function evaluated the received data, converting it to an integer implicitly (read the next section to understand the implication), but Python 3's input function does not do that anymore.
  • 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 input and raw_input. 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 the input and stored in the 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 input 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'>)
作死小能手 2025-02-18 17:17:15

在Python 3.x中, RAW_INPUT 被重命名为 Input ,然后删除了Python 2.x 2.x input 。

这意味着,就像 raw_input 在Python 3.x中总是返回字符串对象。

要解决问题,您需要通过将这些输入放入 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: "))
梦幻的味道 2025-02-18 17:17:15

对于单行中的多个整数, 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())
裂开嘴轻声笑有多痛 2025-02-18 17:17:15

input()(Python 3)和 RAW_INPUT()(Python 2) emwly 返回字符串。用 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: "))
空气里的味道 2025-02-18 17:17:15

多个问题需要在一行上输入多个整数。最好的方法是按行进入整个数字的整个字符串,然后将其分成整数。这是Python 3版本:

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

您还可以使用列表综合:

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

要将所有输入从字符串转换为int,我们进行以下操作:

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

列表元素应以直线打印。

Multiple questions require multiple integers to be entered on a single line. The best way is to enter the entire string of numbers line by line and split them into integers. Here is the Python 3 version:

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

You can also use list comprehensions:

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

To convert all input from string to int we do the following:

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

List elements should be printed in straight lines.

淡淡離愁欲言轉身 2025-02-18 17:17:15

转换为整数:

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"))
柏拉图鍀咏恒 2025-02-18 17:17:15
n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

for循环应运行“ n”次数。第二个“ n”是阵列的长度。
最后一个语句将整数映射到列表,并以空格分离的形式获取输入。
您也可以在循环的末端返回阵列。

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.

你是暖光i 2025-02-18 17:17:15

我遇到了一个问题的问题,即在

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

昇り龍 2025-02-18 17:17:15
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
烙印 2025-02-18 17:17:15

在您的示例中, int(input(...))在任何情况下都可以做到这一点, python-future 's incoreins.input 值得考虑,因为这确保您的代码可适用于Python 2和3 and 禁用 input 的Python2的默认行为,试图对输入数据类型“聪明”( nelidens.input.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).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文