我正在创建一个 python 程序,它根据变量值为网站创建一个 xhtml 表。
请看下面两段代码。第二个不起作用。
rows = int(input('How many rows would you like? '))
for i in range(rows):
print 'lol'
rows = raw_input('How many rows would you like? ')
int(rows)
for i in range(rows):
print 'lol'
即使我已经正确声明 rows
变量正在更改为整数,为什么 range
函数不接受这个并将其视为整数?
最佳答案
i have properly stated that the rows variable is being changed to an integer
否,行未更改为整数。仅在 rows
上应用 int(rows)
不会将 str
对象 rows
更改为 int
。但它返回一个integer
对象。
您可能需要将返回值存储在一个变量中,然后使用它。或者,直接在 range
函数中使用它。
int(rows)
for i in range(rows): // rows used here is still a string
上面的代码应该是:-
for i in range(int(rows)):
关于请解释 Python For 循环和数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13542514/