Explain the difference between local and global variables

The difference is the scope. A local variable can only be seen within its scope, for example a variable defined in a method can only be seen within this method. However, a global variable can be seen by everything within the program.y = 1 def foo(): x = 5 def bar(): print(x) # Doesn't work print(y) # Prints 1

Answered by Peter C. Python tutor

914 Views

See similar Python Mentoring tutors

Related Python Mentoring answers

All answers ▸

Use recursion to print all the sublists of a given list


Write a function s(n) that will return a list of the first n squares.


What would you expect to be the output of the following code snippet: `a = [1, 2, 3]; b = a; b[1] = 4; print(a); print(b);`, and why?


h


We're here to help

contact us iconContact usWhatsapp logoMessage us on Whatsapptelephone icon+44 (0) 203 773 6020
Facebook logoInstagram logoLinkedIn logo
Cookie Preferences