+ 1

How to use if and else conditions while dealing list data?

numbers = [13, 5102, 45, 2301.40, 203, 1502, 3] 1. Set the value of the variable numbers_sum to be the sum of all the numbers in the list numbers. 2. By using a built-in function, complete the ifstatement. If our list has at least one member, we want to print the mean; otherwise, we want to print the number 0.

15th Sep 2020, 8:17 AM
Abhi
Abhi - avatar
11 Answers
+ 2
Did it worked??
17th Sep 2020, 6:32 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 4
To check if list numbers has elements, you can also use: if numbers: Here is the sample: numbers = [13, 5102, 45, 2301.40, 203, 1502, 3] if numbers: print(sum(numbers)/len(numbers)) else: print("0")
15th Sep 2020, 11:12 AM
Lothar
Lothar - avatar
+ 3
and you can use sum function to find out the sum of numbers in the list
15th Sep 2020, 8:29 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 2
your first if statement shoulf be: if len(numbers): # all it wants is for you to check if the list is empty
15th Sep 2020, 8:27 AM
Slick
Slick - avatar
+ 2
Abhi numbers = [13, 5102, 45, 2301.40, 203, 1502, 3] number_sum=sum(numbers) #you have to check wether the list is empty or not if numbers: #as suggested by Lothar print(number_sum/len(numbers)) else: print("0")
16th Sep 2020, 11:24 AM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 2
Try using print(0) instead of print("0")
16th Sep 2020, 2:28 PM
AKSHAY🇮🇳
AKSHAY🇮🇳 - avatar
+ 1
Hi Akshay, I tried with that option as well but not passed the test case 1. numbers = [13, 5102, 45, 2301.40, 203, 1502, 3] 2. number_sum=sum(numbers) if (numbers_sum)>= 1 : print(numbers_sum/len(numbers)) else: print("0")
16th Sep 2020, 1:48 PM
Abhi
Abhi - avatar
+ 1
Thanks Akshay, final code as follows if len(numbers)>= 1 : print(numbers_sum/len(numbers)) else: print(0)
17th Sep 2020, 5:08 AM
Abhi
Abhi - avatar
+ 1
Hi Akshay, Yes it worked at last.
17th Sep 2020, 6:10 PM
Abhi
Abhi - avatar
0
use a loop to loop through the list. use if amd elif statements to check things print out what yod like. please show an attempt
15th Sep 2020, 8:21 AM
Slick
Slick - avatar
0
Hi Lothar, Akshya, Slick, Thanks for your prompt replies but none of them are fix the issue as I mentioned earlier we need to verify the list total is greater than 1 or not first if yes then only we need to print mean of the listed values else print as "0" so please explain what did I miss in my attempt? if (numbers_sum)>= 1 : print(numbers_sum/len(numbers)) else: print("0")
16th Sep 2020, 11:10 AM
Abhi
Abhi - avatar