INTERACTIVE ONLINE COURSE

Python 3

FOR BEGINNERS


"The first Python course that simply amazed me. Very well explained and easy to understand." (Alexandru Cosmin)

"The best Python course in Romania." (Iulian Geană)


ALL REVIEWS
LESSON 19
PAGE 1 / 4
Variable Visibility
Home >>> Online Lessons, Python 3

Which Mihai?

Two siblings, Daniela and Radu, are talking at lunch at home:
- Did you see the cool hoodie Mihai had today? I really liked it, said Daniela.
- Come on, I met him on the street, he was wearing a T-shirt and jumping with his bike in front of the house!
- Really, Radu? He was also in the hallway today in front of 8B... never mind. It's warmer now.
- Which Mihai?!?, asked Radu, puzzled.
- Mihai from 7C, what's up with you?
- Oh... I thought it was Mihai from the top of the street. He was doing some cool tricks earlier...
- Oh... you and your friends!



There may be several Mihais in our lives, different - obviously, just like the variables in your programs! We need to know exactly which one we're talking about so that the conversation or program makes sense.

Local and Global Variables

Below, I created a variable x and assigned it the integer value 6. Then I defined a function called inc, hoping that x would be incremented by one, but the result might be surprising for some of you!
Editor - lesson_19.py
       
Console/Output done
DETAILS

Where did I go wrong? I do have a vague suspicion... previously, I mentioned that functions have their own variables, called local variables, which cannot be accessed from outside.

The parameter, namely the variable x in the function body and header, is a completely different object from the other x in the program after assignment, so it is not recognized outside the function!

How can we solve the problem then? Sometimes we need to modify the content of variables from outside the body of our functions...
Advance to the next page.
 home   list  CONTENTS   perm_identity   arrow_upward