0

I am new to the world of programming and ran into this syntax error when i ran the code it gives me a syntax error and highlights the word element in red.Please help

given_list = [5,4,4,3,1,-2,-2,-5]
total = 0
for given element in given_list:
    if element <= 0:
        break
    total += element
print total    

I have no previous work experience so please help me.I think the error is because of some extra space or so but i have no idea.

2 Answers 2

3

Python identifiers can't use space symbols (well, it is logical). So you can't use given element variable, you should replace it with element. Here is the correct code:

given_list = [5,4,4,3,1,-2,-2,-5]
total = 0
for element in given_list:
    if element <= 0:
        break
    total += element
print(total)  # Works both in Python2 and Python3
Sign up to request clarification or add additional context in comments.

Comments

1

Python does not allow you to use spaces in identifiers. Because of this, you cannot use given element as an identifier name. Instead, you should try using given_element. Another problem here is that you are using print total. This will not work in python 3.x, instead use print(total), as it will work in python 2.x and 3.x. Here is the code with these corrections:

given_list = [5,4,4,3,1,-2,-2,-5]
total = 0
for given_element in given_list:
    if given_element <= 0:
        break
    total += given_element
print(total)    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.