Lesson 3 - Variables, type system and type conversions in Python

Python Basics Variables, type system and type conversions in Python

In the previous lesson, IDLE and the first Python console application, we learned how to work with IDLE, and created our first console application. In today's lesson, we're going to look at the so-called type system of the Python programming language. We'll introduce basic data types, and we'll work with variables. As a result, we'll create 4 simple programs, including a simple calculator.


Before we start with data types, let's make sure we understand what a variable is. If you're already familiar with programming, please excuse the short explanation. Surely, you remember variables from Math class (e.g. X), in which we could store some value, usually a number. A variable in IT is the same thing. It's a place in computer memory where we can store some data, e.g. a username, the current time or a database of articles.

A variable is always of some sort of data type. It can be a number, text, etc. It depends on what we want to use it for. Before working with a variable, we have to declare it first to specify how this variable will be called and of what data type it will be. The programming language will establish it in memory, and we would then be able to use it. Our computer knows, based on our declaration, how to work with that piece of memory.

Type system

There are two basic type systems: static and dynamic.

  • In the dynamic type system, we're fully relieved from the fact that the variable has some data type at all. Obviously, the variables have it internally, but the language doesn't show it. Dynamic typing often goes so far that we don't have to declare variables at all. If we store some data in a variable and the language finds out that this variable had never been declared, it'll just create it automatically. In the same variable, we are able to store text, user objects or decimal numbers. The language will automatically change the inner data type according to data we're assigning into the variable. Due to a smaller amount of code, the development is usually faster in those languages. The example languages with this kind of type system are e.g. PHP or Ruby.
  • On the other hand, we have the static type system. It requires us to declare the variable type, and this type is unchangeable from then on. Meaning that, if we try to store a user object into a string, we'll get yelled at by the compiler.

Python is a dynamically typed language. This means that we don't have to declare variables as specific data types. Also, to add to the confusion, Python is strongly-typed. Meaning that although data types are determined automatically, we don't have to specify them, and we can assign a different type to an already existing variable. In other words, it isn't possible for us to append text to a numeric value without converting one of the values explicitly to the appropriate type.

There are 3 basic data types in Python:

  • Numbers: int
  • Real numbers (10.12, ...): float
  • Texts: string

Let's make an example program so that you'll be able to apply this newly acquired knowledge. We'll continue with the theoretic part of it all next time.

Variable printing program

We'll go ahead and declare a numeric variable, and name it: a, store the number 56 in it and print its content into the console. Create a new file and name it output (we'll create a new file for each sample program). Don't forget to add the line indicating the Python version. We'll need it at the beginning of all our files (I won't copy it here anymore):

The program will look like this:


a = 56

The first command declares a new variable, a, and assigns a value to the variable using the "=" operator which we all know from math classes. The last command is already familiar to us. It will print the content of the variable a. The print() function is smart and knows how to print numeric values as well.

Console application

The same code for a real number variable would look like this:

a = 56.6

It's almost the same as the code for the whole-number variable. The decimal separator will always be represented by a dot here. Even if your regional separator is a comma.

Parrot program

The previous program was a bit boring, let's try to respond to user's input somehow. Let's write a program named Parrot. You can probably guess what it will do - it will repeat what the user has written (twice). We haven't tried to read anything from the console yet, but it's very simple. We use the input() function which returns a string from the console. Go ahead and write the following code:

print("Hi, I'm Lora, the virtual parrot, and I love to repeat!")
text = input("Type something in: ")
result = text + ", " + text + "!"

This one's a little more fun, right? :) The first line is self-explanatory (it just prints text). On the second line, we declare a string variable text. This variable will contain the return value of the input() function, i.e. whatever the user enters into the console. To make the code more understandable, we created another string variable for the result. The most interesting part of the code is when we assign the value to result. There, we use a process called string concatenation. We use the "+" operator to join several strings into one long text. As you can see, it doesn't matter whether it's a variable or it's an explicitly declared string in quotation marks in our source code. We assign the input to the variable, then a comma followed by a space, then the input again and finally an exclamation mark. At that point, the program will display the variable.

Console application
Hi, I'm Lora, the virtual parrot, and I love to repeat!
Say something: Lora wants a cracker!
Lora wants a cracker! Lora wants a cracker!!

We could shorten the program in many other ways, but generally, it is better to use more variables and focus on clarity and readability than altering the code until we forget what the program was even supposed to do.

Doubler program

The doubler program will retrieve an input number, double it, and display it. With the current knowledge we possess, we could write something like this:

# This code does not work
a = input("Enter a number and I'll double it: ")
a = a * 2

Python will execute the program, however, the result will look something like this:

Console application
Enter a number and I'll double it: 15

What's the problem? We've just encountered one of the issues with the strong type system. The input() function returns text. Then, when we multiply the text by 2, it gets copied twice. The * operator on the string type behaves differently than the * operator on numbers. We need to convert it first. Everything from the console is text, even if we enter a number.

Type conversions

Data types in Python have functions prepared for converting them from text or for converting to them from different than textual values. If we wanted to convert a string to an int, we'd write the following:

s = "56"
a = int(s)

The conversion from non-textual types to text is sometimes referred to as parsing. We can see that the int() function takes a string parameter and returns a whole number from it. We can even pass it a parameter with a different value (e.g. a decimal number which would result in it truncating the decimal part). Let's apply this knowledge to our program:

s = input("Enter a number and I'll double it: ")
a = int(s)
a = a * 2

The first thing we did was store the text from the console into the string s. The integer variable a will then, thanks to the int() function, contain the numeric value of the string s. Then, we double the value of a and print it out to the console.

Console application
Enter a number and I'll double it: 1024

The parsing wouldn't work if a word was used instead of a number in the text. However, don't worry about these sort of scenarios for now.

Simple calculator

Since we haven't worked with real numbers yet, let's program a simple calculator. It'll be very easy. The input will consist of two numbers, and the program will display the results of addition, subtraction, multiplication, and division.

print("Welcome to our calculator!")
a = float(input("Enter the first number: "))
b = float(input("Enter the second number: "))
sum = a + b
difference = a - b
product = a * b
quotient = a / b
print("Addition: " + str(sum))
print("Subtraction: " + str(difference))
print("Multiplication: " + str(product))
print("Division: " + str(quotient))
print("Thank you for using our calculator.")

Then, once we execute it:

Console application
Welcome to our calculator!
Enter first number: 3.14
Enter second number: 2.72
Addition: 5.86
Subtraction: 0.41999999999999993
Multiplication: 8.5408
Division: 1.1544117647058822
Thank you for using our calculator.

First, we simplified parsing from the console, so we don't need a string variable (we wouldn't use it anyway). Secondly, at the end of the program, we join the string with a number using the plus sign. As you already know, Python doesn't perform implicit type conversions for us, so we have to use a conversion function. In this case, we used str() which is the opposite of int() and converts a numeric value to a string.

In the next lesson, More on the Python type system: Data types, we'll talk some more about type systems, and introduce you all to more data types.

All of the programs are available for download in the attachment below. You should definitely try to create some programs similar to these, seeing as how you already have the knowledge necessary to do so! :)



Article has been written for you by David Capka
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (5)




To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!