Variables And Numeric Data Types In Python

avatar

This is number 5 in the series of posts we have put together introducing Python as a development language. Feel free to head back to our previous posts to get started with some of the more basics in the Python language:
https://stemgeeks.net/hive-163521/@run.vince.run/manipulating-text-files-and-strings-in-beginner-python
https://stemgeeks.net/hive-163521/@run.vince.run/running-your-python-code

Introducing Variables


So far in the series of posts we've limited the use of Variables within our code. Not for any specific reason other than we wanted to introduce them properly in a separate post. In the simplest terms a Variable is a container for storing data.

Python has no specific command for declaring a variable, with the variable being created at the moment you assign a value to it. We assign the value to the variable using a single equal sign(=) with the variable name being equal to the value assigned on the right side of the equal sign.

In the example below, we create the variable named variable_name and assign it a string value of "variable value".

variable_name = "variable value" 

The name of a variable is usually something descriptive of what is being stored in the variable, for example:

>>> cats_name = "Rusty"
>>> cats_age = "two"

To change the value of the variable, all we need to do is reassign the value using the equal sign again. For example, if our cat is one year older, we can change the value as we have below. You will also notice that we first stored a string in the variable named cats_age, we then decided to change this to an integer, and Python allows us to do this without any errors, it will know what type of data is being stored without the programmer needing to let it know.

>>> cats_age = "three"  # this is a string
>>> cats_age = 3           # this is an integer

We can then use these variables in our code like the print() function we have used below. As you can see before we print out a statement using our variables, we can use the type() function to see what type of data the variables are holding:

>>> print(type(cats_name))
<class 'str'>
>>> print(type(cats_age))
<class 'int'>
>>> print("My cats name is {} and he is {} years old".format(cats_name, cats_age))
My cats name is Rusty and he is 3 years old

As we mentioned earlier, variable names should be descriptive but there will be situations when you will try to limit the amount of characters you are typing with your variable name only being a single character like an x or a y. This is valid in Python, with the only rules for variable names being:

  • It must start with either a letter or an underscore
  • It cannot start with a number
  • Variables can only container alpha-numeric characters and underscores
  • Variable names are also case sensitive, eg; apple and Apple are different variables.

Our variables will be removed as soon as our program stops as it is stored in in your systems RAM. Another way to make sure we can hold onto variables for longer is by using files again as we did in our last post. You'll notice one thing though, when we use the f.write() function to write our variable to a file, we need to enclose our variable name in the str() function. This is because we can only write strings to files. The str() function can be used to change an interger to a string, and the int() function can be used to change a string to an integer.

>>> my_savings = 500

>>> f = open("savings.txt","w")
>>> f.write(str(my_savings))
>>> f.close()

Now getting the data back into a variable, we can use the following:

>>> f = open("savings.txt", "r")
>>> savings_from_file = f.read()
>>> f.close()

>>> print("I have saved ${} so far this year".format(savings_from_file)
I have saved $500 so far this year

Introducing Numeric Data Types


We've seen previously that strings are basically anything in between quote marks. Numeric datatypes on the other hand are not placed in between quotes. If they were, they would be strings.

>>> print(type(5))
<class 'int'>
>>> print(type("5"))
<class 'str'>

Numeric data types aren't too complex but there are a few things you need to keep in mind when you are using them.

Int


These are made up of numbers with digits from 0 to 9 and can be either positive(+) or negative(-). Examples of int data type are:

>>> print(5)
5
>>> print(-5)
-5
>>> print(+5)
5

Float


A float or floating point number includes numbers with decimal points and also supports exponential values. Python will actually convert very small numbers into exponential values automatically. Here are some examples:

>>> type(5.4)
<class 'float'>
>>> print(0.000000000000000000000000456)
4.56e-25

Arithmetic Operators


Just as we can use numbers in our code we can also perform operations on our numbers, which include addition(+), subtraction(-), multiplication(), to the power of(*), divided by(/) and modulus(%).

Operator precedence follows the usual flow where:

  • Brackets
  • Of
  • Multiplication and Devision
  • Addition and Subtraction

Simple Program To Display Savings


Earlier in this post we used the interactive shell to get the details from a file. Instead of needing to type these commands by hand every time we wanted to know our savings, we can instead create a program that gives us the information every time we want to use this information. Perform the steps below to create the check_savings program.

  1. Create the new program file called check_savings.py
echo "" > check_savings.py
  1. Add in the following details, but don't include the line numbers at the start of each line. This is just for reference and expaination. Line one tells the script where to find Python in our system. The rest of the lines should looks pretty familiar to you by now. Line 3 will open the savings.txt file we created earlier and allow us to read the contents. We then create a variable called savings_from_file and add the details from the contents of the file using the read() function. We close of the file object and then using the print() function we print out a nicely formatted sentence of what is in our savings.
 1  #!/usr/bin/env python
 2
 3  f = open("savings.txt", "r")
 4  savings_from_file = f.read()
 5  f.close()
 6  
 7  print("I have saved ${} so far this year".format(savings_from_file))
  1. To now run our program, you simply need to be in the directory our file is located and run the following. Even though we have used the .py extension we need to let shell know we are using Python to run this program, so before we call the program file, we start with python3 and then the program file name. If everything has worked correctly, you should then see the output below.
python3 check_savings.py
I have saved $500 so far this year

If you've been following from the start, we took our time to set things up but now we are moving a lot quicker through our code and hopefully introducing you to a lot of new functionality. We should be able in another week with some more progress on getting user input and improving our programs further.

Posted with STEMGeeks



0
0
0.000
8 comments
avatar

I love that Python is so flexible, but you do need to watch out for the types of your variables. I have played around with things like prime numbers and it it helps that integers can be as long as you like. In out languages they tend to be limited.

I fairly recent feature I like is 'f' strings so you can simplify

print("My cats name is {} and he is {} years old".format(cats_name, cats_age))

to

print(f"My cats name is {cats_name} and he is {cats_age} years old")
0
0
0.000
avatar

Thanks for that @steevc . My goal this year is to be 100% proficient with Python and be confident in calling myself a Python programmer. So any suggestions you have I will take on and f string are something I have seen and will have to do an indepth post on.
Thanks again.

0
0
0.000
avatar

I'm doing some Python for work, so I keep picking up things. I expect posts on lists and other collections are planned by you.

0
0
0.000
avatar

Very informative. You explained variable and types in very easy way. Good python basics post.

0
0
0.000