【问题标题】:Trying to add all Values [duplicate]尝试添加所有值[重复]
【发布时间】:2020-10-07 16:27:34
【问题描述】:

我是 python 的初学者,但我对 C++ 有一些了解,我的问题是我试图获取用户给出的所有值的总和,但我得到这个错误 'int' object is not iterable所以有人可以帮我吗这是我的代码

Food= int(input("Enter number of Food: "))
for x in range(Food):
    Foodn = str(input("Enter Food Name: "))
    Value = int(input("Enter Value: ))

以上代码有效

#--Getting the Sum of all Value

for j in Value:
    j += Value

print(j) 

【问题讨论】:

  • Value = int(input("Enter Value: )) ==> Value 是一个整数。 for j in Value:==> 你尝试迭代一个整数。你如何迭代 42?
  • 我对 python 有点陌生,这就是为什么我用 C++ 询问我是通过 for(int i =1 , i != Food, i ++) { 完成的
  • 对不起,如果我不够了解

标签: python python-3.x


【解决方案1】:

第一:

str(input())

变成

input() #By default its a string but it doesn't really matter

然后: 如果您在 for 循环中使用 j 它将不起作用,因为您正在更改它的值, 你需要做的是这样的事情

Food= int(input("Enter number of Food: "))
List = []
for x in range(Food):
    Foodn = str(input("Enter Food Name: "))
    Value = int(input("Enter Value: "))
    List.append(Value)

Total = 0
for j in List:
    Total += j
print(Total)

【讨论】:

  • 不要使用sum作为变量,因为它是一个内置函数名。
  • 非常感谢
【解决方案2】:

Value 只是用户输入的最后一个值,而不是他们输入的所有值。如果你想循环它们,你需要把它们放在一个列表中。

Food= int(input("Enter number of Food: "))
values = []
for x in range(Food):
    Foodn = str(input("Enter Food Name: "))
    Value = int(input("Enter Value: "))
    values.append(Value)

#--Getting the Sum of all Value

total = 0
for j in values:
    total += j

print(total)

【讨论】:

  • 非常感谢!
【解决方案3】:

您似乎对 python 很陌生。在我看来,你应该参考Lists in Python。但是下面给出了解决您问题的简单方法-

Food= int(input("Enter number of Food: "))
total = 0
for x in range(Food):
    Foodn = str(input("Enter Food Name: "))
    Value = int(input("Enter Value: ))
    total += Value
print(total)

您应该注意的另一件事是,输入只是以字符串格式返回输入的数据。因此,无需使用str() 进行类型转换。

【讨论】:

  • 谢谢,是的,实际上在学习时我将一些 C++ 项目更改为 python
  • 将项目从一种编程语言转换为另一种编程语言是一个非常好的习惯。它有助于理解语言之间的差异并加快学习过程。祝你未来好运。 :)
  • 非常感谢,愿上帝保佑我们
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-21
  • 2011-12-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多