We will learn about variables today.
Let’s see it by an example :
What does the above line mean? It means that we are assigning a value of 1 to ‘a’. Here a is a variable. It can be anything, but for now, its value is 1.
There is a print command in python. It is used to print anything you like to show in command line or terminal. You can print numbers, patterns, strings like your name, last name, designation, etc.
Now, for variables, we can do something like,
Here, you can see, value of a was 1, and then we used print command to show its value. Then, we changed it’s value to a string ‘hello’, and it became ‘hello’.
This is how variables work. They change their appearance around our instructions.
Here, we can also see print command can also be used to do calculation operations, and other type on operation like concatenation ( joining ) of strings.
Unlike other programming languages, Python has no command for declaring a variable. A variable is created the moment you first assign a value to it.
Let’s make a program today for swapping two numbers to understand more about variables,
Let a=5 and b=3, we want a to become 3 and b to become 5 after some sets of operation.
How can we do this?
If we write a=3, then the number 5 will get lost.
So to avoid that, what we can do is, let’s introduce another variable c,
c = a ( we assigned value of a into c, so now c = 5 )
a = b ( Now we changed value of a to b, without losing value of a as it is stored in our new variable c, So now, a=3 )
b = c ( Now, assign value of c to b, So now, b=5 )
So, here by adding only 3 instructions we made two variables swap their values.
Tips for naming a variable (naming convention):
Usually programmers at a beginning stage start naming variables as a, b, i, j, k, x, y but this is not the correct way to name a variable. It’s because when you will start writing your own programs and come back to refer your code after some time, you might face difficulty to analyse what that variable is used for. So, it’s in best practices to name your variable which somehow reflects its use.
For example, we can write a=’Piyush’ but this doesn’t give me a sense as to what a is. If I write it as name=’Piyush’ , now we know that name variable is used to store different names.
A variable can have a short name (like x and y) or a more descriptive name (age, username, total_volume).
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 (name, Name and NAME are three different variables)
That’s it for today.
You guys have fun playing with variables. Try and experiment with what you learned today, so that you can learn more. If you get stuck at something, I am always available to help.