0

I'm a beginner in python but i have some knowledge with C++, My Problem is that I'm trying to get the sum of all the Values given by the user but i get this error 'int' object is not iterable so can someone help me please Here is my code

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

The above code works

#--Getting the Sum of all Value

for j in Value:
    j += Value

print(j) 
Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
Cuteko
  • 13
  • 1

3 Answers3

0

First:

str(input())

becomes

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

Then: if you are using j in the for loop it wont work because you are changing its value, what you need to do is something like this

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)
azro
  • 53,056
  • 7
  • 34
  • 70
Evorage
  • 493
  • 3
  • 15
0

Value is just the last value that the user entered, not all the values they entered. You need to put them in a list if you want to loop over them.

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)
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You seems to be pretty new to python. In my opinion, you should refer to Lists in Python. But the easy solution for your problem is given below-

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)

One more thing which you should notice is that, input simply returns the entered data in string format. So, no need to typecast that with str().

Chetan Goyal
  • 435
  • 5
  • 14
  • Thankyou, Yes actually while learning i kinda change some of my projects in C++ to python – Cuteko Jun 17 '20 at 19:20
  • It's a very good habit to convert projects from one programming language to another. It helps to understand the differences between the languages and makes the learning process fast. Good Luck for your future. :) – Chetan Goyal Jun 18 '20 at 18:38