Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)
closed by

I'm totally new to python, and I have an issue.

I want to program a Python work that gives me back the amount of a rundown/list of numbers utilizing a for loop.

Check the below code:

sum = 0

for x in [1,2,3,4,5]:

      sum = sum + x

print(sum)

closed

4 Answers

0 votes
by (15.4k points)
 
Best answer
# Initialize the variable to store the sum of numbers

total_sum = 0

# Iterate through each number in the given list

for num in [1, 2, 3, 4, 5]:

    # Add the current number to the total sum

    total_sum += num

# Display the final sum

print(total_sum)

In this code, the variable total_sum is used to accumulate the sum of numbers. The for loop iterates through each number in the provided list and adds it to the total_sum variable. Finally, the resulting sum is displayed using the print() function.
0 votes
by (26.4k points)

I think what you mean is the way to exemplify that for general use, for example in a capacity: 

def sum_list(l):

    sum = 0

    for x in l:

        sum += x

    return sum

Presently you can apply this to any rundown/list. Models:

l = [1, 2, 3, 4, 5]

sum_list(l)

l = list(map(int, input("Enter numbers separated by spaces: ").split()))

sum_list(l)

Want to learn python to get expertise in the concepts of python? Join python certification course and get certified

0 votes
by (25.7k points)
The code you provided calculates the sum of the numbers in the given list using a for loop. However, it seems like you have used a reserved keyword, "sum," as a variable name. To avoid any conflicts, it's recommended to use a different variable name. Here's the corrected code:

total_sum = 0

for x in [1, 2, 3, 4, 5]:

    total_sum = total_sum + x

print(total_sum)

In this updated code, the variable total_sum is used to store the accumulated sum of the numbers. The for loop iterates over each number in the list [1, 2, 3, 4, 5] and adds it to the total_sum variable. Finally, the result is printed using the print() function.
0 votes
by (19k points)
# Initialize a variable to keep track of the sum

running_total = 0

# Iterate over a list of numbers

for number in [1, 2, 3, 4, 5]:

    # Add the current number to the running total

    running_total += number

# Display the final sum

print(running_total)

In this, a variable called running_total is used to accumulate the sum of the numbers. The for loop iterates through each number in the given list and adds it to the running total. Finally, the resulting sum is printed using the print() function.

Related questions

0 votes
1 answer
asked Feb 19, 2021 in Python by laddulakshana (16.4k points)
0 votes
1 answer
asked Mar 25, 2021 in Java by dante07 (13.1k points)
0 votes
1 answer
asked Jan 8, 2021 in SQL by Appu (6.1k points)

Browse Categories

...