Skip to content

Commit 2ca4505

Browse files
committed
Add more on variables
1 parent 0d50cb8 commit 2ca4505

14 files changed

+706
-56
lines changed
Lines changed: 96 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,96 @@
1+
# Operations on sequences
2+
3+
So far, we have introduced two types that are sequences (containing ordered data): tuple (`tuple`) and string (`str`). You can iterate over each element with a for loop. Below is a description of other useful operations that we can perform on each sequence (not only on the two above, but also on the others, which will be introduced soon).
4+
Sequence length
5+
6+
The first operation that may be useful is to know the sequence length. This is done by a function `len(sequence)` that returns the number of elements in the sequence given as its argument (i.e. in parentheses). E.g:
7+
8+
```python
9+
data = (1, 2, 3, 10)
10+
print(len(data))
11+
12+
length = len("To be of not to be?")
13+
print("Sentence has", length, "letters.")
14+
```
15+
16+
As an exercise, I propose to modify the Password task from the previous topic (without sending it) and add an additional security test for the password you entered: it must be at least 8 letters long.
17+
18+
> **Warning!**
19+
> When using a for loop, do not iterate over the element indexes as follows `for i in range(len(sequence)):`. Instead, you should use simple syntax `for element in sequence:`. If you need element numbers, or you want to iterate over several sequences simultaneously, the appropriate methods are described separately.
20+
21+
## Does the sequence contain an element?
22+
23+
Another useful operation is checking if a given element is present in the sequence. The operator is for this **`in`**, or **`not in`**. E.g:
24+
25+
```python
26+
if 'a' in 'Alice':
27+
print("The word 'Alice' contains the letter 'a'")
28+
29+
if 4 not in (2, 3, 5, 7, 11, 13, 17, 19):
30+
print("Four is not a prime less than 20")
31+
```
32+
33+
## Access to individual sequence elements
34+
35+
Since sequences are an ordered collection of elements, it is necessary to be able to access the element with a specific number. For this, in Python, square brackets are used immediately after the sequence, or (more commonly) the name of the variable representing it:
36+
37+
```python
38+
data = ('A', 'B', 'C')
39+
print(data[0]) # prints the first element of the tuple ('A')
40+
print(data[2]) # prints the third element of the tuple ('C')
41+
42+
word = "Kalambur"
43+
for i in (1, 3, 6):
44+
# print second, fourth and seventh letters
45+
print(word[i])
46+
```
47+
48+
Inside the square brackets there must be an integer (or a variable that represents such a number) called the index. It indicates the element number in the sequence, with the first element numbered 0. This is somewhat counterintuitive and is due to the fact that in most older programming languages this convention has been used historically. Please note that this behavior is consistent with the function of the previously discussed function `range`:  **Python always counts from 0!**
49+
50+
In Python it is also possible to use negative numbers as indices. Then the countdown starts from the end. So `sequence[-1]` means the last element of the sequence, `sequence[-2]` the penultimate one, etc. Example:
51+
52+
```python
53+
name = input("Enter your name:")
54+
55+
if name[-1] == 'a': # in Polish, female names end with "a"
56+
print("You are a woman")
57+
else:
58+
print("You are a man ")
59+
```
60+
61+
As a simple exercise, please modify the example above so that each Kuba is treated like a man ☺.
62+
63+
64+
## Range slices
65+
66+
You can use square brackets to dereference not only individual sequence elements, but also slices of them. Such slices have the following form `sequence[start:stop:step]`, where `start` is the index of the first element entering the slice, `stop` the index of the first element that does not enter the slice, and the `step` is the step with which subsequent elements are taken (please note that there is some similarity to the arguments of the `range` the function). Each of the `start`, `stop` and `step` numbers can be omitted.
67+
68+
The operation of the slices is best illustrated by an example. Please rewrite them in the interactive console and try to understand exactly how the successive elements of each slice are counted.
69+
70+
```python
71+
digits = tuple(range(10)) # (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
72+
73+
digits[2:7] # (2, 3, 4, 5, 6)
74+
digits[2:7:2] # (2, 4, 6)
75+
digits[:5] # (0, 1, 2, 3, 4)
76+
digits[5:] # (5, 6, 7, 8, 9)
77+
digits[::3] # (0, 3, 6, 9)
78+
digits[7:2:-1] # (7, 6, 5, 4, 3)
79+
digits[-1:3:-2] # (9, 7, 5)
80+
digits[6::-2] # (6, 4, 2, 0)
81+
digits[::-1] # ( 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
82+
digits[:-4:-1] # (9, 8, 7)
83+
```
84+
85+
**Important!** Please note that the element with the stop index is no longer part of the slice.
86+
87+
Example for text strings:
88+
89+
```python
90+
text = input("Enter text:")
91+
print("Your text backwards is:", text[::-1])
92+
```
93+
94+
<hr/>
95+
96+
Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.

04 More on Variables/1.md

Lines changed: 0 additions & 8 deletions
This file was deleted.

04 More on Variables/2 Lists.md

Lines changed: 165 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,165 @@
1+
# Lists
2+
3+
There is a data type very similar to tuples in Python. These are lists (`list`). Unlike tuples, which are constants, lists are structures that can change: you can add new elements to them, delete or change them.
4+
5+
Lists with specific items are created similar to tuples, however, instead of parentheses, square brackets are used:
6+
7+
```python
8+
list = ["first", 2, 2.5, 3-1j]
9+
```
10+
11+
As with tuples, the list items don't have to be of the same type. All the previous operations shown for tuples, such as iterating over them in a **for** loop, indexing elements, slices, and so on, work exactly the same for lists.
12+
13+
However, the list items can be changed. Please enter the following commands in the interactive console
14+
15+
```python
16+
list = [1, 2, 3]
17+
18+
list[0] = 10
19+
20+
print(list) # [ 10 , 2, 3]
21+
```
22+
23+
If I did such an assignment for a tuple, it would cause a `TypeError`.
24+
25+
List items can also be removed with a command **`del`**. E.g:
26+
27+
```python
28+
list = ['A', 'B', 'C', 'D']
29+
30+
del list[1] # delete the second element
31+
32+
print (list) # ['A', 'C', 'D']
33+
```
34+
35+
It is also possible to insert and add items to the list. They are used to this method with names `insert` and `append`. These methods are specific operations related to a variable of a given type. They are similar to a function, but affect only one specific object. They are called as follows `object.method(arguments...)`, where object is usually a variable name, and the method name is separated from the object by a period. Adding an item to the list will look like this:
36+
37+
```python
38+
list = ['A', 'B', 'C']
39+
40+
list.append('D')
41+
```
42+
43+
The method append puts the element given as its argument to the end of the list. So in the example above, the list would be `['A', 'B', 'C', 'D']`. In contrast, the method `insert` takes two arguments: the place where the element should be inserted (i.e. the index of the inserted element) and its value:
44+
45+
```python
46+
list = ['A', 'B', 'C']
47+
48+
list.insert(1, 'X')
49+
50+
print(list) # ['A', 'X', 'B', 'C']
51+
```
52+
53+
Below is an example of creating a names list. Please run it and analyze it:
54+
55+
```
56+
names = [] # this creates an empty list
57+
58+
# The following loop will run infinitely
59+
# it can only be ended with break
60+
while True:
61+
name = input("Enter name or write a dot to end:")
62+
if name == '.':
63+
break
64+
names.append(name)
65+
66+
print(names)
67+
```
68+
69+
## Converting lists and other types
70+
71+
You can convert lists to tuples and vice versa without any restrictions. This way, you can work around the restriction not allowing tuples to be modified:
72+
73+
```python
74+
my_tuple = (1, 2, 3)
75+
my_list = list(my_tuple)
76+
list[0] = 10
77+
my_tuple = tuple(my_list)
78+
print(my_tuple)
79+
```
80+
81+
However, keep in mind that tuples are more efficient and run faster, so avoid this conversion unless absolutely necessary.
82+
83+
Similarly, you can convert strings into lists, but not the other way around: check what the following command will do `str(['a', 'b', 'c'])`. However, there are two very useful methods defined for strings: `split` and `join`. The method `split` is used to split a text string into words, and join to concatenate list items. Please try to split the text yourself in the interactive console:
84+
85+
```python
86+
text = "one two three"
87+
88+
list = text.split()
89+
90+
print(list) # ['one', 'two', 'three']
91+
```
92+
93+
There is also an alternate way of calling the method `split` that allows you to split text not into words (that is, at spaces and newlines), but selected strings. For example, let's see how to split a text containing words separated by a comma followed by a space:
94+
95+
```python
96+
text = "one, two, three"
97+
98+
list = text.split(', ')
99+
100+
print(list) # ['one', 'two', 'three']
101+
```
102+
103+
The method `join` (which works on text strings) is used to concatenate the elements of a list (or a tuple) given as its arguments. The hyphen is the text that this method works on. This is best illustrated by an example:
104+
105+
```python
106+
list = ['Kacper', 'Melchior', 'Balthazar']
107+
108+
hyphen = "+"
109+
110+
text = hyphen.join(list)
111+
112+
print(text) # "Kacper+Melchior+Baltazar
113+
```
114+
115+
The methods also work directly for text values:
116+
117+
```python
118+
list = ['Kacper', 'Melchior', 'Balthazar']
119+
120+
text = "+".join(list)
121+
122+
print(text) # "Kacper+Melchior+Baltazar
123+
```
124+
125+
### Elegant list creation
126+
127+
The method `append` is used to add items to the list. If it can be avoided, it is better not to use it to build entire lists, repeating it inside a for loop. Python offers an elegant method of creating lists called **list comprehension**. Above is an example of creating a list by listing its elements separated by a comma and placed in square brackets `[...]`. Instead of listing the items manually, you can use a for loop with the following syntax:
128+
129+
```python
130+
list = [expression for counter in sequence]
131+
```
132+
133+
This expression comes before the **`for`** command and there is no colon anywhere. This expression can use a loop counter to compute successive values to insert into the list. It is best to illustrate this with an example. Suppose we want to create a list containing squares of numbers in the range 1-10:
134+
135+
```python
136+
squares = [i**2 for i in range(1, 11)]
137+
138+
print(squares)
139+
```
140+
141+
Please note that this is very similar to the natural language: "let the list of squares consist of the values i² for i in the range 1 to 10".
142+
143+
In a more advanced version, we can add an additional condition that the loop counter must satisfy in order for the corresponding expression to be included in the list:
144+
145+
```python
146+
list = [expression for counter in sequence if condition]
147+
```
148+
149+
For example, if we do not want to include the squares of 3 and 7 in our list of squares, we can write:
150+
151+
```python
152+
squares = [i**2 for i in range(1, 11) if i not in (3, 7)]
153+
```
154+
155+
## Exercise
156+
157+
Please write the shortest possible program, which will create a list containing the lengths of individual words in the sentence "To be or not to be" (for the sake of simplicity, punctuation marks have been omitted).
158+
159+
160+
161+
162+
163+
<hr/>
164+
165+
Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.

04 More on Variables/2.md

Lines changed: 0 additions & 8 deletions
This file was deleted.
Lines changed: 115 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,115 @@
1+
# Dictionaries
2+
3+
Normal lists (arrays) are usually a collection of numbered elements, so to refer to any list element you must enter its number. But identifying elements by numbers aren't always convenient. For example, flight numbers are identified by an alpha-numeric code. Similarly, bus numbers in Łódź may contain letters.
4+
5+
A data structure that allows any type of index (called a key) to be used instead of a number is called a dictionary. In Python, the corresponding data structure is called `dict`. Like a list, it is a variable structure: after you create a dictionary, you can change it. Just like tuples are made with parentheses, lists with square brackets, dictionaries are made with curly braces:
6+
7+
```python
8+
dictionary = { key1: value1, key2: value2, key3: value3 }
9+
```
10+
11+
Consider a simple example. Let's create a dictionary where the key is the name of the country, and the value the name of the capital of that country:
12+
13+
```python
14+
capitals = { # after opening the parenthesis, you can go to a new line
15+
'Poland': 'Warsaw',
16+
'Germany': 'Berlin',
17+
'USA': 'Washington
18+
}
19+
```
20+
21+
Thus, each dictionary element consists of two objects: a key and a value. In our example, the key is the name of the country and the value is the name of the capital. A key identifies an element of a dictionary, value is the data corresponding to the given key. The key values ​​must be unique, i.e. there cannot be two identical keys in the dictionary.
22+
23+
The phone book is another example of the dictionary data structure. In this case the name is the key and the value is the phone number. For both a dictionary and a phone book, it is easy to find an item for a given key (e.g., if the records are stored in alphabetical order), but if the key is unknown and only the value is known, searching for an item with the given value may require you to browse the entire dictionary.
24+
25+
Access to the dictionary elements is done using square brackets. The key value is given inside the parentheses, e.g.:
26+
27+
```python
28+
print(capitals['Poland']
29+
```
30+
31+
Attempting to retrieve a value for a key that is not in the dictionary in this way will result in a `KeyError`.
32+
33+
As stated above, the dictionary can be changed. Adding new items and changing existing ones is very simple:
34+
35+
```python
36+
capitals['France'] = 'Paris'
37+
```
38+
39+
If the key "France" was not previously in the dictionary, it will be added and assigned the value "Paris". If it already existed, it will simply be assigned a new value.
40+
41+
Removing items from the dictionary is possible with the command **`del`**:
42+
43+
```python
44+
del capitals['USA']
45+
```
46+
47+
In Python, the key can be any immutable data type: integers and real numbers, strings, tuples. It cannot be lists or other dictionaries. The value of a dictionary item can be any data type.
48+
49+
In addition to the use of square brackets to access the dictionary elements it is possible using the method `get`: `dictionary.get(key)`. If the given key is in the dictionary, the corresponding element will be returned. Otherwise, the method will return None. This method also has a version with two arguments `dictionary.get(key, default_value)`, which — if the given key is missing from the dictionary — returns the given default value. In both cases, this method (unlike retrieving the item using square brackets), will not generate an exception (error).
50+
51+
To check if a key is in the dictionary, you can use operators **`in`** and **`not in`**, similarly to sequences.
52+
53+
```python
54+
letters = {'ab': 'ba', 'aa': 'aa', 'bb': 'bb', 'ba': 'ab'}
55+
56+
key = 'ac'
57+
if key in letters:
58+
del letters[key]
59+
```
60+
61+
## More about creating dictionaries
62+
63+
Just as it is possible to create lists elegantly with list comprehensions, it is possible to construct dictionaries as follows:
64+
65+
```python
66+
dictionary = { expression_for_key: expression_for_value for item in sequence }
67+
```
68+
69+
E.g:
70+
71+
```python
72+
words = "Ala has a cat".split() # ['Ala', 'has', 'a', 'cat']
73+
74+
word_lengths = {word: len(word) for word in words}
75+
```
76+
77+
This will create a dictionary `{'Ala': 3, 'has': 3, 'a': 1, 'cat': 3}`.
78+
79+
## Iteration through dictionaries
80+
81+
Although dictionaries are not sequences, you can iterate over them with a **for** loop:
82+
83+
<pre>
84+
<b>for</b> <i>key</i> <b>in</b> <i>dictionary</i><b>:</b>
85+
loop block
86+
</pre>
87+
88+
This loop will be performed for each key in the dictionary. Unlike sequences, the iteration order is undefined (i.e. the loop will be executed for each key, but we cannot predict in what order). E.g:
89+
90+
```python
91+
word_lengths = {'Ala': 3, 'has': 3, 'a': 1, 'cat': 3}
92+
93+
for word in word_lengths:
94+
print("Word", word, "has", word_lengths[word], "letters")
95+
```
96+
97+
If we want to iterate over dictionary values only, we can use the method `dictionary.values()`:
98+
99+
```python
100+
capitals = { 'United Kingdom': 'London', 'Germany', 'Berlin', 'USA' 'Washington}
101+
102+
for city in capitals.values():
103+
print("There is no such city as", city, "in Poland")
104+
```
105+
106+
It is also possible to iterate through keys and values simultaneously using the method `dictionary.items()`:
107+
108+
```python
109+
for country, city in capitals.items():
110+
print("Capital of", country, "is", city)
111+
```
112+
113+
<hr/>
114+
115+
Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/license.

0 commit comments

Comments
 (0)