Trying to add all Values [duplicate] - python

This question already has answers here:
'int' object not iterable
(2 answers)
Closed 2 years ago.
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)

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)

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)

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().

Related

Final outputs aren't printing after inputting values

I'm new to lists in python and trying to write a code where one inputs 10 numbers using a list and the following is performed:
Copy the number which is even to a new list named "EvenList" and
output that new list.
Output the average of the numbers stored in the new list.
Here is my code:
List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
List.append(int(input("Enter a number: ")))
while List[i]%2==0:
EvenList.append(List[i])
totalnum=totalnum+List[i]
count=count+1
print(EvenList)
average=totalnum/count
print("Average: ", average)
Whenever I run this module, after inputting my values my outputs (both the EvenList and average) aren't printed. Here's the output I get:
Example 1:
Enter a number: 1
Enter a number: 2
Example 2:
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 2
By further analysis, I realized whenever an even number was inputted, that's when the code gave an empty output. So I'm speculating my error lies in line 8 - 11 (there may be even more).
I so far changed my inital code:
List[i]=int(input("Enter a number: ")) and EvenList[index]=(List[i])
to
List.append(int(input("Enter a number: "))) and EvenList.append(List[i]) respectively - which I'm still confused as to why the intial code isn't considered to be correct since I thought they did the exact same thing [if someone could explain, it'd be very appreciated] - but that didn't fix this error.
It's because in while loop condition, if the number is even it gets stuck in infinite loop, instead of while add if:
List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
List.append(int(input("Enter a number: ")))
if List[i]%2==0:
EvenList.append(List[i])
totalnum=totalnum+List[i]
count=count+1
print(EvenList)
average=totalnum/count
print("Average: ", average)
Here's alternative using list comprehension, sum(), and len() as substitutes of creating EvenList, totalnum, count, and average :
List = [int(input("Enter a number: ")) for i in range(10)]
EvenList = [i for i in List if i % 2 == 0]
average = sum(EvenList)/len(EvenList)
print(EvenList); print("Average: ", average)
Or list comprehension in list comprehension:
EvenList = [i for i in [int(input("Enter a number: ")) for i in range(10)] if i % 2 == 0]
average = sum(EvenList)/len(EvenList)
print(EvenList); print("Average: ", average)

Output smiley faces based on number input [duplicate]

This question already has answers here:
How to print something a specific number of times based on user input?
(3 answers)
Closed 1 year ago.
The code is supposed to print :) based on the number inputted (an integer 1 to 10). With any positive integer, the code is supposed to print that many smiley faces (ex. if 5 is entered, 5 smiley faces should be printed).
It's required that the code should use += to add onto the end of a string and should also decrement to count down and use a loop.
x = input("enter number 1 to 10: ")
for i in len(x):
print(":) " * x)
I don't think you can multiply int values and str values, and I can't find another way to do this.
First things first, input() function returns a string. You want x to be an integer, use the int() function:
x = int(input("enter number 1 to 10: "))
Second You can either use a for loop or the multiplication operator to print n number of smileys.
# Using for loop to print n smileys :
x = int(input("enter number 1 to 10: "))
for i in range(x):
print(":) ",end="")
# Using multiplication operator :
x = int(input("enter number 1 to 10: "))
print(":) "*x)
# x should be an integer
x = int(input("enter number 1 to 10: "))
# define "s" as an empty string
s = ''
# increment ":)" to "s" x times
for _ in range(x):
s += ':)'
print(s)
You're almost there! In fact, you can multiply string and integer values. This code does what you described:
print(':) '*int(input("Enter number 1 to 10: ")))
If you really want to use a for loop and +=, you could also do this
x, s = input("enter number 1 to 10: "), ''
for i in range(x):
s += ':) '
print(s)
Answer: How to print a string x times based on user input
Credits to: NoobCoder33333
times = input('Enter number from 1 to 10: ')
word = ":-)"
print('\n'.join([word] * int(times)))

How do I sum numbers from user input in python?(only if they are even numbers)

I am new to programming, and I'm trying to make a code to get six numbers from a user and sum only even numbers but it keeps error like, "unsupported operand type(s) for %: 'list' and 'int' How can I do with it?
Also, I want to make like this,
Enter a value: 1
Is it even number?:no
Enter a value: 2
Is it even number?:yes
Enter a value: 3
Is it even number?:no
Enter a value: 6
Is it even number?:yes
but it keeps like this,
Enter a value: 1
Enter a value: 2
Enter a value: 3
Enter a value: 4
Enter a value: 5
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
Is it even number?:
How can I fix this?
anyone who can fix this problem please let me know
Python 3.7
numbers = [int(input('Enter a value: ')) for i in range(6)]
question = [input('Is it even number?: ') for i in range(6)]
list1 = [] #evens
list2 = [] #odds
if numbers % 2 ==0:
list1.append
else:
list2.append
sum = sum(list1)
print(sum)
And I'd appreciate it if you could let me know if you knew the better code
This should do it. Note that there is no real need to ask the user if the number is even, but if you do want to ask, you can just add question = input('Is it even number?: ').lower() in the loop and then do if question=='yes'. Moreover, note that you cannot perform % on a list; it has to be on a single number.
evens = []
odds = []
for i in range(6):
number = int(input('Enter a value: '))
if number%2==0:
evens.append(number)
else:
odds.append(number)
print(sum(evens))
you are running the first two input statements in for loops and print at the same time.
You can just take inputs first 6 times and store them in a list. After that you can check each input and store in even and odd lists while printing if its even or odd. and print the sum at last.
Your if condition makes no sense:
if numbers % 2 == 0:
What is the value of [1, 2, 3, 6] % 2? There is no such thing as "a list, modulo 2". Modulus is defined between two scalar numbers.
Instead, you have to consider each integer in turn. This is not an operation you get to vectorize; that is a capability of NumPy, once you get that far.
for i in range(6):
num = int(input('Enter a value: '))
# From here, handle the *one* number before you loop back for the next.
If you want to show running sum. You can do something like :
import sys
sum_so_far = 0
while True:
raw_input = input('Enter an integer: ')
try:
input_int = int(raw_input)
if input_int == 0:
sys.exit(0)
elif input_int % 2 == 0:
sum_so_far = sum_so_far + input_int
print("Sum of Even integers is {}. Enter another integer er or 0 to exit".format(sum_so_far))
else:
print("You entered an Odd integer. Enter another integer or 0 to exit")
except ValueError:
print("You entered wrong value. Enter an integer or 0 to exit!!!")

Python 2D lists appending data to a location

Wondering if someone can help me on this. I know I can append data to a 1D list by using .append. What I am having trouble figuring out is how to append data to a 2D list and have Python place the data in the right list in the right spot.
I need to create a program that runs x times (with each name having 2 pairs of values), and after each time append the user input to a list. So at the end, I need something like this:
[[Name] [1,2] [3,4]]
[[Name] [4,5] [6,7]]
etc….
How do I tell Python which List and position to place the Names and values in ?
This is what I have so far for code.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = [ [], [] ]
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
counter = counter + 1
main()
OK - so I modified the code and added in a line to append the data, after the line with the counter + 1.
list.append([[name],[first_val,first_val2], [sec_val,sec_val2]])
What I would now like to do is print the list out (via rows and columns), but am getting a IndexError. This occurs when I try to enter/print out more than 4 values. The error appears to be in the last line. Is there a way I can modify the code to stop this and print out as many values as have been requested by the user ?
for r in range(how_many):
for c in range (how_many):
print list [r][c]
And yes, I will look into using tuples as well at some point.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = []
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
counter = counter + 1
Assume we are reading the values from stdin (as in the question body)
you can use lists:
list = []
....
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
but a tuple seems to be a better fit here:
t = (name, (first_val, first_val2), (sec_val, sec_val2))
list.append(t)
Since the values are not likely to change, a tuple feels like the better choice.
Think about how a field would be accessed in each case:
list:
name = list[i][0][0]
tuple:
name = list[i][0]
Again...it just seem more natural...

Taking the sum of a list without sum()

I have a list that gets generated when a user inputs a random number they want. I want to add the sum together with out using sum(). How could I do this?
xAmount = int(input("How man numbers would you like to input: "))
numList = []
for i in range(0, xAmount):
numList.append(int(input("Enter a number: ")))
print(numList)
From here
Store the sum in a temp variable. Keep adding the input numbers to the temp variable:
xAmount = int(input("How man numbers would you like to input: "))
numList = []
numList_sum = 0
for i in range(0, xAmount):
inputted_number = int(input("Enter a number: "))
numList_sum += inputted_number
numList.append(inputted_number)
print(numList)
print(numList_sum)
You don't need a list at all.
xAmount = int(input("How man numbers would you like to input: "))
result = 0
for i in range(0, xAmount):
result = result + int(input("Enter a number: "))
print(result)
To sum a list just iterate over the list, adding up the individual values:
num_total = 0
for value in numList:
num_total += value
You could also use reduce but this might not meet your h/w requirements either:
from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)

Categories

Resources