Recognizing Different Types of Variables Python - AkuCode
Python recognizes several types of variables: string literals (words), numbers, sequences (lists), mapping (dictionaries), and Booleans (true or false values). These are the staple ingredients of all Python programs. The value None has a type all of its own, NoneType. The rest of this chapter will introduce you to words and numbers. However, first, we need to talk about Python’s dynamic typing features.
Working with Dynamic Typing
In python, once the value has been assigned to a variable, the interpreter will then decide what sort of value it is (i.e., a number, some text, or some other relevant quality). This is known as dynamic typing (it has nothing to do with how many words per minute you can input from the keyboard). Unlike some other languages, it is not necessary to declare what your variables are before you use them. This is both a blessing and a curse. The main advantage is that you don’t really have to worry exactly what type an item of data is, so long as it behaves the way you want it to.
Dynamic typing makes it much easier to handle different types of unpredictable user input. The interpreter can accept user input in many different forms, to which it assigns a type dynamically. This means that a single piece of code can be used to deal with words, numbers, or any other data type and that the programmer doesn’t need to decide what type the data will be to assign it to a variable.
Not needing to declare variables before you use them makes it tempting to introduce variables at random places in your scripts. Beware: Python won’t complain unless you try to use a variable before you have actually assigned it a value, but it’s really easy to lose track of what variables you are using and where you set up their values in the script.
Two really sensible practices will help keep you sane when you start to create large numbers of different variables. One is to set up a bunch of default values at the start of each section where you will be needing them, keeping all the variables you are going to use together in one part of the text like an ingredients list. The other is to keep track of the expected types and values of your variables, keeping a data table in your design document for each program that you are writing.
Python needs to keep track of the type of variable for two main reasons. Chiefly, the machine needs to set aside enough memory to store the data, and different types of data take up different amounts of space, some more predictably than others. The second reason is that keeping track of types helps to avoid and troubleshoot errors. Once Python has decided what type a variable is, it will flag up a TypeError if you try to perform an inappropriate operation on that data. Although this might at first seem to be and unnecessary irritation, you will discover that this can be an incredibly useful feature of the language; as the following command-line example shows:
>>> b = 3
>>> c = ‘Word’
>>> trace = False
>>> b + c
Traceback (most recent call last):
File “<stdin>”, line 1, in <module>
TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’
>>> c – trace
Traceback (most recent call last): File “<stdin>”, line 1, in <module>
TypeError: unsupported operand type(s) for -: ‘str’ and ‘bool’
Here, I attempted to perform operations on incompatible types. You’re not allowed to add a number to a word or take a yes/no answer away from it. It is necessary to convert the data to a compatible type before trying to process it. You can add words together or take numbers away from each other, just like you can in real life, but you can’t do arithmetic on a line of text. The traceback is Python’s way of alerting you to a potential error in your logic, in this case, a TypeError. This tells me that I need to rewrite the code to make it clear what type of information I want to put in and get out of the equation
The purpose of data types is to allow us to represent information that exists in the real world, that is, the world that exists outside your computer, ad opposed to the virtual world inside. We can have an existential conversation about what is real and what is not some other time. The previous example used variables of type int (whole number) and type str(text). It will quickly become apparent that these basic data types can only represent the simplest units of information; you may need to use quite a complicated set of words, numbers, and relationships to describe even the simplest real-world entity in virtual-world terms.
Python provides a variety of ways of combining these simple data types to create more complex data types, which I’ll come to later in this book. First, you need to know about the fundamental building blocks that are used to define your data and the basic set of actions you can use to manipulate the different types of values.
In the Beginning Was the Void
Python has a special predefined value called None, which represents nothing, zilch, nada. The value none has its own type and is useful where you want to create a variable but don’t want to specify its value (and therefore its type) just yet. Assigning values such as – or “” to a variable will create an int or str type variable. You can assign the value None like this, which produces a NoneType variable. Don’t forget it starts with a capital N
Information = None
For the next few examples, the real-world information that I’ll be attempting to model in the virtual form will be fantasy characters for a role-playing game. To create some continuity in my fantasy world, I need to be able to keep track of the characters’ names, plus some descriptive information, such as what kind of fantasy creature each is. I also need to create some statistics to represent strength, speed, and so on, to provide some data for the combat system to use, and I need to be able to keep a record of how much money each character has. I’m sure you’ll be itching to learn how to automate your accounts and database your stock you to the inhabitants of Cloud-Cuckoo Land.
Comments