为什么在下面的代码中x和y是字符串而不是整数?

(注:在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

当前回答

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

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

如果数字已经知道,(比如2个整数),您可以使用

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

其他回答

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

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

如果数字已经知道,(比如2个整数),您可以使用

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

转换为整数:

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

浮点数也类似:

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

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

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

在Python 3中。在Python 2. x中,raw_input被重命名为input。X输入被移除。

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

为了解决这个问题,你需要显式地将这些输入放入int中,使它们成为整数:

x = int(input("Enter a number: "))
y = int(input("Enter a number: "))
n=int(input())
for i in range(n):
    n=input()
    n=int(n)
    arr1=list(map(int,input().split()))

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