Python Programming for Beginners Lesson 1
Numbers and Variables in Python
A Brief Overview of Python
Python is an interpreted, high-level, general-purpose programming language. Created by Guido van Rossum and first released in 1991, Python’s design philosophy emphasizes code readability with its notable use of significant whitespace. Its language constructs and object oriented approach aim to help programmers write clear, logical code for small and large-scale projects.
Python is dynamically typed and garbage-collected. It supports multiple programming paradigms, including structured (particularly, procedural), object-oriented, and functional programming. Python is often described as a “batteries included” language due to its comprehensive standard library.
Python was conceived in the late 1980s as a successor to the ABC language. Python 2.0, released in 2000, introduced features like list comprehensions and a garbage collection system with reference counting.
Python 3.0, released in 2008, was a major revision of the language that is not completely backward-compatible, and much Python 2 code does not run unmodified on Python 3.
The Python 2 language was officially discontinued in 2020 (first planned for 2015), and “Python 2.7.18 is the last Python 2.7 release and therefore the last Python 2 release.” No more security patches or other improvements will be released for it. With Python 2’s end-of-life, only Python 3.5.xand later are supported.
Python interpreters are available for many operating systems. A global community of programmers develops and maintains CPython, a free and open-source reference implementation. A non-profit organization, the Python Software Foundation, manages and directs resources for Python and CPython development.
Variables – Boxes to store our data
So the first question that comes to mind is – Why do we need to use variables at all? We can simply do something like (2 + 2), (3 + 5) or (8 * -2) in order to do numerical computations in the Python shell itself, just like in the image below.
Here the + denotes addition, – denotes subtraction, / denotes division and * denotes multiplication in Python. Python also provides another operator denoted by %, which stands for the modulus operation which essentially returns us the remainder of a division operation. Say for example if I do 5 % 2 then I will get the result 1 since 5 when divided by 2 leaves 1 as a remainder.
We can continue doing calculations like the way shown in the image above by using the Python shell, but doing so will lead to cumbersome copying and pasting of repeated numerical calculations, manually typing in large mathematical expressions and so on, which can get very tiresome easily.
That is why Python has provided us with variables, which are nothing but little boxes in which we can store our numbers and then we can keep using these variables repeatedly in our calculations instead of having to type in the numbers manually everytime.
A number, string, character or any other type of data can be stored in a variable using something like number = 1. This will store the value 1 in the variable called „number‟. Note that variables are case sensitive, so if I type “NUMBER” instead of “number” then Python will return an error since they are not the same variable. To check the data type that the variable contains we can use the “type” operator. The “type” operator will return whether the information stored in our variable is an integer, a decimal number or a string and so on. For example doing type(number) will return “int” since 1 is an integer.
Note that we can also store a string in a variable called “number” by doing something like number = “hello”. Python doesn‟t care what our variable name is, we can name our variable as “number” and still keep a string or a line of text in it because Python is a dynamically typed language i.e. Python automatically knows what is the data type of the value that we are storing in our variable. In this case Python automatically recognizes that even though the variable is named as “number” the data type of the data that is stored in it in the expression number = “hello” is a string. We can confirm this again by using the type() operator, as doing type(number) this time will return the class „str‟ which stands for string.
Let‟s now update our script by using variables. Let‟s say we store the value of 1 + 1 in a variable called first_number by doing “first_number” = 1 + 1. Secondly, let‟s store the value of 105 + 10 in a variable called “second_number”. Now let‟s add both the values up and store them in a variable called “total” by doing total = first_number + second_number and print the output to our Python shell by doing print(total). We can also print the values stored in “first_number” and “second_number” by doing print(first_number) and print(second_number). Save the script by giving it a suitable name of your choice and then once you run the script you will see that it outputs the values 2, 115 and 117 for the first_number, second_number and the total variable. Do you see the advantage now? Now instead of going over to the Python Shell and manually changing or typing in the values everytime we want to do a new calculation, we can simply
change the values that we are storing in our variables first_number and second_number, run the script and let Python do the rest of the things for us. As can be seen, we can save a huge amount of time by simply making the use of variables in our Python programs.
Mathematical Operations in Python
Python provides us with all the tools for doing basic mathematical operations. Using + we can do addition, – for subtraction, * for multiplication and / for division. It also provides us another operator called the “modulo operator” denoted by %. The modulo operator returns the remainder when a number is divided by another number. So if I do 5 % 2, then I will get 1 as the output as 5 when divided by 2 leaves 1 as a remainder. The figure below will display an example of the various sorts of mathematical operations that you can do with Python. Once again, we can use the type() operator to determine the data type of the output.
One key thing to keep in mind here is that division in Python always returns floats, which are essentially nothing but decimal numbers. So if I do 2/4 in Python then I will get 0.5, if I do 4/2 then I will get 2.0 instead of just 2. To check the datatype we can do type(0.5) and this will return the class “float”.
However we have to keep in mind that while doing any numerical computation, we always have to follow certain rules so that output of our calculations are always correct and consistent. Let‟s say you wanted to calculate the output 2 * 5 – 1. You may be expecting an answer 8 here since 5-1 = 4 and multiply that with 2 gives 8. However the answer in this case is 9, because multiplication ends up taking more preference instead of subtraction according to the BODMAS rule whose full form is shown below:
As can be seen from the figure above, brackets get the highest preference, followed by order which is nothing but exponentiation i.e. squaring, cubing etc. followed by division, multiplication, addition and subtraction. So for our last example 2 * 5 – 1, we got the output as 9 because multiplication part was solved first and then subtraction, which gets the lowest preference. If we want the answer as 8, we can do something like 2 * (5 – 1) and this time we shall get the answer as 8 since the part which is inside the brackets i.e. 5 – 1 will be solved first compared to multiplication since brackets have a higher preference according to the BODMAS rule. So (5 – 1) will give us 4 and multiply that with 2 gives us 8. Whenever in doubt, always use brackets to simplify your mathematical expression and get accurate, consistent results.
Project – Creating a Health Potion (Part 1)
In the first part, we shall create a project whereby we have a character that has a certain amount of health, let‟s say 50 and then we shall add a random amount of health to this character using Python‟s inbuilt random module. To do this we simply have to do import random first. This will load Python‟s inbuilt random module. Then create a new variable called health and assign it the vale 50 by doing health = 50. Then create a new variable called potion_health and assign it any random value between 25 and 50 (both inclusive). This can be done by using the builtin randint function of the random module which will return a random integer in the range that we specify it. So we can do something like potion_health = random.randint(25, 50). Next we shall add this potion_health variable to the original health of our character by doing health = health + potion_health. Finally we display the total health of our character after he consumed the potion by doing print(health). The entire code can be visualized in the figure below:
As can be seen our player got an additional health boost of 36 points after drinking the potion since his new health is 86 compared to his original health of 50. Next up, we shall add a difficulty system, with 3 levels of difficulty. 1 will be the easiest difficulty, 2 will medium and 3 will be the hardest difficulty level.
Project – Creating a Health Potion (Part 2)
In this section, everything else remains the same as the previous code, we shall just be adding a difficulty value. For now let‟s keep the difficulty at medium since we are all new players and don‟t want too much of a tough time. We can do this by creating a new variable called difficulty and assign it the value 2 i.e. difficulty = 2. Then we can do something like potion_health = random.randint(25 ,50) / difficulty. This will reduce the amount of health our player gets by a factor of 2 now since the difficulty level has been raised. Finally we add the potion_health to our original health just as before and we get the answer this time as 71.0, which is not an integer but a float. This happens because Python always returns a float in division operations. If you want an integer then you have to typecast it to be an integer which is nothing but telling Python, “Hey I don‟t want a float value. Please give me an integer value”. You can achieve this by writing the code as follows: potion_health = int(random.randint(25, 50) / difficulty). Now this will return us the result 71 which is an integer, instead of 71.0. Do keep in mind that you may get a different answer compared to 66 but that is because Python will keep generating random integers using random.randint() and add that to our original health. The entire code can be found below:
So that wraps up everything that you need to know about numbers, mathematical operations and variables in Python. If you ever get stuck in some code or can‟t seem to figure out a concept, then you can always come back and refer to this guide.
Numbers and Variables in Python