int对象不可迭代? [英] int object is not iterable?

查看:1764
本文介绍了int对象不可迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

inp = int(input("Enter a number:"))

for i in inp:
    n = n + i;
    print (n)

...抛出错误: 'int'对象不可迭代

我想通过添加每个数字找出总数,例如110. 1 + 1 + 0 = 2.我该怎么做?

I wanted to find out the total by adding each digit, for eg, 110. 1 + 1 + 0 = 2. How do I do that?

谢谢

推荐答案

首先,失去对 int 的荒谬的召唤 - 这会让你更远从你想要的东西,所以,什么曾经拥有你把它在?!更改:

First, lose that absurd call to int -- which is taking you farther from what you want, so, what ever possessed you to put it in?! Change:

inp = int(input("Enter a number:"))

更简单

inp = input("Enter a number:")

以便 inp 是一串数字,你确实可以逐位循环。

so that inp is a string of digits and you can indeed loop over it, digit by digit.

接下来,将一些初始值赋给 n - 当你现在编码代码时,你会得到一个 NameError ,因为你从来没有初始化它。大概你希望 n = 0 之前循环。

Next, assign some initial value to n -- as you code stands right now, you'll get a NameError since you never initialize it. Presumably you want n = 0 before the for loop.

接下来,再次考虑字符和整数之间的差异。你现在有:

Next, consider the difference between a character and an integer again. You now have:

n = n + i;

除了完全荒谬(但无害)的分号外,还试图将字符加起来我对整数 n - 这不起作用!所以,这个变成

which, besides the utterly absurd (but innocuous) semicolon, is trying to sum the character i to the integer n -- that won't work! So, this becomes

n = n + int(i)

将字符'7'转换为整数 7 ,等等。

to turn character '7' into integer 7, and so forth.

这篇关于int对象不可迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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