Python Variables

In programming languages, variables are containers for holding data of various types for processing. The rules for declaring and using variables slightly vary from language to language but there is a general sense of similarity in the rules e.g. global variables vs local variables,naming conventions.Some of the differences may include variable reassignment rules e.g. in Java whereby a variable declared as int cannot be used to hold strings in the same program whereas in Python,a variable can hold an int and later hold a string in the same program.

Let’s dive and learn more on variables in Python;variables declaration and  assignment,naming conventions,global vs local variables in Python,nonlocal variables,variable types,reserved words

Variable declaration and assignment

In Python, we do not need to declare variables before using them. In languages like Java, a variable type and name has to be declared before the variable can be used. In Python, the variable is created the moment you assign a value to it. You also do not need to give the variable type. As such, Python is a ‘dynamically typed’ language-variable type is assigned at runtime depending on the variables value at that point in time.

When the above program is run,the output is as below

Python Variable Naming conventions

Like in most programming languages,Python defines some rules when naming variables to avoid errors.

  1. Variables can only start with a letter (a-z), (A-Z) or underscore (_).They cannot begin with a number.
  2. If a variable is made up more than one word,there are 3 ways of naming it
    • Snake case-This uses underscore(s) to connect the various words e.g student_name
    • Camel case-except for the first word, subsequent words begin with a capital letter e.g studentName,dateOfBirth
    • Pascal case-all words begin with a capital letter e.g. StudentName,DateOfBirth
  3. Variables cannot be named after python reserved words e.g. for,from,break,class,finally,as,assert,except,with,yield e.t.c. or Python’s built in functions e.g.bytes(),chr(),float(),help(),id(),pow() e.t.c.

Tips for good variable naming

  • Variable names should be descriptive of their purpose.E.g. file_size if more descriptive than

Next,we look at global and local variables in Python.

About the Author - John Kyalo Mbindyo(Bsc Computer Science) is a Senior Application Developer currently working at NCBA Bank Group,Nairobi- Kenya.He is passionate about making programming tutorials and sharing his knowledge with other software engineers across the globe. You can learn more about him and follow him on  Github.