Skip to content

Commit 067cafd

Browse files
committed
Add flow control
1 parent a4dae86 commit 067cafd

File tree

7 files changed

+343
-25
lines changed

7 files changed

+343
-25
lines changed

02 Constants, Variables and Basic Operations/1 Constants and their types.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,7 +144,7 @@ type(1 + 2)
144144
type(1 + 2.0)
145145
```
146146

147-
As you can see above, Python is able to convert numeric types by itself so that the result of a given action makes sense. However, it is possible to force type conversions manually by directly using their names as functions. This is especially useful when you want to convert a string to a number. For example:
147+
As you can see above, Python is able to convert numeric types by itself so that the result of a given action makes sense. However, it is possible to force type conversions manually by directly using their names as functions. This is especially useful when you want to convert a string to a number. For example:
148148

149149
```python
150150
float("2.5")

03 Flow Control/1 Conditions.md

Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
# Conditions
2+
3+
All previous programs have been executed sequentially, line by line. No line could be skipped.
4+
5+
Consider the following problem: for a given real number, determine its absolute value. If number > 0, the program should print its value, otherwise it should print –number . This behavior cannot be achieved by using a sequential program. The program should conditionally select the next step. The following command used for this purpose is called if:
6+
7+
```python
8+
number = float(input("Enter a number:"))
9+
10+
if number > 0:
11+
absolute_value = number
12+
else:
13+
absolute_value = -number
14+
15+
print(absolute_value)
16+
```
17+
18+
This program uses a conditional statement **`if`** . After that, we put a condition `number > 0` after a colon. We then insert a block of statements that will only be executed if the condition is true (i.e. the value of the expression `number > 0` is equal to `True`). This block can be followed by a word else, a colon, and another block of instructions that will only be executed if the condition is false (i.e., has the value `False`).
19+
20+
## Blocks in Python
21+
22+
In Python, blocks are marked with indentation i.e. spaces at the beginning of the line. The number of these spaces is arbitrary, but it is important that there are enough of them to make the block visually stand out. Each block must be identified by a colon (**`:`**) at the end of the preceding line. Of course, only some commands can start a new block. In the example above, these are the commands if and else. The blocks assigned to them will be executed only if the condition is met (**`if`**) or not met (**`else`**). We finish the block by removing the indentation of the first non-block line.
23+
24+
Blocks can be nested: next levels are marked by increasing the number of spaces at the beginning (e.g. 4, 8, 12 etc.), and each of them is finished by undoing the indentation accordingly. (8, 4, 0). It is possible to remove indentations corresponding to several blocks at once — then we finish them all at once.
25+
26+
The way of marking blocks with indentation is specific to Python. Other programming languages use special characters (usually braces) to mark the beginning and end of a block.
27+
28+
In summary, a conditional statement in Python has the following syntax:
29+
30+
<pre>
31+
<b>if</b> <i>condition</i><b>:</b>
32+
any number of commands
33+
executed if the condition is True
34+
<b>else:</b>
35+
any number of commands
36+
executed if the condition is False
37+
</pre>
38+
39+
the keyword else along with its corresponding block can be omitted if nothing should be done if the condition is false. For example, we can replace the variable with number with its absolute value as follows:
40+
41+
```python
42+
number = float(input("Enter a number:"))
43+
44+
if number < 0:
45+
number = -number
46+
47+
print(number)
48+
```
49+
50+
In this example, the variable `number` is assigned the value `-number` only if `number < 0`. On the other hand, the command `print(number)` is executed every time because it is not indented, so it does not belong to the block that is executed only when the tested condition is true.
51+
52+
## Nesting conditions
53+
54+
Each Python statement can be placed in any of the blocks, including a different conditional statement. Thus, we obtain nested conditions. Internal condition blocks are indented with more spaces (e.g., 8 spaces). Let's see an example. Given the coordinates of a point on the plane, print a quarter of it:
55+
56+
```python
57+
x = float(input("Enter x coordinate:"))
58+
y = float(input("Enter y coordinate:"))
59+
60+
if x > 0:
61+
if y > 0:
62+
# x is greater than 0, y is greater than 0
63+
print("Quadrant I")
64+
else:
65+
# x is greater than 0, y is less than or equal to 0
66+
print("Quadrant IV")
67+
else:
68+
if y > 0:
69+
# x is less than or equal to 0, y is greater than 0
70+
print("Quadrant II")
71+
else:
72+
# x is less than or equal to 0, y is less than or equal to 0
73+
print("Quadrant III")
74+
```
75+
76+
If we have more than two options to distinguish using the conditional operator, we can use the statement **`if ... elif ... else`** (**`elif`** is short for *else if*):
77+
78+
<pre>
79+
<b>if</b> <i>condition1</i><b>:</b>
80+
any number of commands
81+
executed if condition1 is True
82+
<b>elif</b> <i>condition2</i><b>:</b>
83+
any number of commands
84+
executed if the condition1 if False and condition2 is True
85+
<b>elif</b> <i>condition3</i><b>:</b>
86+
any number of commands
87+
executed if the condition1 and condition2 are False and condition3 is True
88+
<b>else:</b>
89+
any number of commands
90+
executed if all conditions are False
91+
</pre>
92+
93+
Let's show how it works by rewriting the example above:
94+
95+
```python
96+
x = float(input("Enter x coordinate:"))
97+
y = float(input("Enter y coordinate:"))
98+
99+
if x > 0 and y > 0:
100+
print("Quadrant I")
101+
elif x > 0 and y < 0:
102+
print("Quadrant IV")
103+
elif y > 0:
104+
print ("Quadrant II")
105+
else:
106+
print ("Quadrant III")
107+
```
108+
109+
<hr/>
110+
111+
Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.

03 Flow Control/1.md

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

03 Flow Control/2 While loops.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# While loops
2+
3+
To be useful any programming language must allow you to repeat a portion of a program more than once. These types of repetitions are called loops. There are two kinds of loops in Python. Below, we will discuss the first of them: the **while** loop. It is used to repeat a given block as long as a certain condition is met. This loop looks like this:
4+
5+
<pre>
6+
<b>while</b> <i>condition</i><b>:</b>
7+
block of statements executed
8+
as long as the condition
9+
is True
10+
</pre>
11+
12+
Please note the colon after the condition and the block indentation — the same rules for defining blocks apply as for the **if** statement. Sample code:
13+
14+
```python
15+
number = 0
16+
while number < 1 or number > 10:
17+
number = int(input("Enter an integer from 1 to 10:"))
18+
print("Your number is", number)
19+
```
20+
21+
In the above example, the user will be prompted to enter a `number` as long as the value of the variable number to which the value is assigned is either less than 1 or greater than 10.
22+
23+
<u>The condition in the **while** loop is checked at the very beginning, before the loop is executed for the first time.</u> This means that the loop may not be executed even once if the condition is not met at the very beginning. Please note the first line of the example above `number = 0`. It defines a variable `number` and sets its value to zero, which guarantees that the first time it checks, the **while** loop will be true (0 < 1) i.e. the user will be prompted for a number at least once.
24+
25+
## Breaking the loop
26+
27+
The standard termination of the while loop occurs when the condition has a value False. When set to value True, the entire loop block is executed. This is not always what you want. Therefore, it is possible to interrupt execution of a loop inside its block with an instruction break. Let's see an example of a primitive version of the 21 game:
28+
29+
```python
30+
sum = 0
31+
given_number = int(input("Enter a number: "))
32+
while given_number != 0:
33+
sum += given_number # this entry is a shortened version of the assignment sum + = sum + given_number
34+
if sum > 21:
35+
print("You have exceeded 21 and you lost! ")
36+
sum = 0
37+
break
38+
given_number = int(input("Enter a number (0 to end): "))
39+
print("Your score is", sum)
40+
```
41+
42+
Normal loop break occurs when the user enters the number 0 (the condition will not be fulfilled then `given_number != 0`). However, when the calculated sum exceeds 21, the loop is stopped abnormally using the break command. In both cases, the program will continue from the first command outside the loop block (`print("Your score is", sum)`).
43+
44+
After a completed loop block, it is possible to add a command **`else`** followed by a block, which will only be executed if the loop ended normally (that is, not via a command **`break`**). Using this, you can write the above example in a slightly more elegant way:
45+
46+
```python
47+
sum = 0
48+
given_number = int(input("Enter a number: "))
49+
while given_number != 0:
50+
sum += given_number
51+
if sum > 21:
52+
print("You've exceeded 21 and lost!")
53+
break
54+
given_number = int(input("Enter number (0 to finish): "))
55+
else:
56+
print("You won! Your score is", sum)
57+
```
58+
59+
The last line will only be printed when the loop ends with a zero, not by exceeding 21.
60+
61+
## Continuation of the loop
62+
63+
Another statement that is used to control loop execution is **`continue`**. If the Python interpreter hits **`continue`** somewhere in the middle of a loop iteration, it skips all remaining statements and proceeds to the next iteration. Example:
64+
65+
```python
66+
i = -11
67+
while i < 10:
68+
i += 1
69+
if i == 0:
70+
continue
71+
print(1 / i)
72+
```
73+
74+
<hr/>
75+
76+
Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.

03 Flow Control/2.md

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

03 Flow Control/3 For loops.md

Lines changed: 155 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,155 @@
1+
# For loops
2+
3+
Another type of loop in Python is the for loop. It is used when we are able to predict in advance how many times we want to perform this loop, or when we want to repeat it for each element of the sequence. The for loop syntax is as follows:
4+
5+
<pre>
6+
<b>for</b> <i>pointer</i> <b>in</b> <i>sequence_which_we_iterate</i><b>:</b>
7+
block repeated for each element of the sequence,
8+
the identifier given as a pointer will
9+
point at each element of the sequence in every iteration
10+
</pre>
11+
12+
In the above syntax we give the correct variable name as the pointer. This variable does not have to be previously defined (and if it was, its previous value will be removed). Each time the loop passes, this variable will take the next values ​​in the sequence we iterate through. Of course, the sequence must exist: either be given as a constant or assigned to a variable.
13+
14+
So far, two sequence types have been introduced: string and tuple. The following is an example of a loop in which all the elements of a tuple are summed:
15+
16+
```python
17+
numbers = (1, 2, 3, 5, 7)
18+
sum = 0
19+
for number in numbers:
20+
sum += number
21+
print("Sum of numbers is", sum)
22+
```
23+
24+
> **Attention!** In Python, many basic operations (such as adding the elements of a set) can be done with one command or function (in this case, it would be enough to write `result = sum(liczby)`). In normal programs, use these abbreviated forms as they are clearer and usually run faster. However, for the purposes of examples and exercises, we will write many of these simple operations by hand — for illustration purposes only.
25+
26+
You can also iterate over elements of a text string:
27+
28+
```python
29+
name = input("What is your name:")
30+
for letter in name:
31+
print(letter)
32+
```
33+
34+
The above example will ask the user for their first name and then print each letter in a separate line.
35+
36+
## Caesar cipher
37+
38+
Now let's look at a more advanced example. We will implement the [Caesar cipher](https://en.wikipedia.org/wiki/Caesar_cipher) (although we will limit ourselves to the alphabet used in the English language). First, however, it is necessary to explain how the characters are stored in the computer's memory. Well, every computer is a device that can carry out operations on numbers and only on numbers. Therefore, in order to save any text in the computer's memory, each character must be assigned a numerical value. Which number corresponds to which letter defined by the ASCII and Unicode standards. There are two functions in Python that let you find out which number corresponds to which character and vice versa. The first is a function `ord(character)` whose argument can only be one character (that is, a text string containing exactly one element). It will return the numeric code of this character. The inverse function `chr(code)` will return the character represented by the numeric code given as its argument. Please check in the interactive console:
39+
40+
```python
41+
print(ord('A'))
42+
43+
print(chr(122))
44+
```
45+
46+
The above functions will be used in the encryption program using the Caesar cipher. We will use an alphabetic shift of 13, because the English alphabet has 26 letters, so double encrypted messages will restore it (in other words, the same program can be used to encrypt and decrypt messages — this variant of the Caesar cipher is called ROT-13).
47+
48+
```python
49+
# We read the text to be encrypted
50+
original_text = input("Enter the text to be encrypted: ")
51+
52+
# The ciphertext is empty for now; we will add further characters to it
53+
encrypted_text = ''
54+
55+
# In the loop we iterate over each
56+
for character in original_text:
57+
58+
if 'A' <= character <='Z': # condition a < x <b is the same as: a < x and x < b
59+
# We have a capital letter; we calculate its sequence number
60+
# (so that the letter "A" corresponds to 0)
61+
code = ord(character) - ord('A')
62+
63+
# We encrypt the character: add 13 and wrap up to 26 characters (remainder from division)
64+
new_code = (code + 13) % 26
65+
66+
# We add a new ciphertext:
67+
# first "shift" the new code so that the letter "A" has the correct code,
68+
# then convert it to a character and add it to the string with the result
69+
encrypted_text += chr(new_code + ord('A'))
70+
71+
elif 'a' <= character <= 'z': # we do the same for lower case letters
72+
code = ord(character) - ord('a') # subtract lower case code "a"
73+
new_code = (code + 13) % 26
74+
encrypted_text += chr (new_code + ord('a'))
75+
76+
else:
77+
# Rewrite the remaining characters unchanged
78+
encrypted_text += character
79+
80+
# Print the results
81+
print(encrypted_text)
82+
```
83+
84+
Please copy the example below to a new file (e.g. `rot13.py`), and then run. Please carefully analyze its syntax so that you understand each line. As part of the classes, you will write more advanced programs than the above.
85+
86+
If in doubt, please post on the forum.
87+
88+
## Numeric ranges
89+
90+
It is very often necessary to repeat the loop a specific number of times. We can then use the following form:
91+
92+
<pre>
93+
<b>for</b> <i>counter</i> in <b>range</b>(<i>number_of_repetitions</i>)<b>:</b>
94+
block repeated a given number of times
95+
</pre>
96+
97+
As this loop runs, the counter will go from 0 to the value of *repetitions*–1. Try the following example:
98+
99+
```python
100+
for i in range(10):
101+
print(i)
102+
```
103+
104+
Please note that the number 10 has not been printed.
105+
106+
In fact, `range` is a function that generates a sequence of numbers on the fly, and the **for** loop just iterates over that generated sequence. It can be used in three ways: The most basic and most frequently used `range(stop)` will form a sequence from 0 to the preceding value `stop`. We can also provide the function of two arguments `range(start, stop)`. Then the countdown will start from the value given as `start` (if *start**stop*, the range will be empty and the loop will not run even once). So *range(stop)* is equivalent of *range(0, stop)*. The third version is `range(start, stop, step)` that adds a step used to change the value each time. In this case, the iteration will end when the next value reaches or exceeds the `stop` value.
107+
108+
So to print the numbers from 1 to 10 we can use:
109+
110+
```python
111+
for i in range(1, 11):
112+
print(i)
113+
```
114+
115+
and to do it backwards:
116+
117+
```python
118+
for i in range (10, 0, -1):
119+
print(i)
120+
```
121+
122+
## Exercise
123+
124+
Write a program that asks the user for an integer, then calculates and prints its factorial (that is, the product of the numbers from 1 up to and including the given number ). Your work may be based on the above example for calculating the sum of numbers and on the examples of the range function. Please check if you have calculated 5! is equal to 120 and 10! = 3 628 800.
125+
126+
## Breaking and continuing the loop
127+
128+
As with the while loop, the **`break`** and **`continue`** commands and can be used in the for loop. Their operation is the same as in the case described earlier. Here, too, it is possible to use the **`else:`** block, which will be executed only when the loop ends normally (that is, after it has finished iteration over all elements).
129+
130+
```python
131+
trap = int(input("Enter the trap value:"))
132+
133+
for i in range (1, 11):
134+
if i == trap:
135+
print ("You felt into the trap!")
136+
break
137+
print(i)
138+
else:
139+
print ("You successfully avoided the trap.")
140+
```
141+
142+
## Loop nesting
143+
144+
There are no obstacles to place the other inside one loop. It is only important to use different pointer (counter) names in nested loops. For example, to display the names of all fields on a chessboard, we can use the following program:
145+
146+
```python
147+
for row in range(8, 0, -1): # numbers from 8 to 1 (inclusive) backwards (row 8 will be on top)
148+
for column in "ABCDEFGH":
149+
print(column, row, sep='', end=' ') # the meaning of sep and end was explained before
150+
print() # at the end of each row we only print a newline (default end)
151+
```
152+
153+
<hr/>
154+
155+
Published under [Creative Commons Attribution-NonCommercial-ShareAlike](https://creativecommons.org/licenses/by-nc-sa/4.0/) license.

03 Flow Control/3.md

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

0 commit comments

Comments
 (0)