Variables in Python are declared on first use.
Variable names in Python must:
- Start with a letter or an underscore character
- Not start with a number
- Only contain alpha-numeric characters and underscores (A-Z,a-z, 0-9 and _)
- Be case sensitive (ex. name and Name are different variables)
Good variable names
apple b_funky _tester
The underscore as the first character usually indicates that the function is for internal use. This convention is mentioned in PEP 8.
Bad variable names
8million $dog +happy
The scope of a Python variable depends where it is defined.
If it defined outside of any function or class, then that variable is global. This means that all functions can access that variable.
some_var= "Eric"
If it is defined within a class or function, than that variable is considered to have local scope.
def print_name(name): greeting = "Good Morning," print(greeting,name)
The variable some_var is global and can be used throughout the program, but the variables name and greeting are local to the function and are not available outside of the function.
Tags: Python