Woordenlijst

Selecteer een van de zoekwoorden aan de linkerkant ...

Programming in PythonTypes

Leestijd: ~30 min

Python, like most programming languages, has built-in types for handling common data like numbers and text.

Numbers

As discussed in the previous section, a numerical value can be either an int or a float. We can represent integers exactly, while storing a real number as a float often requires rounding slightly.

A number typed directly into a Python program is stored as a float or integer according to whether it contains a decimal point, so if you want the value 6 to be stored as a float, you should write it as 6.0.

Numbers can be compared using the operators ==,>,<,<=,>=,!=.

Exercise
What is the type of the object returned by 1 == 2?

1 == 2

Exercise
x == 1 is which returns True or False according to whether . Meanwhile, x = 1 is that .

Strings

Textual data is represented using a sequence of characters called a string. We can create a string object by enclosing the desired sequence of characters in quotation marks: a = "this is a string". Such a quote-enclosed string of characters in a Python program is called a string literal. String literals can also be delimited by triple quotes, which can be useful for multi-line strings and for strings containing quotes.

"""
This is a multiline string.
It can have "quotes", no problem.
"""

"This is an ordinary string. \"Quotes\" require a backslash."

We can find the number of characters in a string with the len function: len("hello") returns .

We can concatenate two strings with the addition operator (+): "Hello " + "World".

We can return the first character in a string s using the expression s[0], the second element using s[1], and so on. We can get the substring from the third to the eighth character using s[2:8]. Note that the 9 is one past the index where we want to stop.

Exercise
For which values of i and j does the expression "Hello World"[i:j] == "o Wo" return True? i = and j =

"Hello World"[i:j]

Exercise
If either i or j is omitted in the expression s[i:j] (where s is a string), what happens? Experiment using the code block above.

Solution. Omitting i or j has the effect of setting i = 0 or j = len(s).

String interpolation

We can insert the value of a variable into a string using string interpolation. There are several ways to do this in Python, but perhaps the simplest is to place an f character immediately before the opening quotation mark. A string literal modified in this way is called an f-string, or formatted string literal. Any parts of an f-string between curly braces are evaluated, and their string representations are inserted into the string at that point.

x = 19
print(f"""
The quotient when x is divided by 3
is {x//3}, and the remainder is {x % 3}.
""")

Exercise
Use string interpolation to write a single line of code which prints multiplying by 6.2 yields 12.4 if 2 is assigned to the variable A and prints multiplying by 6.2 yields 18.6 if 3 is assigned to A.

A = 2
print()

Solution. The expression print(f"multiplying by 6.2 yields {6.2*A}") works.

Booleans

A bool is a special type whose only values are True and False. The fundamental operators that can be used to combine boolean values are and, or, and not.

Exercise
Does Python convert types when doing equality comparison? In other words, does 1 == 1.0 return True or False?

1 == 1.0

Solution. Yes, Python does convert types for equality comparison. So 1 == 1.0 returns True.

Exercise
Write a one-line function which takes 3 bools as arguments and returns True if and only if either

  1. Both of the first two arguments are True , or
  2. The third argument is False
def f(a,b,c):
    pass # add code here

def test_f():
    assert f(True, True, True)
    assert f(False, True, False)
    assert not f(False, True, True)
    return "Tests passed!"

test_f()

Solution. Here's an example of a simple way to do it:

def f(a,b,c):
    return a and b or not c

Be wary of comparisons of the form a == True or b == False. These are equivalent to a and not b, respectively, assuming a and b are both bools. The more succinct versions are preferred.

Exercises

Exercise

Write some code for computing \frac{1}{a+\frac{2}{3}} where a is equal to the number of characters in the string "The quick brown fox jumped over the lazy dog"

Solution. We store the length of the given string in a variable a and evaluate the given expression as follows:

a = len("The quick brown fox jumped over the lazy dog")
1/(a+2/3)

Exercise
The expression 1 < 3 returns , which is an object of type .

Exercise
If we set s = "Bruno", then s[:j] == "Bru" when j = .

Bruno
Bruno Bruno