请解释 Python For 循环和数据类型

标签 python string for-loop int user-input

我正在创建一个 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/

相关文章:

python - Django 身份验证 : password change template customization

python - 使用查询迭代器在 python 中查询应用程序引擎的游标

python - 在 Python 中使用类根据用户输入打印出实例属性

string - 奇怪的 typescript 字符串枚举无法从字符串解析

python - Pandas read_csv converter – 如何处理异常(literal_eval SyntaxError)

javascript - 无法弄清楚我在 JavaScript 中的 if 语句有什么问题 [9 月 1 日更新 看来我的 for 循环运行了两次,我该如何解决?]

C语言isMagicsquare函数: What logic error is in my function code?

c++ - 将 for 循环从 matlab 转移到 c++

python - 如何提取和打印与这些 RegEx 模式之一匹配的子字符串,同时保持原始输入字符串中的出现顺序?

正确输出后打印随机符号的C程序