2. Strings, variables, Booleans and None
Strings
In the previous chapter we used Python as a calculator. Entering a number to the interactive prompt would simply echo it back.
Typing text instead of numbers doesn't work like that.
>>> hello Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'hello' is not defined >>>
But putting the text in quotes works. You can use single quotes or double quotes. They work the same way, but things entered with double quotes will be echoed back with single quotes. Pieces of text inside quotes are known as strings.
>>> 'hello' 'hello' >>> "hello" # Python defaults to single quotes 'hello' >>>
There's full Unicode support.
The + and * operators also work like you may expect them to work.
>>> 'hello' + 'world' 'helloworld' >>> 'hello' + ' ' + 'world' # ' ' is a space 'hello world' >>> 'hello' * 3 'hellohellohello' >>> 3 * 'hello' 'hellohellohello'
You can't use + to combine numbers and strings. You can convert the number to a string with str() and then use + instead.
>>> 'number ' + 1 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: Can't convert 'int' object to str implicitly >>> str(1) # converts to string '1' >>> 'number ' + str(1) 'number 1' >>>
You can also use len() to get the length of a string in characters. This will come in handy later in this tutorial.
- and / can't be used with strings.
>>> 'hello' - 'o' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for -: 'str' and 'str' >>> 'hello' / 'o' Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) for /: 'str' and 'str' >>>
Variables
Variables are easy to understand. They simply contain data. [*]
>>> a = 1 # create a variable called a and assign 1 to it >>> a # get the value of a 1 >>>
[*] In fact, variables point to data stored in the computer's memory. All strings, integers and other objects are just data in RAM. See this video for more info.
Variable names can be multiple characters long. They can contain uppercase characters and special characters, but most of the time you should be using simple, lowercase variable names. You can also use underscores.
>>> number_one = 1 >>> number_two = 2 >>>
Here's exercise 1 from the first chapter:
A company needs to buy new computers and monitors. With taxes, a new monitor costs 49,95 € and a new computer costs 200 €. How much would 100 computers cost without taxes, when the taxes are 24 % of the price?
With variables, calculating something like this is simple. In this example, we assign the price of 100 computers and monitors to a variable called price, then the amount of tax to a variable called tax and calculate the price without the tax. Here 1 - tax is the ratio of price without tax to price with tax.
>>> price = 100 * (200 + 49.95) >>> tax = 24 / 100 >>> price * (1 - tax) 18996.2 >>>
The advantage of this is that finding out how much 500 computers and monitors would cost without the taxes is easy.
>>> price = 500 * (200 + 49.95) >>> price * (1 - tax) 94981.0 >>>
The right side of the = sign is always executed before the left side. This means that you can do something with a variable on the right side, then assign the result back to the same variable on the left side:
>>> a = 1 >>> a = a + 1 >>> a 2 >>>
To do something to a variable (for example, to add something to it) you can use +=, -=, *= and /= instead of +, -, * and /. The "advanced" %=, //= and **= also work.
>>> a += 2 # a = a + 2 >>> a -= 2 # a = a - 2 >>> a *= 2 # a = a * 2 >>> a /= 2 # a = a / 2 >>>
This also works with strings.
>>> a = 'hello' >>> a *= 3 >>> a += 'world' >>> a 'hellohellohelloworld' >>>
Now you also understand why typing hello to the prompt didn't work in the beginning of this tutorial. But we can assign something to a variable called hello and then type hello:
>>> hello = 'hello hello' >>> hello 'hello hello' >>>
Booleans and None
In Python, and many other programming languages, = is assigning and == is comparing. a = 1 sets a to 1 and a == 1 checks if a equals 1.
>>> a = 1 >>> a == 1 True >>> a == 2 False >>> a = 2 >>> a == 2 True >>>
a == 1 is the same as (a == 1) == True. a == 1 is more readable, so == True needs to be used very rarely.
>>> a = 1 >>> a == 1 True >>> (a == 1) == True True >>> a = 2 >>> a == 1 False >>> (a == 1) == True False >>>
True and False are boolean values. In Python they're built-in variables. [*] There's also None, which is often used as a default value. All these can be saved to variables, just like integers, floats and strings.
>>> a = True >>> a True >>> b = (1 == 2) >>> b False >>> c = None >>> c # nothing happens, the interactive prompt doesn't show None >>> print(c) # print() can be used to display it instead None >>>
[*] In Python 3, True, False and None are actually keywords, but they behave just like variables.
There are other comparing operators than == too:
| Usage | Description | True examples |
|---|---|---|
a == b |
a is equal to b | 1 == 1 |
a != b |
a is not equal to b | 1 == 2 |
a > b |
a is greater than b | 2 > 1 |
a >= b |
a is greater than or equal to b | 2 >= 1, 1 >= 1 |
a < b |
a is lesser than b | 1 < 2 |
a <= b |
a is lesser than or equal to b | 1 <= 2, 1 <= 1 |
a in b |
b contains a | 'hello' in 'hello world' |
a not in b |
b does not contain a | 'howdy' not in 'hello world' |
not a |
a is False [*] | not 1 == 2 |
a and b |
a is True and b is True [*] | 1 == 1 and 2 == 2 |
a or b |
a is True, b is True or they're both True [*] | False or 1 == 1, 1 == 1 or 2 == 2 |
[*] These are not always correct, but this tutorial is about Python's basics, not about cool tricks we can do with it. See this for more info.
There is more than one way to do some things. For example, to check if a is not equal to 1 you could do a != 1 or not a == 1. To check if b does not contain a you could do a not in b or not a in b. However, != and not in should be used in cases like this because they're more convinient once you get used to them.
There's also is, but don't use it instead of == unless you know what you are doing.