Skip to main content

Variables and Data Types

Introduction to Variables

Let'To start, let's create a new Python file called variables"variables." This can be done by againgoing to the project tool window on the left-hand side and right-clicking on your "first-pycharm-projectproject" andfolder. clickingFrom onhwere Newyou can then select "New" > "Python file." LikeJust like before, we'you'll enterneed to specify the desired namefilename in the window that popsappears. up.In Ithis havecase, chosenI've gone with the name variables.pypy..

Now withWith our blanknewly created variables.py file we can beginnow todelve learninto whatthe variablesceoncept areof about.variables.

Why Use Variables?

Python can be used as a calculator as it allows us to perform calculators with whole-numbers. In programming, we refer to these whole-number values as integers or ints.

Let'sConsider saya webasic wanttask: to use Python to addadding two whole-numbers.whole Trynumbers using Python. You can achieve this by entering the following code ininto your "variables.pypy" file and running it.it:

print(1 + 1)

As you'd expect,expected, Python tells us that 1 + 1 gives a result of 2.

one-plus-one-print.png

However, rather than simply print of such values once, weyou may want to store the results ofuse a certain value more complexthan calculationonce. soIt thatis itoften canuseful beto usedstore ordata modifiedin later.our code for repeated use. This is whenwhere wethe wouldconcept use something called aof variablevariables. comes into play.

What Are Variables?

In the world of programming, variables are like containers that hold information. Imagine them as labeled boxes where you can store different types of data. This data could be numbers, words, sentences, or anythingsomething else your program needs to work with.

Variables allow you to give a name to a piece of data, making your code more readable and organised.

Variable Assignment

To put data into a variable, we use the assignment operator =. Now we can find a sum of two integers andlike thenwe storedid before, except this time we are storing the result.result so that it can be accessed again.

my_sum = 1 + 1

ButWe have now created a box with the label my_sum that contains an integer of the value 2. Now we can display this aloneby won't display the result when we run the program. In order to this we will use another print() statement, but give itgiving our my_sum variable.variable to the print() command.

PutWhen together,combined, we get the followingthese two lines of code:code appear as follows:

sum-with-variable.png

Naming Variables

Python hasenforces specific rules aboutfor naming variables. Variable names canmust startbegin with a letter or an underscore (_) and can be followed by letters, numbers, or underscores. However, they can'tcannot startbegin with a number or contain spaces or special characters.

Self-Documenting Code

It's also a good idea to make sure your variable names are clear and meanginful. For example, recipe_name or ingredient_count are good variable names, as they help us understand what a variable is for and what a bit of code is doing.

Let's take the example of code used for finding the area for a rectangle:

a = x * y
print(a)

rectangle_area = width * length
print(rectangle_area)

While bothBoth code snippets are doingaccomplish the same thing,task, understanding whatbut the second bit of code is forone requires less mental effort thanto understandingunderstand whatits the first bit of code is for.purpose. This is somethingan toimportant considerconsideration when writing code and choosingselecting variable names.

When you writechoose names in your code that essentiallymake it more "explains itself,self-explanatory," weit callis thisoften writingreferred to as self-documenting code. This is a very good habit to pick up.

Reserved Words

ItAvoid is also not advisable to giveusing variable names that arecoincide alsowith reserved words in Python. InPython Python,reserves certain key words suchkeywords such as while,while, for,for, if,if, else,else, import,import, exit,exit, and others.others for its built-in functions and tools. By using these keywords for variables, we are in a sense "confusing" Python, as it no longer knows where to find the built-in tools that are associated with those names. This is almost guaranteed to make your program misbehave.

TakeFor example, consider the use of print. In Python, print foris example. We use this in Pythonused to indicatedisplay we want something to see outputdata from our program.code in the console or terminal. Let's see what happens ifwhen I instead use this for a variable name, and then try towe use print as a variable name and then attempt to use the print as a command again afterwards.later:

You'll see that print on line four now has a squiggly line beneath it. Moving the cursor over the print on line 4 gives us a pop-up message. ???

ThisNotice that on line 4, print is onehighlighted ofdifferently thecompared otherto usefulhow featuresit ofis IDEs.highlighted Hereon it'sline telling2. usThe print on line 4 also has a squggly line beneath it. Hovering over it provides a pop-up message indicating that the built-in print command print is being "shadowed" by something else. Likewise, puttingplacing the mouse-cursor over the command on line 5five showsgenerates another pop-up message.message, indicating that int objects are not callable. These are some of the indications that IDEs give us that let us know we may have done something wrong in the code.

This time we're being told that certain things that are "callable" in Python, but that int objects are not these things. This should make sense later.

Now when we run it we get the following output:

/home/dolica/mambaforge/envs/first-pycharm-project/bin/python /home/dolica/PycharmProjects/first-pycharm-project/variables.py 
2
Traceback (most recent call last):
  File "/home/dolica/PycharmProjects/first-pycharm-project/variables.py", line 5, in <module>
    print(my_sum)
TypeError: 'int' object is not callable

Process finished with exit code 1

On the first line, we have two paths. The first is the path to a particular version of Python that is being used specifically for our first-pycharm-project. The second path is the file that was run with this version of Python -- the variables.py file that we have just created.

After this, we see the number 2. This is the output created by the second line in our code, as Python was able to get to that point without any problems.

However, further down we get an error. The Run pane tells us that on Line 5 we attempted to treat an int as a Callable when it is not one. It even shows us that the command on that line we used was print(my_name).

While this is the exact same command that was used on Line 2, we have confused Python by replacing what it typically stores in the print box with something else. ANother incidcator of this is that the first print is highlighted differently while the second and third ones aren't.

Remeber: When you deal with errors the first thing you should do is identify the file and line that it is coming from. If you have any output before an error, that's an indication that the program was still running at least part of the way through.

We can fix this by using a different variable name for our other number.

Now the squiggly lines have disappeared. ANother indication that the issue has been fixed is that the second print command now has the same highlighting as the first one. Now let's examine the pop-up messages again.

reserved-word-fix.gif

The first pop-up message simply tells us we have a variable of the type int with a value of 1234.

The second pop-up message shows us some information about how to use the print command. This is another handy feature of IDEs -- showing us how commands work without having to go to its decleration or the documentation. Chances are you won't use any of the "advanced" features of print and will simply stick to using it with basic data.

Now you should understand why reserved words should not be used for naming variables.

Reusing Variables

Variables can hold different values over time. If you later find out you need 12 ingredients for the cake, you can simply change the value:

ingredient_count = 12

No need to create a new variable; the old one updates with the new value.

Dynamic Nature of Variables

Unlike some other programming languages, Python is dynamically typed. This means you don't have to specify the type of data a variable will hold. Python figures it out on its own.

Example: Storing a Name

Let's see a quick example. We can use a variable to store a person's name:

name = "Alice"

Now the variable name contains the string "Alice". You can use this variable to display the name or manipulate it in various ways.