-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpython-conditionals.qmd
More file actions
451 lines (326 loc) · 10.4 KB
/
python-conditionals.qmd
File metadata and controls
451 lines (326 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
---
title: "Python: Conditionals"
subtitle: Python Conditionals
author: Isaac Boixaderas
date: "06/01/2025"
date-modified: last-modified
date-format: full
description: The file system is organized into a hierarchical structure, starting with the root directory
categories: [python, strings]
toc: true
number-sections: true
highlight-style: pygments
format: html
filters:
- pyodide
---
## Overview
::: {.summary .container}
📘 **Conditionals in Python**
In Python, **conditionals** are constructs that control the flow of program execution by evaluating Boolean expressions and determining which code blocks should be run based on whether conditions are true or false. Conditionals allow us to control the flow of code execution, enabling the program to choose between different paths depending on some situation and making it more flexible and dynamic.
:::
---
## Conditionals
Structure of Conditionals
- The primary decision-making tool is the "if" statement, which checks a given condition.
- Using "if-else", the program can specify alternative code paths if the condition is false.
- "elif" allows chaining of multiple mutually exclusive branches, where each is tested in order.
### Logical and Relational Operations
- Conditions are built using relational operators (such as <, >, ==) to compare values.
- Compound conditions use logical operators like "and", "or", and "not", enabling more complex decision logic.
### Truthiness and Flow Control
- Python evaluates condition expressions for "truthiness", meaning any object can be tested for truth value: nonzero numbers, non-empty sequences, or objects evaluate as true, while zeros, empty sequences, or None evaluate as false.
- Indentation (not braces) defines the scope of each conditional block, ensuring only the chosen code sections execute.
### Ternary or Conditional Expressions
```
- Python provides a compact conditional expression (ternary operator) in the form: `<expr1> if <condition> else <expr2>`, allowing assignment or inline decisions without formal control structures.
```
- Only the necessary branch of a conditional expression is evaluated, supporting short-circuiting.
### Advanced Conditional Constructs
- In modern Python, the "match-case" statement allows pattern matching against values, similar to a switch statement in other languages.
Conditionals thus enable Python programs to react to dynamic situations by selectively executing code based on logic and conditions, forming the basis for decision-making and branching in software.
## `if` statements
```
if [condition]:
indented code block
```
---
```python
age = 18
if age >= 18:
# Make sure there is indentation
print("You are eligible to vote.")
print("This line is also inside the `if` block.")
print("This line is outside the `if` block.")
```
<div class="output">You are eligible to vote.<br>This line is also inside the `if` block.<br>This line is outside the `if` block.</div>
---
- If the condition is not met, the code inside it is not executed:
```python
age = 12
if age >= 18:
print("You are eligible to vote.")
print("This line is also inside the `if` block.")
print("This line is outside the `if` block.")
```
<div class="output">This line is outside the `if` block.</div>
---
## `if`-`else` statements
- Allow to execute one block of code if the condition is `True`, and another block if the condition is `False`.
- They never run together, it is just one or the other.
```
if [condition]:
code block
else:
code block
```
---
```python
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
print('hi')
```
<div class="output">You are not eligible to vote.<br>hi</div>
---
- If the condition is met:
```python
age = 20
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
print('hi')
```
<div class="output">You are eligible to vote.<br>hi</div>
---
## `Elif`
- Chain multiple conditions.
- Execute the **first block** of code with a `True` condition and ignore the rest.
```
if [condition]:
code block
elif [condition]:
code block
else:
code block
```
---
- What does this print?
```python
grade = 75
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("D or F")
```
---
```python
grade = 75
if grade >= 90:
print("A")
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("D or F")
```
<div class="output">C</div>
---
- There must be an `if` before an `elif`.
- Same for `else`.
```python
elif grade >= 80:
print("B")
elif grade >= 70:
print("C")
else:
print("D or F")
```
<div class="output">SyntaxError: invalid syntax</div>
---
## Nested conditionals
- We can nest conditions inside conditions for more complexity in decision-making.
- What does this print?
```python
age = 18
citizenship = "Spain"
if age >= 18:
if citizenship == "Spain":
print("You are eligible to vote.")
else:
print("You must be a Spain citizen to vote.")
else:
print("You are not old enough to vote.")
```
---
```python
age = 18
citizenship = "Spain"
if age >= 18:
if citizenship == "Spain":
print("You are eligible to vote.")
else:
print("You must be a Spain citizen to vote.")
else:
print("You are not old enough to vote.")
```
<div class="output">You are eligible to vote.</div>
---
- The same conditions can be expressed in multiple ways:
```python
age = 18
citizenship = "Spain"
if citizenship == "Spain":
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not old enough to vote.")
else:
print("You must be a Spain citizen to vote.")
```
<div class="output">You are eligible to vote.</div>
---
```python
age = 18
citizenship = "Spain"
if citizenship != "Spain":
print("You must be a Spain citizen to vote.")
else:
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not old enough to vote.")
```
<div class="output">You are eligible to vote.</div>
---
- We could also write the code without nesting, although it is maybe a bit more difficult to understand:
```python
age = 18
citizenship = "Spain"
if age >= 18 and citizenship == "Spain":
print("You are eligible to vote.")
elif age >= 18:
print("You must be a Spain citizen to vote.")
else:
print("You are not old enough to vote.")
```
<div class="output">You are eligible to vote.</div>
---
```python
age = 18
citizenship = "Spain"
if citizenship != "Spain":
print("You must be a Spain citizen to vote.")
elif age >= 18:
print("You are eligible to vote.")
else:
print("You are not old enough to vote.")
```
<div class="output">You are eligible to vote.</div>
---
## Conditional variable assignation
- Set a value to a variable depending on a condition:
```python
age = 18
if age >= 18:
eligibility = "eligible"
else:
eligibility = "not eligible"
print(f"You are {eligibility} to vote.")
```
<div class="output">You are eligible to vote.</div>
---
## Ternary operator
- Shorter way to write if-else statements.
- Use them only if the code is simple.
- Same code as before but in a single line:
```python
age = 18
eligibility = "eligible" if age >= 18 else "not eligible"
print(f"You are {eligibility} to vote.")
```
<div class="output">You are eligible to vote.</div>
---
## Best practices
- Keep code blocks simple and focused, handling one specific task or condition.
- Use parentheses for complex conditions to improve readability.
- If needed, you can write multi-line code in Python by using the `\` at the end of the line.
---
## Example
- Website membership levels and restrictions.
- What does this print?
```python
membership_level = "premium"
account_age_days = 45
num_posts_created = 12
# Check if user is allowed to create a post
if (membership_level == "free" and num_posts_created < 10) or \
(membership_level == "basic" and num_posts_created < 30) or \
(membership_level == "premium" and num_posts_created < 100) or \
(membership_level == "unlimited" or account_age_days >= 365):
print("You are allowed to create more posts.")
else:
print("You have reached your limit on the number of posts.")
```
---
```python
membership_level = "premium"
account_age_days = 45
num_posts_created = 12
# Check if user is allowed to create a post
if (membership_level == "free" and num_posts_created < 10) or \
(membership_level == "basic" and num_posts_created < 30) or \
(membership_level == "premium" and num_posts_created < 100) or \
(membership_level == "unlimited" or account_age_days >= 365):
print("You are allowed to create more posts.")
else:
print("You have reached your limit on the number of posts.")
```
<div class="output">You are allowed to create more posts.</div>
## Exercises
### Density calculator (to my ❤️ daughter Emma )
`DensityCalculator` without functions to calculate the density of a given object and return it. The density is calculated using the formula mass / volume. The user assumes that the density is given in kg/m3 as the mass is in kilogrames and the volume could be selected in different units (ml, m3, cl, mm3, cm3, dm3, l, hl).
```{pyodide-python}
# Calculador de densidad en kg/m³ con varias unidades de volumen
# Pedir la masa al usuario (kg)
# masa = float(input("Introduce la masa en kg: "))
# Mostrar las opciones de unidades posibles
print("Unidades aceptadas: ml, m3, cl, mm3, cm3, dm3, l, hl")
# Pedir el volumen al usuario en la unidad elegida
# unidad = input("¿En qué unidad está el volumen (ml, m3, cl, mm3, cm3, dm3, l, hl)? ").strip().lower()
masa = 20
unidad = "ml"
volumen = 10.5
#Las diferentes formas de calcular la densidad dependiendo la unidad de medida del volumen introducido
if unidad == "ml":
volumen_m3 = volumen * 0.000001
elif unidad == "m3":
volumen_m3 = volumen
elif unidad == "cl":
volumen_m3 = volumen * 0.00001
elif unidad == "mm3":
volumen_m3 = volumen * 0.000000001
elif unidad == "cm3":
volumen_m3 = volumen * 0.000001
elif unidad == "dm3":
volumen_m3 = volumen * 0.001
elif unidad == "l":
volumen_m3 = volumen * 0.001
elif unidad == "hl":
volumen_m3 = volumen * 0.1
else:
print("Unidad no válida.")
exit()
#Calculo de la densidad
densidad = masa / volumen_m3
# Enseñar al usuario el valor de la densidad calculada y la unidad de volumen elegida
print(f"Densidad: {densidad:.2f} kg/m³ (volumen introducido en {unidad})")
```