-1

I m new to python and based on what I learnt so far this code should be correct,but it doesn't run.Can any of you help out

list_x=[4,5,6,7]

total1=0

def total(list_1):
    for values in list_1:
        total1 += values 
        
    print(total1)
    
total(list_x) 
001
  • 13,291
  • 5
  • 35
  • 66
  • 1
    "but it doesn't run" What do you mean, *exacty*? What are you doing? – juanpa.arrivillaga Sep 29 '20 at 20:00
  • 1
    _it doesn't run_ If you're getting errors, please include them in the question. – John Gordon Sep 29 '20 at 20:00
  • `total1 += values` You can't modify global variables inside functions without the `global` keyword. – 001 Sep 29 '20 at 20:01
  • You must define the initial total in the function, not outside of it. – MisterMiyagi Sep 29 '20 at 20:01
  • 1
    Just for fun, a shortcut would be: `sum(list_x)`. I only post this comment, not to discount learning to write functions (good work!), but simply to show the possible brevity of Python. :-) – S3DEV Sep 29 '20 at 20:04
  • wow you guys reply real fast. Thanks i figured out the problem now – Sovietsperm Sep 29 '20 at 20:07
  • @Sovietsperm - Welcome to SO. Please remember to accept (and upvote when you have enough rep) those answers which help you along the way. – S3DEV Sep 29 '20 at 20:08
  • @S3DEV could you explain how to use sum because i tried using sum(list_x) and it gave me an error – Sovietsperm Sep 29 '20 at 20:18
  • TypeError Traceback (most recent call last) in 1 list_x=[4,5,6,7] 2 ----> 3 sum(list_x) TypeError: 'int' object is not callable – Sovietsperm Sep 29 '20 at 20:19
  • 1
    This should not give any errors: `list_x = [4, 5, 6, 7]` then `sum(list_x)`. – S3DEV Sep 29 '20 at 20:28
  • @S3DEV yeah it works now. By the way is it normal for python to take up 70% of my cpu ? Im using jupyter notebook via anaconda and my cpu is relatively new. – Sovietsperm Sep 30 '20 at 10:21
  • That's a very broad question mate. It all depends of the type of processing you have going on. Very large datasets, complex graphs in Notebook - yes, it's plausible. But for small functions such as this, no. I'd recommend a Python close/re-open or reboot to clear the process log/caching. – S3DEV Sep 30 '20 at 11:12

1 Answers1

1

Move the total1 variable inside your function. Right now, it is a global variable, which means that you can't modify it from within the function without declaring your reference to it as global.

list_x=[4,5,6,7]

def total(list_1):
    total1=0
    for values in list_1:
        total1 += values 
        
    print(total1)
    
total(list_x) 
mypetlion
  • 2,415
  • 5
  • 18
  • 22