Skip to content

Commit b05673e

Browse files
Write section about control flow.
1 parent 5a5cff3 commit b05673e

File tree

1 file changed

+259
-8
lines changed

1 file changed

+259
-8
lines changed

welcome/Hello_Python.md

Lines changed: 259 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ This document will jumpstart your understanding of Python. We will cover all the
99
1. [Data Types](#data-types)
1010
2. [Variables](#variables)
1111
3. [Control Flow](#control-flow)
12-
4. [Functions](#functions)
13-
5. [Container Types](#container-types)
12+
4. [Container Types](#container-types)
13+
5. [Functions](#functions)
1414
6. [Credits](#credits)
1515

1616
## Data Types
@@ -186,10 +186,7 @@ Here are examples of when we can interchange values between the `int`, `float`,
186186
```python
187187
print('I am {} years old.'.format(str(29)))
188188
```
189-
190-
```python
191-
str(-3.14)
192-
```
189+
**Note**: don't be intimidated by the syntax of the above statement - it is just another form of string formatting! The result is the program will display a message that says `'I am 29 years old.'`. Please look at the [Python documentation](https://docs.python.org/3/library/stdtypes.html#str.format) if you are curious to learn more.
193190

194191
2. Float to Integer:
195192

@@ -232,6 +229,262 @@ _spam = 'Hello'
232229
Because of how `_spam` is named, we know it is not a variable we should use again in the code.
233230

234231
## Control Flow
232+
While knowing how to store data is nice, it is even cooler to be able to write programs that can let the computer do certain tasks for us.
233+
234+
*Control flow* refers to how the computer figures out what to do with our data in a given situation. This is most often done through giving the computer specific conditions on what to do in a given scenario ahead of time.
235+
236+
For example, you may do this yourself when deciding what clothes to wear outside. You might decide whether to wear sunglasses or not, based on if the sun is shining. If we were to write *pseudocode* for this decision, it might look like the following:
237+
```
238+
if the sun_is_out,
239+
THEN, I will wear_sunglasses()!
240+
```
241+
This process can be almost exactly replicated in Python code - the first piece to making it possible is *comparison operators*!
242+
### Comparison Operators
243+
*Comparison operators* help our program decide whether or not a given piece data meets a given condition.
244+
245+
Table 3 shows the comparison operators found in Python:
246+
##### Table 3: Comparison Operators and What They Mean
247+
248+
| Operator | Meaning |
249+
| -------- | ------------------------ |
250+
| `==` | Equal to |
251+
| `!=` | Not equal to |
252+
| `<` | Less than |
253+
| `>` | Greater Than |
254+
| `<=` | Less than or Equal to |
255+
| `>=` | Greater than or Equal to |
256+
257+
These operators evaluate to True or False depending on the values you give them. They all follow a syntax of `data <operator_goes_here> condition` (but you don't necessarily have to put the `data` on the left side and `condition` on the right).
258+
259+
**Note**: since the result of a comparison operation is only True or False, this means comparison operators *must* return Boolean(`bool`) values.
260+
261+
Here are a few examples of Boolean operations - can you tell if they evaluate to `True` or `False`?
262+
263+
1. With Numeric Data:
264+
```python
265+
42 == 42
266+
```
267+
268+
```python
269+
40 == 42
270+
```
271+
272+
```python
273+
42 == 42.0
274+
```
275+
2. With String Data:
276+
```python
277+
'hello' == 'hello'
278+
```
279+
280+
```python
281+
'dog' != 'cat'
282+
```
283+
284+
```python
285+
42 == '42'
286+
```
287+
**Note**: comparison operators are *case-sensitve* - that is, they will not judge two characters as equal if one is lower case and the other is upper case. The following code snippet demonstrates this:
288+
```python
289+
'hello' == 'Hello'
290+
```
291+
### Boolean Operators
292+
293+
There are also operators specifically meant for working with `bool` values. Specifically, the four Boolean operators are `is`, `and`, `or`, and `not`.
294+
295+
Tables 4-7 show where each of these operators returns `True` or `False`:
296+
297+
298+
##### Table 4: The *is* Operator’s *Truth* Table:
299+
300+
| Expression | Evaluates to |
301+
| --------------- | ------------ |
302+
| True is True | True |
303+
| True is False | False |
304+
| False is True | False |
305+
| False is False | True |
306+
307+
##### Table 5: The *and* Operator’s *Truth* Table:
308+
309+
| Expression | Evaluates to |
310+
| --------------- | ------------ |
311+
| True and True | True |
312+
| True and False | False |
313+
| False and True | False |
314+
| False and False | False |
315+
316+
##### Table 6: The *or* Operator’s *Truth* Table:
317+
318+
| Expression | Evaluates to |
319+
| -------------- | ------------ |
320+
| True or True | True |
321+
| True or False | True |
322+
| False or True | True |
323+
| False or False | False |
324+
325+
##### Table 7: The *not* Operator’s *Truth* Table:
326+
327+
| Expression | Evaluates to |
328+
| ---------- | ------------ |
329+
| not True | False |
330+
| not False | True |
331+
### Boolean evaluation
332+
333+
By convention, Python programmers do not like to use the `==` or `!=` operators to evaluate `bool` values themselves. Instead, it is more popular to use the `is` or `is not` operators.
334+
335+
Examples of What NOT To Do:
336+
337+
```python
338+
True == True
339+
```
340+
341+
```python
342+
True != False
343+
```
344+
345+
Do THIS Instead:
346+
347+
```python
348+
True is True
349+
```
350+
351+
```python
352+
True is not False
353+
```
354+
355+
### Mixing Boolean and Comparison Operators
356+
Just as we saw with mixing single and double quotes in strings, Python is not *totally* against us mixing Boolean and comparison operators. See if you can correctly identify the return value of each expression:
357+
358+
```python
359+
(5 >= 7) and (5 < 6)
360+
```
361+
362+
```python
363+
(1 == 2) or (2 == 2)
364+
```
365+
**Note**: although we are mixing Boolean and comparison operators here, notice how we use parentheses `()` to clearly show the how the Boolean operators `or` and `and` are only working with values that have already been evaluated to be `True` or `False`.
366+
367+
You can also use multiple Boolean operators in an expression, along with those comparison operators:
368+
369+
```python
370+
(4 < 9) and not (-6 < 6) and (2 * 2 == 2 + 2)
371+
```
372+
373+
### if Statements
374+
The `if` statement takes the value computed by a Boolean evaluation, and if it is `True` we can run a specific piece of code to so our program does the appropiate thing in that scenario.
375+
376+
Going back to our sunglasses example above, we are one step closer to writing code that can tell our user when to put on sunglasses:
377+
378+
```python
379+
if is_sun_out == True:
380+
print("You're going to need sunglasses today!")
381+
```
382+
Don't forget to tab over all the code you want to be run in case the `if` statement is `True`!
383+
384+
### else Statements
385+
The `else` statement is a complement to the `if` statement - that is, if the condition in the `if` statement evaluates to `False`, then control flow in our program will go and execute the code found indented below our `else` keyword:
386+
387+
```python
388+
if is_sun_out == True:
389+
print("You're going to need sunglasses today!")
390+
else: # the sun is NOT out
391+
print("You're all set :)")
392+
```
393+
394+
### elif Statements
395+
The `else` keyword is nice, but it cannot be given a condition to evaluate by itself - it *has* to be paired with an `if` statement. This is not a good situation for scenarios where our program needs to be able to do more than just 1 of 2 actions.
396+
397+
This is where the `elif` statement comes in handy - it is short for "else if". Like the `else` statement, it will be evaluated by control flow in our program, if the condition in our `if` statement is `False`. BUT, it can also be given a condition of its own, just like the `if` statement! to allow for writing more nuanced programs!
398+
399+
For example, let's say you usually greet your friends `Andre` and `Rediet` when you first come to school. We can make special greetings for both of our friends in Python, with code such as the following:
400+
401+
```python
402+
name = 'Andre'
403+
404+
if name == 'Andre':
405+
print('Wassup, Andre!')
406+
elif name == 'Rediet':
407+
print('Howdy Rediet')
408+
```
409+
To go one step further, we can use an `if`, `elif`, and `else` all together! In a given program, control flow will only go to the block of code whose condition evaluates to `True`. This lets us write even more nuanced programs, such as being able to greet anyone we meet as we come into school, even if we don't already know their name:
410+
411+
```python
412+
if name == 'Andre':
413+
print('Wassup, Andre!')
414+
elif name == 'Rediet':
415+
print('Howdy Rediet')
416+
else: # name does not have a value yet, for some reason
417+
print('Hey, nice to meet you!')
418+
name = input("What's your name?")
419+
```
420+
421+
### Implicit Boolean Evaluation
422+
It can be cumbersome to write out the full condition for an `if` or `elif` statement all the time - and that's why Python actually lets us take it out if we want:
423+
```python
424+
a = (2 + 2 == 4)
425+
426+
if a is True:
427+
pass
428+
if a is not False:
429+
pass
430+
if a:
431+
pass
432+
```
433+
All of the `if` statements in the code above are equivalent - but that in the last `if` block above, we stopped right at `a`! This is an example of using *implicit boolean evaluation*. It is a great way to save yourself a few keystrokes, and if `a` has a `bool` data type, then this is still valid Python code!
434+
435+
### while Loop Statements
436+
The `while` loop is used just the `if` statement, except that it will exhaustively execute the code in its block. It will only stop once the condition it has evaluates to `False`:
437+
438+
```python
439+
spam = 0
440+
441+
while spam < 5:
442+
print('Hello, world.')
443+
spam = spam + 1
444+
```
445+
446+
### for Loops and the range() Function
447+
Another kind of loop in Python is the `for` loop. Unlike the `while` loop, it doesn't need a condition - instead, `for` loops are used when we already know ahead of time how many *iterations*, or the number of times our code executes, that we want to have.
448+
449+
Therefore, the syntax of the `for` loop is only there to let the program know how many iterations to go through.
450+
451+
```python
452+
print('My name is')
453+
for i in range(5):
454+
print('Jimmy Five Times ({})'.format(str(i)))
455+
```
456+
If you run the code snippet above, you will see the following output:
457+
```
458+
'Jimmy Five Times (0)'
459+
'Jimmy Five Times (1)'
460+
'Jimmy Five Times (2)'
461+
'Jimmy Five Times (3)'
462+
'Jimmy Five Times (4)'
463+
```
464+
Why is this happening?
465+
466+
The `range()` function is commonly used in `for` loops, and it is a good one to remember - it essentially is used to set the value of `i` on each of the 5 iterations our `for` goes through. You may also read more about it on the [Python documentation](https://docs.python.org/3/library/stdtypes.html#range) as you wish.
467+
468+
The `range()` function can also be called with three arguments. The first two arguments will be the *start* and *stop* values, and the third will be the *step* argument. The step is the amount that the variable is increased by after each iteration.
469+
470+
Once the value of our *iterator* (in this case `i`) reaches or surpasses the value of the *stop* argument, our for loop terminates:
471+
472+
```python
473+
for i in range(0, 10, 2):
474+
print(i)
475+
```
476+
**Note**: when we only the `range()` function with 1 argument, then that is the *stop* argument - the defaults for the *start* and *step* parameters are 0 and 1, respectively.
477+
478+
You can even use a negative number for the step argument to make the for loop count down instead of up.
479+
480+
```python
481+
for i in range(5, -1, -1):
482+
print(i)
483+
```
484+
485+
...and that's it for control flow! Being able to use conditional statements like `if`, `elif`, and `else`, as well as being able to write loops will enable us to work with larger and larger datasets using Python. Speaking of which, let's see how Python represents large collections of data the next section, which is all about using container data types!
486+
487+
## Container Types
235488
236489
## Functions
237490
@@ -246,8 +499,6 @@ def foo():
246499
"""
247500
```
248501
249-
## Container Types
250-
251502
## Credits
252503
253504
This section would not be possible if not for the following sources:

0 commit comments

Comments
 (0)