int 对象在尝试对数字的数字求和时不可迭代? [英] int object is not iterable while trying to sum the digits of a number?

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

问题描述

我有这个代码:

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

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

但它抛出一个错误:'int' object is not iterable

我想通过添加每个数字来找出总数,例如,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 call to int - you're converting a string of characters to an integer, which isn't what you want (you want to treat each character as its own number). Change:

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

到:

inp = input("Enter a number:")

既然 inp 是一串数字,您可以逐个数字地循环遍历它.

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

接下来,为 n 分配一些初始值——就像你现在的代码一样,你会得到一个 NameError 因为你从来没有初始化它.大概你想要 n = 0for 循环之前.

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;

除了不必要的分号(Python 是一种基于缩进的语法)之外,它还试图将 字符 i 与 整数 n 相加——这不会工作!所以,这个变成了

which, besides the unnecessary semicolon (Python is an indentation-based syntax), 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天全站免登陆