Sunday, May 27, 2012

Variable Scope

I know this was probably confusing, so let's go over it in detail.

Scope


Again, scope is the word we use to describe the ability to access certain variable names in a certain place in our code.  Languages vary on how scope works, but we'll stick with python.

So far, we've learned about two kinds of scope: function scope and global scope.  The two are separate from each other, but there are ways to cross over, but first let's explore what scope means for our programs.

Open a new file and save it where you want (I recommend calling it "scopeTest.py" and putting in a folder called "tests").  Lets start by creating a function and a few variables in various scopes.


globalVar = "This is global"


def myFunction():
  localVar = "This is local"
  print "myFunction - localVar:  " + localVar
  print "myFunction - globalVar: " + globalVar


myFunction()
print
print "global - globalVar: " + globalVar
print "global - localVar:  " + localVar




Can you figure out what will happen?  Let's run it and see if you're right.



Oops.  We couldn't access the variable localVar outside the function.  Ok so let's get rid of the line where we print that out

print "global - localVar:  " + localVar

Now let's make things a little trickier.  Let's change our function to this.


def myFunction():
  localVar = "This is local"
  globalVar = "This is local"
  print "myFunction - localVar:  " + localVar
  print "myFunction - globalVar: " + globalVar



Ok now let's run it and see what happens.



Surprised?  In one place, globalVar was one string, and in the other it was a different one at the same time.  Apparently, when you assign to globalVar inside the function, Python creates a new variable with function scope and hides or shadows the global-scope globalVar.  In order to access the global version of globalVar, we need to add this line underneath the def line.

global globalVar



That should do it.  Now run it.



There we go.  Now when we assign "This is local" to globalVar, we're assigning it to the global version.  You must do this whenever you want to assign to a global variable inside a function.

I hope that clarifies a few things for you about scope.  I know it's just another thing to get your mind around, but trust me: it's not that difficult once it clicks.  All these things make sense together; it just takes a little practice.


101 comments:

  1. You said... at the start at this page...

    "I know this was probably confusing, so let's go over it in detail."

    You need to learn how to correctly reference your work. How do you get to the first part ? I've been trying to find part one for a damn week !

    ReplyDelete
    Replies
    1. Rudares
      Rudra Engineering Services Is One Of The Best Engineering Services Firm In India.
      We help startups and established organizations by bringing product ideas to life through superior product design and engineering services.

      Delete
  2. Thanks for the tutorial, the "global" keyword used inside a function definition cured my local variable woes.

    ReplyDelete
  3. Are local function variables thread safe in python

    ReplyDelete
  4. Are local function variables thread safe in python

    ReplyDelete
  5. Thank you so much.I hope to really understand this information.The way you share stated everything useful content and content is quality awesome info.Python Online Training
    Learn Python Online

    ReplyDelete
  6. Worthful Python tutorial. Appreciate a lot for taking up the pain to write such a quality content on Python course. Just now I watched this similar -Python tutorial and I think this will enhance the knowledge of other visitors for sure. Thanks anyway.https://www.youtube.com/watch?v=qgOXopu4n7c

    ReplyDelete
  7. Thanks for sharing basic python concept.we are clearly understand the variable scope concept. we do have dedicated and experience developer.Hire Python

    ReplyDelete
  8. awesome post presented by you..your writing style is fabulous and keep update with your blogs Data Science online Course Hyderabad

    ReplyDelete
  9. Nice Post! It is really interesting to read from the beginning & I would like to share your blog to my circles, keep sharing… Python Training in Hyderabad

    ReplyDelete
  10. Great blog informative and understandable

    Sanjary Academy provide pressure vessel design,quality management system course, piping design course, qa/qc course and document controller course.
    Welding Inspector Course
    Safety officer course
    Quality Management Course
    Quality Management Course in India

    ReplyDelete
  11. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.DataScience with Python Training in Bangalore


    ReplyDelete
  12. I think you did an awesome job explaining it. Sure beats having to research it on my own. Thanks
    BCOM 1st, 2nd & 3rd Year TimeTable 2020

    ReplyDelete
  13. This is a terrific article, and that I would really like additional info if you have got any. I’m fascinated with this subject and your post has been one among the simplest I actually have read.

    Selenium Training in Electronic City

    ReplyDelete
  14. Excellent blog, I wish to share your post with my folks circle. It’s really helped me a lot, so keep sharing post like this.
    Microsoft Azure Training in Electronic City

    ReplyDelete
  15. After going over a handful of the weblog articles for your net website, I genuinely admire your approach of writing a weblog. I bookmarked it to my bookmark web site list and might be checking lower again in the close to future. tech Please test out my website as nicely and let me apprehend what you believe you studied.

    ReplyDelete

  16. Needed to compose you a very little word to thank you yet again regarding the nice suggestions you’ve contributed here.



    Machine Learning Training In Hyderabad

    ReplyDelete

  17. I am very happy when read this blog post because blog post written in good manner and write on good topic. Thanks for sharing valuable information about Salesforce Course.

    Java training in chennai | Java training in annanagar | Java training in omr | Java training in porur | Java training in tambaram | Java training in velachery

    ReplyDelete
  18. Great post! I am actually getting ready to across this information, It’s very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.
    CRS Info Solutions Salesforce Admin Training 

    ReplyDelete
  19. The information's which are conveyed through this Blogs are Very Essential for all.Thanks for sharing your Knowledge's with all.
    python training in chennai | python training in annanagar | python training in omr | python training in porur | python training in tambaram | python training in velachery

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. thanks for sharing nice information.
    more : https://www.kellytechno.com/Hyderabad/Course/Machine-Learning-Training-In-Hyderabad

    ReplyDelete
  22. wonderful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article resolved my all queries.
    AWS training in Chennai

    AWS Online Training in Chennai

    AWS training in Bangalore

    AWS training in Hyderabad

    AWS training in Coimbatore

    AWS training

    ReplyDelete

  23. You have explained the concept really well. Was looking for this information from a while & luckily I stumbled upon your post. Looking forward for more of such informative updates from you

    Data Science Training In Hyderabad
    Data Science Course In Hyderabad

    ReplyDelete
  24. Great post! I am actually getting ready to across this information, It’s very helpful for this blog. Also great with all of the valuable information you have Keep up the good work you are doing well.

    DevOps Training in Hyderabad

    ReplyDelete
  25. Very useful information, the post shared was very nice.
    python Online Training

    ReplyDelete
  26. I’ve beeen exploring for a little for any high quakity articles or weblog posts on this kind of space.
    BA Third Sem Result

    ReplyDelete
  27. I am very happy when these blog posts read because blog post was written in a good manner and write on a good topic.
    Hire developers

    ReplyDelete
  28. This is exactly the information I'm looking for, I couldn't have asked for a simpler read with great tips like this... Thanks! ExcelR Data Analytics Course

    ReplyDelete
  29. software development company
    Hire the web of experienced custom software developers for your esteemed project today. Mobile app, web app, cloud app, hybrid app development company.

    ReplyDelete
  30. Really nice blog, Impressive and knowledgeable content. Keep sharing more.
    Python Course with Placements in Hyderabad

    ReplyDelete
  31. Your article is such an informative article. It is glad to read such those articles thanks for sharing. Kit Harington Eternals Jacket

    ReplyDelete
  32. CronJ, a flutter development company, can help you find a flutter app developer, coder, programmer, architect, engineer mentor. For startups and enterprises, we offer flutter app development services in the United States, the United Kingdom, Singapore, and Hong Kong.

    ReplyDelete
  33. You have done a great job. I will definitely dig it and personally recommend to my friends. I am confident they will be benefited from this site. data scientist course in kanpur

    ReplyDelete
  34. I really enjoyed reading your articles. It looks like you’ve spent a lot of time and effort on your blog. Coco Miguel Hoodie

    ReplyDelete
  35. Amazing or I can say this is a remarkable article.

    BA 3rd Year Admit Card 2022

    ReplyDelete
  36. This comment has been removed by the author.

    ReplyDelete
  37. SEM Course is the process by which we promote our website or business through the use of social media. We have a lot of social media like Facebook, YouTube, Twitter, Google+, LinkedIn and many more. These social media are the best sources for growing your audience. Because everyone knows they access these media every day. Social Media Marketing provides an effective social media strategy for your business with a focus on social trending media
    SMM Course
    Address_ Pitampura, Unit No.-601-602, 6th Floor, PP City Center, Delhi, 110034, India
    Phone No._9818629898, 9818619898.

    ReplyDelete
  38. Positively, generally speaking, particularly interesting post. I was looking for such an information and totally valued the experience of checking this one out. Keep on posting. A commitment of appreciation is all together for sharing.data science course in bhopal

    ReplyDelete
  39. Thanks for sharing. This blog post was really amazing!
    visit: -swhizz
    Our services:-
    Devops
    aws
    java
    SoftwareTesting

    ReplyDelete
  40. Very Nice Blog. Thanks for sharing this information with us. Here am sharing some information about training institute.
    Online Dispensary Canada

    ReplyDelete
  41. VRay Crack For SketchUp is one of the top industry standard render engines, spanning feature film to architectural visualization V-Ray Serial Key

    ReplyDelete
  42. Great blog, keep writing. if any one want to learn these coding, they can join online python classes in Ghaziabad.

    ReplyDelete
  43. Hi thanx for the information keep sharing it

    Crystaline is the leading provider of point-of-sale (POS) software solutions in Kenya . We offer the best POS software solutions to help businesses streamline their operations, increase efficiency, and reduce costs. Our POS software provides a comprehensive suite of features that enable businesses to manage their sales and inventory, track customer data, generate reports, and more. With our POS system, businesses can easily manage their operations and maximize profits.

    ReplyDelete
  44. "Great explanation of variable scope! This helps clarify an important concept in Python programming."
    Data Analytics Courses In Bangalore

    ReplyDelete
  45. This explanation of variable scope is extremely beneficial to Python beginners. Understanding scope might be difficult, but your clear examples help. Thank you for your contribution!
    Data Analytics Courses in Delhi

    ReplyDelete
  46. Thanks for the detailed explanation of variable scope in Python. It's a tricky concept to grasp, but your examples and explanations helped a lot.
    Data Analytics Courses in Nashik

    ReplyDelete
  47. An article on variable scope is likely a helpful resource for programmers, clarifying the concept and importance of variable scope within various programming languages.

    Data Analytics Courses In Kochi



    ReplyDelete
  48. This explanation of variable scope in Python is incredibly helpful for beginners. The step-by-step examples and clear explanations make it easy to grasp this important concept. Great teaching.
    Data Analytics Courses In Dubai

    ReplyDelete
  49. "This blog is a knowledge oasis, offering valuable insights in a digestible format. It's my go-to source for staying informed and inspired."
    Data Analytics Courses in Zurich

    ReplyDelete
  50. I loved the content especially the topic in that one of the standout features of Python is its readability, and the blog post does an excellent job of showcasing this aspect. The author's explanations are easy to follow, making it an engaging learning experience.
    Data Analytics Courses In Chennai

    ReplyDelete
  51. nice blog
    Data Analytics Courses In Vadodara

    ReplyDelete
  52. This site is a haven of knowledge, providing insightful information in an easily readable way. thanks.
    Data Analytics Courses in Agra

    ReplyDelete
  53. Thanks for sharing basic python concept.
    I are clearly understand the variable scope concept.
    Data Analytics courses IN UK

    ReplyDelete
  54. Thank you so much for informing us about this Variable Scope. It was so helpful for me. keep posting more.
    Visit - Data Analytics Courses in Delhi

    ReplyDelete
  55. Variable scope in Python defines where in the code a variable can be accessed. It includes local, enclosing, global, and built-in scopes, each with different visibility and accessibility rules.
    In the context of data analytics, understanding variable scope is crucial for effective data manipulation and analysis. Glasgow's Data Analytics courses offer comprehensive training in Python and data handling, empowering professionals to harness the full potential of their data. Please also read Data Analytics courses in Glasgow.

    ReplyDelete
  56. This article is a goldmine of information. Thanks for the insights!

    ReplyDelete
  57. I appreciate the research that went into this. It's evident that you're passionate about the subject.

    ReplyDelete
  58. The blog post provides clear and excellent explanation of the topic function scope and global scope. Thanks for sharing informative blog post.
    data analyst courses in limerick

    ReplyDelete
  59. such a informative & well explained blog, a must read for python beginners like me.
    financial modelling course in melbourne

    ReplyDelete
  60. "Great article! Understanding variable scope is crucial for avoiding bugs and writing clean code. I particularly liked your explanation of local and global scope. Have you encountered any tricky scenarios related to variable scope in your programming experience? Share your thoughts below!"
    Best Data analytics courses in India

    ReplyDelete
  61. Thank you for providing the in depth explanation and information on the word Variable Scope.
    Digital Marketing Courses In Bhutan

    ReplyDelete
  62. Nice article. The content is on point. Thanks a lot for sharing this content. Keep it up!
    Please do check here for many of the professional skills courses launched globally. please click here for more details.
    investment banking courses in Mumbai

    ReplyDelete

  63. "Variable scope is such a fundamental concept in programming, and this blog does a fantastic job of demystifying its complexities. The clear explanations and examples make it an invaluable resource for beginners navigating this aspect of coding. The breakdown of local and global scope, along with practical tips, truly simplifies what can often be a confusing topic. Well done!"
    Investment banking jobs in Mumbai

    ReplyDelete
  64. Thank you for the clear and concise explanation of variable scope in Python. Your examples and step-by-step approach make it easier to grasp. Great job on the post!

    Investment banking courses syllabus

    ReplyDelete
  65. Hey there! Variable scope is a fundamental concept in programming. It refers to the accessibility and lifespan of variables within different parts of a program. Understanding variable scope is crucial for writing clean and efficient code. It helps us avoid conflicts and ensures that our variables are used in the right context. Thanks for bringing up this important topic!
    Data analytics courses in Rohini

    ReplyDelete