Numbers, Strings and Variables in Python

Football is full of numbers, names, lists, teams and a million other ‘things’ that make up our understanding of what is happening.

In the same way, Python has lots of different ways of classifying things that it can understand. For example, it uses numbers to count, ‘strings’ for names and even has ways to group these things – like we would need for a league. This introductory post takes a look at a couple of these data types.

Numbers

As its simplest, Python is a calculator:

In [1]:
1+1
Out[1]:
2
In [2]:
10*2
Out[2]:
20
In [3]:
20/2
Out[3]:
10.0
In [4]:
# ** = to the power of
2**3
Out[4]:
8
In [5]:
5%2
Out[5]:
1

Variables

While a calculator is incredibly useful, we can give these numbers a name and a placeholder so that they are a bit more tangible and applicable to a problem. For example, if I want to keep track of our top scorer’s shots and goals:

In [6]:
Ronney_Goals = 15
Ronney_Shots = 63

I could now calculate Ronney’s conversion rate! Dividing goals by shots, I can see how many shots it takes him to score.

In [7]:
Ronney_Conversion = Ronney_Goals/Ronney_Shots
Ronney_Conversion
Out[7]:
0.23809523809523808

Strings

Now that Python has some interesting information on Ronney, it wants to share it with the world. As we can see above, sharing a number by itself doesn’t tell us a great deal. However, a string of text can give us a bit of context.

Surround a piece of text in quotation marks (be consistent with single or double quotes) to create a string:

In [8]:
"Ronney is truly a great player, his conversion rate speaks for itself."
Out[8]:
'Ronney is truly a great player, his conversion rate speaks for itself.'

…and let’s use the print() and str() commands to add the evidence to our commentator’s opinion.

In [9]:
print("His conversion rate of " + str(Ronney_Conversion) + " is sublime")
His conversion rate of 0.23809523809523808 is sublime

That is a bit specific, Merse, but I appreciate the information! Let’s take a look at those two commands:

print() – Python, please print everything that I put into the brackets. I might break up what I want to print with the ‘+’ symbol.

str() – You can’t print numbers? OK, then please consider this number as a string.

Summary

In this introductory post, we have seen that Python can be used as a calculator at its very simplest. However, we have seen that we can make it a bit more useful with variables, even using a variable to help our commentator give a great bit of insight, combining it with a string.

We even saw a couple of commands with print() and str().

Next up, take a look at how we compare and evaluate this information in Python to make decisions with our code.