类型错误:“str"对象不能解释为整数 [英] TypeError: 'str' object cannot be interpreted as an integer

查看:58
本文介绍了类型错误:“str"对象不能解释为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't understand what the problem is with the code, it is very simple so this is an easy one.

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

for i in range(x,y):
 print(i)

它给了我一个错误

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

举个例子,如果 x 是 3,y 是 14,我希望它打印

As an example, if x is 3 and y is 14, I want it to print

Give starting number: 4
Give ending number: 13
4
5
6
7
8
9
10
11
12
13

有什么问题?

推荐答案

最简单的解决方法是:

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)

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

input returns you a string (raw_input in Python 2). int tries to parse it into an integer. This code will throw an exception if the string doesn't contain a valid integer string, so you'd probably want to refine it a bit using try/except statements.

这篇关于类型错误:“str"对象不能解释为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆