Python programing 35 Define a function sumNegativeInts that

Python programing 3.5

Define a function sumNegativeInts that has one parameter of type list. The list can be empty or can contain integers. The integers can be positive or negative. The function should return the sum of negative integers in the list. Then write a main program that asks a user to enter a list of integers separated by commas with no spaces, and by using the function sumNegativeInts, display the sum of negative integers in the list the user provided to the user. Again the function sumNegativeInts should only do what’s asked to do. If the user entered an invalid list (i.e., the list contains any type that is not an integer), ask the user to re-enter until he/she enters a valid list. Use the lstrip(“-“) and isdigit() to check for integers. You can assume the user will not enter values like --3 (“double negative”). You must use a while loop to verify the user input until he/she enters it correctly.

Solution

def sumNegativeInts(l):
   sum = 0;           # make sum=0
   for i in l:           # for each number in list
       if i<0:           # add to sum if number is negative
           sum += i
   return sum
while True:
   flag = True
   x = input(\"Enter a list:\")
   try:
       nums = list(map(int, x.split(\",\")))           # check number is integer or not and convert to list
       break
   except:
       print(\"Invalid List\")  
s = sumNegativeInts(nums)
print(s)

# sample output

# Enter a list: -1,-2,-3

Python programing 3.5 Define a function sumNegativeInts that has one parameter of type list. The list can be empty or can contain integers. The integers can be

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site