Python for Beginners 04: Basic Types in Python

After two more theoretical posts on comments and programming principles, it is time to practice a bit more.


What are we going to learn?

The basic data types that are used in Python, when to use which one and why distinguishing them is important.


What do you need (to know)?

Nothing. You don’t even have to read the previous posts on calculations, comments, or the principles of Python. You just need a program that can execute Python code such as Thonny.


Before we get started with practicing, we need a quick introduction to the types of data used in Python. Basically, there are three groups of variables:

a) numeric variables = numbers

  • without decimals → integer implemented with the function int() [you probably remember them from the previous posts]
  • with decimals → floating-point numbers implemented with the function float()

b) alphanumeric variables: numbers, letters and other symbols

  • a single character → not really useful
  • sequences of character data strings → strings implemented with the function str()

c) variables of Boolean data type: may have one of two values, True or False
(Attention: make sure it starts with a capital letter)

The variable type matters because it decides which operations you can execute with your code. Add two numbers, for instance 26 and 9, as strings (a), one as string and the other as integer (b), and both as integers (c). What are the results?

If you add two number that are formatted as strings (standard option when you get them as an input from a user), you just get the two numbers combined as a result (a). If you want to get the sum, both numbers need to be numeric variables, so either integer or float (c). In this case, the integer type is enough, but you might as well format both as float. What is important is that the variables you want to do operations with are from the same group. Otherwise, you will get an error message (b).

Did you notice how I used comments to explain what I am doing and to prevent the code in a) and b) from executing, also to avoid the error message from b)?

Boolean variables are useful to evaluate whether an expression is true or not. You can just use the function bool(), write some expression in brackets and when executing the code, the result will be either True and False. Try it yourself in Python: If a = 4 and b = 5, are the following three expressions true or false?

d) a > 9
e) a < (3+b)
f) (90-b) <= a

Did you remember that Python will only display the result if you print it? This means, of course, that you have to save the result in a variable before. Lesson 5 will focus entirely on output, so don’t worry if it is still challenging for you.

A final piece of advice: If you don’t know what type of variable you are using, you can always use the function type() and just write the name of the variable inside the brackets. Python will give you the answer using the term class and indicating Python’s abbreviation of the data type, i.e. the one that you use to define a variable’s type.

Congratulations! You have mastered lesson 4! #mastery04

Python for Beginners 03: The Zen of Python

When learning a programing language, it makes sense to know about its background and its design principles. For Python, you should have a look at the Zen of Python. You can find them either on the Internet or it appears if you run import this (This kind of hidden joke is called “Easter egg”).

I am not going to give you a full explanation of each guideline, as there are many good ones on the Internet, but I am going to mention those who are most relevant for beginners or attention-grabbing.

From my understanding, many of the principles, in particular those 2-7, boil down to one key guideline: “keep it simple, but not at the expense of clarity”. The goal is to write code that can be understood, at a later point in time or by you. This is also the motivation behind comments. The combination of the principles 3. Simple is better than complex. and 4. Complex is better than complicated., shows that their creator was aware that not everything you develop will be easy and thus recommends not to sacrifice understandability for simplicity.

The principles 8. Special cases aren’t special enough to break the rules. and 9. Although practicality beats purity. are equally relevant for beginners and experts. Taken together, they recommend that you should stick to the “best practices” like simplicity and clarity, but again keep in mind that the purpose is improving your program, not following the rules.

The principles 13. There should be one– and preferably only one –obvious way to do it. and 14. Although that way may not be obvious at first unless you’re Dutch. are insider jokes. The first one points to the Perl programming language that prides itself of having many ways of solving the same problem, but this does also create confusion and additional work if you need to learn various possibilities. Python wants to avoid this, but of course there are exceptions. The allusion to being “Dutch” refers to the nationality of the creator of Python, Guido van Rosum.

In my opinion, knowing all of this gives you a good first idea of what the Zen of Python is about. Needless to say, if you are interested and as you are getting more and more involved with programming, I highly recommend to read them all and, of course, see what other people’s interpretations are.

Finally, you may think that it is kind of random to have 19 design principle and that having 20 would have been much more logical. There are some rumors that the writer of the principles, Tim Peters, wanted to leave the final one to the creator of Python, Guido van Rosum, whereas other sources say it is “some bizarre in-joke”. Whatever may be the truth, fact is that there is no 20th principle written down so far so there is a lot of speculation.

#mastery03

Python for Beginners 02: Just a Comment

If you want to make a clarification or explain something, you can write a comment in Python. If you start the line with a hashtag # or three apostrophes ‘‘‘, Python knows that this is not part of your code and does not execute it.


What do you need comments for?

Look at this code without any comments.

Do you understand what it is supposed to mean? It is less than 10 lines of code.

Now look at this code with some explanations.

Basically, comments are just supposed to make your life easier for when you try to understand your code later on and of course for others who might need to look at your code.


When to use which type of comment?

You may have noticed that Thonny fades out comments started by # and displays comments between ”’ in green (like text). This is not the only difference between them.

#: valid for the rest of the line

  • advantage: only one symbol necessary
  • disadvantage: automatically blocks out the rest of the line; if necessary, you need to repeat it in the next line

‘’’ [text] ‘’’: valid until closed

  • advantage: you determine the start and the end (works in the middle of a line and for multiple lines)
  • disadvantage: you need three symbols each time (if you forget one, it will not work); you need to close it

In general, I agree with the website Python for Beginners – very useful, by the way – that recommends to think “of the first type as a comment for yourself, and the second as a comment for others”.

So from now on, just add comments to your code whenever necessary! #mastery02

Python for Beginners 01: How to Write a Simple Program (No Previous Knowledge or Theory Required)


What are we going to learn?

How to create a Python3 program that asks the user for two integer values and does some simple calculations with it (sum, difference, product, division).


What do you need to know beforehand?

Nothing. However, you do need to install a tool if you want to run the program, for instance Thonny (free, self-explanatory download and easy to use).


2 pieces of advice before we start:

  • Write your code (= the instructions) step by step and try it out by running it (press F5).
  • If there is an error, check brackets, quotation marks etc. and use Thonny’s assistant function (appears automatically). The debugger even points out the exact location of the error with a small ^ below it.

0. Install your tool (e.g. Thonny) and open it.

The larger empty field, where the cursor is, is called the editor where you can write instructions. The smaller empty field below is the console where you can see the result if you execute your instructions using F5.

1. Ask the user for an integer value, which is a number without any decimal points etc.

In the editor: We define a variable in which we store the number we get it: We choose a name, meaningful at best, like number1, and tell Thonny that we want to define it by using =. With the function input(), we set our variable equal to whatever is written into the console. Inside the brackets (), we can write an explanation for the user what he/she should write, but it needs to be in quotation marks.

In the console: Press F5 and you will be asked to type in a number. Do it.

If you want to see your result, you write the function print() in the editor and put your variable’s name in the brackets (). If you press F5, your number will appear in the console.

2. Ask the user for another integer value.

Repeat the process from 1. Unless you type in the first number required, you will not see any difference in the console. I use the example of 24 and 789 here.

You may notice that every time you press F5, the console runs the code (= your instructions) from the beginning.

3. Use those two values to make some calculations.

So far, we have only saved the integer values as the data type string (= text). Before we can do calculations, we need to change both variables by adding the function int() around each definition. This converts each one to an integer (= number) that we can use to make calculations.

a) Calculate the sum of the two numbers.

Just write the names of the two variables with a +, but put each name inside the function int(). This is necessary so Thonny knows that it is supposed to work with integers (= numbers) and not strings (text).

Don’t forget: If you want to see the result, you need to use the function print(), either putting it around everything or defining an additional variable as the sum and printing this one.

You can add a description such as “sum: “ beforehand if you want to, but remember to put it in quotation marks and you are going to have to add a comma to separate it from the calculation.

b) Calculate the difference of the two numbers.

Do the same as in a), but exchange the + for a -.

c) Calculate the product of the two numbers.

Do the same as in a), but exchange the + for a *.

d) Calculate the integer-based division of the two numbers (so no decimal point).

Do the same as in a), but exchange the + for a /.

e) Calculate the remainder of integer division of the two numbers (= what remains when you do the division because you cannot fit the second number anymore into the first one).

Do the same as in a), but exchange the + for a %.


YOU MADE IT! If you want a more complete approach to learning Python (including all the theory), you can have a look at the free pdf version of Think Python by Allen B. Downey.


Did I keep my promise of keeping it short and simple? If you have any questions or comments, just let me know. #mastery01