Python Variables

·

3 min read

Variables are simply containers for storing data values. Think of it like a jug of milk. The jug is the container and the data value is the milk stored inside the container.

Some examples of the simple variable are shown below:

x = 10

batman = "Bruce Wayne"

Step 1

Open your code editor and type the below code.

Step 2

Print the program and the output should appear in the "Output" window as seen below.

Variables can even change after they have been set. For example, you can change the Batman variable and set it to Dick Grayson (he has replaced Bruce Wayne as Batman in the comics). Let's change it and see what happens.

Changing variables

Step 1

Step 2

It is generally a good practice to avoid having variables with the same name in the same scope, as this can lead to confusion and errors in your program. When two or more variables have the same name, it becomes difficult to keep track of which variable is being used at a particular point in the program.

Casting

It is the process of converting a variable from one data type to another.

Step 1

Step 2

Your "output" window should look like the below image.

Now, let's combine everything we have learned and come up with a nice sentence using variables.

Combining what we have learned

Step 1

Type the following variables in your editor

Step 2

In Python, an f-string is a way to create a string containing variable values that you can insert into the string.

For example, if you have a variable called name that stores the value "Bruce Wayne" and wants to create a string that says "Hello, Bruce Wayne", you can use an f-string to combine the variable with the string. The syntax for an f-string is to start the string with the letter "f", and then use curly braces {} to enclose the name of the variable you want to insert into the string.

The f-string for the example I gave earlier would be f"Hello, {name}". When Python evaluates this f-string, it replaces the curly braces and the variable name inside them with the variable's actual value, resulting in the final string "Hello, Bruce Wayne".

Create a new variable called combined_string as follows.

Step 3

Your editor should have the below program. Print the program.

Step 4

Your "output" window should have the below result.

Of course, variables become more complicated in the long run but what has been accomplished today is the first step to learning Python. In the next article, we shall cover if-else statements. Stay tuned.