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.


123 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. 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
  34. Amazing or I can say this is a remarkable article.

    BA 3rd Year Admit Card 2022

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

    ReplyDelete
  36. 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
  37. Thanks for sharing. This blog post was really amazing!
    visit: -swhizz
    Our services:-
    Devops
    aws
    java
    SoftwareTesting

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

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

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

    ReplyDelete
  41. 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
  42. "Great explanation of variable scope! This helps clarify an important concept in Python programming."
    Data Analytics Courses In Bangalore

    ReplyDelete
  43. 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
  44. 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
  45. 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
  46. 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
  47. "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
  48. 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
  49. nice blog
    Data Analytics Courses In Vadodara

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

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

    ReplyDelete
  52. 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
  53. 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
  54. This article is a goldmine of information. Thanks for the insights!

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

    ReplyDelete
  56. 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
  57. such a informative & well explained blog, a must read for python beginners like me.
    financial modelling course in melbourne

    ReplyDelete
  58. "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
  59. Thank you for providing the in depth explanation and information on the word Variable Scope.
    Digital Marketing Courses In Bhutan

    ReplyDelete
  60. 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

  61. "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
  62. 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
  63. 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
  64. chester bennington outfits often included edgy band tees, leather jackets, and layered accessories, reflecting his rockstar persona. His unique style combined casual wear with punk and grunge elements, making a lasting impression on fans.

    ReplyDelete
  65. This article is a great resource—concise, clear, and full of practical information. I’ve gained a lot from it, and I’m sure others will too. Thanks for writing and sharing this valuable content.
    Data Analytics Courses in Delhi

    ReplyDelete
  66. This is a fantastic resource! The tips you shared are practical and actionable. I’m excited to implement some of these ideas

    Data science courses in Gujarat

    ReplyDelete
  67. Superb learning on python. Want more info then come here at Data science courses in Jaipur

    ReplyDelete
  68. Great insights on variable scope! Understanding where and how variables can be accessed is fundamental to writing efficient and bug-free code.
    Data Science Courses in Singapore

    ReplyDelete
  69. Fantastic introduction to Python! Your guide makes it easy for beginners to dive into programming. I love how you’ve covered the essential tools and concepts without overwhelming the reader.
    Data Science Courses In Malviya Nagar ​

    ReplyDelete
  70. Never thought the variable scope can be this easy to understand. Good explanation on the python topic. And the example you have provided are very simple and understandable. thank for sharing.
    Online Data Science Course

    ReplyDelete
  71. Great introduction to variable scope in Python! Your clear explanations and examples make it easy to understand how different scopes affect variable accessibility. This is essential knowledge for anyone learning Python. Thanks for providing such a helpful resource!
    Data science courses in Dubai

    ReplyDelete
  72. Great explanation of variable scope! Your clear examples and step-by-step breakdown really help make this concept easier to grasp. Thanks for making tricky topics more approachable and understandable!
    cyber security internship for freshers | cyber security internship in chennai | ethical hacking internship | cloud computing internship | aws internship | ccna course in chennai | java internship online

    ReplyDelete
  73. Your passion for this subject really shines through in your writing.

    Data science courses in Mumbai

    ReplyDelete
  74. What an excellent article! Your insights are much appreciated, and I admire the effort behind this. It’s always refreshing to see varied viewpoints. Excited for future content!
    Data science courses in Bangalore

    ReplyDelete
  75. "The flexibility of IIM Skills' Data Science course made it perfect for studying remotely in Spain. The curriculum was well-balanced."
    Data science Courses in Spain

    ReplyDelete
  76. "Getting Started with Python" is an ideal course for beginners, covering essential programming concepts and syntax in an accessible way. Python's straightforward syntax makes it great for newcomers, while its versatility extends to data analysis, web development, and more. This course lays a solid foundation, making Python both approachable and practical for anyone interested in programming.
    Thank you for the post.
    Data science Courses in Germany

    ReplyDelete
  77. Hi blogger, I Read your blog about python, and I must say it is quite interesting. it is such a complex topic, but you made it look so easy.
    Data science courses in chennai

    ReplyDelete
  78. I found this blog incredibly informative. Your ability to make such intricate topics so digestible is impressive. Definitely learned something new today
    Data science courses in Bangalore

    ReplyDelete
  79. It was a good read and informative article on the subject of variable scope.
    Data science courses in Bangladesh

    ReplyDelete
  80. This post does a great job of explaining variable scope in Python, focusing on the difference between function scope and global scope. By using practical examples and step-by-step modifications Totally informative blog.
    Digital marketing courses in mumbai

    ReplyDelete
  81. Yes, I concur with the ideas and details you've provided here. I value your efforts, and I'm passing this along to others to aid in their work.
    Investment Banking Course

    ReplyDelete
  82. Clearly understand the point of Scope and its extremely valuable knowledge and helpful towards our work.
    IIM SKILLS Data Science Course Reviews

    ReplyDelete
  83. written very precisely and factually well, thanks for sharing.
    technical writing course

    ReplyDelete