编程新手求助:如何实现Python数组中负数求和?
Fixing Your Python Negative Number Sum Code
Hey there! Let's get your code working to sum all the negative numbers in your array. I'll break down the issues in your current code and show you a corrected version, plus a more concise alternative.
Issues in Your Current Code
- Incomplete function definition: Your
def maline is cut off, and the function nameArraySumNegativeis placed incorrectly. Proper function definitions follow the formatdef function_name(parameters):. - Missing loop logic: You need to iterate over each element in the array to check if it's negative—right now there's no code to go through each value.
- Syntax error in condition:
if i<0is missing a colon (:) at the end, which is required for Python conditional statements. - No accumulator variable: There's nothing to keep track of the total sum of negative numbers as you find them.
- Invalid function call:
printsum(myvals)isn't a valid Python function; you need to call your defined function and print its result.
Corrected Complete Code
Here's a fixed version that works as intended:
# Define the function to calculate sum of negative numbers def ArraySumNegative(arr): # Initialize a variable to hold the total sum of negatives total_negative = 0 # Loop through each number in the input array for num in arr: # Check if the number is negative if num < 0: # Add the negative number to the total total_negative += num # Return the final sum return total_negative # Test the function with your sample array myvals = [1, -1, 2, -3.5, 8.5] # Call the function and store the result result = ArraySumNegative(myvals) # Print the result print("Sum of negative numbers:", result)
How This Works
- Function Definition:
ArraySumNegative(arr)takes an arrayarras input. - Accumulator:
total_negativestarts at 0 and will hold the sum of all negative numbers. - Loop:
for num in arriterates over every element in the array, assigning each element tonum. - Condition Check:
if num < 0checks if the current number is negative. If yes, it adds the number tototal_negative. - Return Result: The function returns the final sum, which we then print.
A More Concise Version
If you want to write this more succinctly, you can use Python's built-in sum() function with a generator expression to filter negatives:
def ArraySumNegative(arr): return sum(num for num in arr if num < 0) myvals = [1, -1, 2, -3.5, 8.5] print("Sum of negative numbers:", ArraySumNegative(myvals))
This does the same thing in fewer lines—sum() calculates the total of all numbers in the generator expression, which only includes values from arr that are negative.
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

