Variables

Variables in Python Programming


Let’s learn all about Python Variables.

We will learn what variables are and how to use them in Python programs. We will also learn the common operations that we can performed on variables.

What are variables?

Variables are names given to some data or information that we want to store in computer programs. For example, our program wants to store the marks of a student. For that, we can declare the variable studentMarks using the following python statement.
studentMarks = 0

When we declare a variable studentMarks, python program will allocate some space in computer’s temporary memory. We can then access and modify this data by referring it’s name (studentMarks). Usually after declaring variable, we initialize it with some default value. In our case we have assigned 0 to studentMarks. We can always change this value in our program later as and when needed. 

A variable can have a short name (like x and y) or a more descriptive like (age, studentName, totalVolume).

We can also define multiple variables using single python statement as shown below:
rollNo, studentMarks, studentName = 101, 90, ‘KP’

Above statement is equivalent to following three statements:
rollNo = 101
studentMarks = 90
studentName = ‘KP’

Important Rules for Python variables

  • A variable name must start with a letter or the underscore character
  • A variable name cannot start with a number
  • A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
  • Variable names are case-sensitive (age, Age and AGE are three different variables)

In short, a variable name in Python can only contain letters (a – z, A – B), numbers (0-9) or underscores (_). However, the first character cannot be a number.

There are some reserved words that you cannot use as a variable name in your program as they already have some predefined meanings for Python interpreter. Some of the reserved words are print, while, for, input, if, etc. You can learn more about python reserved words here.

Examples of Valid Python Variable Names
studentName, student_name, studentName1, Name2, Age, age1

Examples Invalid Python Variable Names
1_name, 123, while, if, name@1, @123

There are two common conventions popular for naming a variable in Python: 
  • camel case notation and 
  • underscores notation. 

Camel case is the practice of writing multiple words as firstName, lastName (every upcoming words in variable is written using Uppercase). This is the convention that is popular in Object Oriented Programming like Java. Another common practice is to use underscores (_) to separate the multiple words. For example, you can also declare variables as: first_name, last_name.

* * * * *

Back to Home Page >

< Next Article : Python Numbers

No comments:

Post a Comment