TypeError:'str'对象不能解释为整数

Joe*_*Joe 9 python types

我不明白代码的问题是什么,它非常简单,所以这很简单.

x = input("Give starting number: ")
y = input("Give ending number: ")

for i in range(x,y):
 print(i)
Run Code Online (Sandbox Code Playgroud)

它给了我一个错误

Traceback (most recent call last):
  File "C:/Python33/harj4.py", line 6, in <module>
    for i in range(x,y):
TypeError: 'str' object cannot be interpreted as an integer
Run Code Online (Sandbox Code Playgroud)

例如,如果x为3且y为14,我希望它打印

Give starting number: 4
Give ending number: 13
4
5
6
7
8
9
10
11
12
13
Run Code Online (Sandbox Code Playgroud)

问题是什么?

Bar*_*zKP 14

最简单的解决方法是:

x = input("Give starting number: ")
y = input("Give ending number: ")

x = int(x)  # parse string into an integer
y = int(y)  # parse string into an integer

for i in range(x,y):
    print(i)
Run Code Online (Sandbox Code Playgroud)

input返回一个字符串(raw_input在Python 2中).int尝试将其解析为整数.如果字符串不包含有效的整数字符串,则此代码将引发异常,因此您可能希望使用try/ exceptstatements 对其进行一些优化.


小智 6

您收到错误是因为 range() 仅将 int 值作为参数。

尝试使用 int() 来转换您的输入。


小智 5

x = int(input("Give starting number: "))
y = int(input("Give ending number: "))

for i in range(x, y):
    print(i)
Run Code Online (Sandbox Code Playgroud)

这输出:

我已经用代码上传了输出