-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPython_programming_data_analysis_ai.qmd
More file actions
3520 lines (2480 loc) · 79.3 KB
/
Copy pathPython_programming_data_analysis_ai.qmd
File metadata and controls
3520 lines (2480 loc) · 79.3 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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Python Programming and Data Analysis in the Age of AI"
subtitle: "A beginner-friendly teaching document for undergraduate students"
author: "Prepared for summer undergraduate instruction"
date: today
format:
html:
toc: true
toc-depth: 3
number-sections: true
code-fold: false
theme: cosmo
pdf:
toc: true
number-sections: true
execute:
eval: false
echo: true
jupyter: python3
---
# How to use this document
This document is designed for students who are new to programming. It uses Python as the main language for learning programming and then applies Python to data analysis and plotting.
The document can support a summer semester course, a short bootcamp, or a self-study module. It starts with the question "What is programming?" and gradually builds toward practical analysis with data tables, files, and **visualizations**.
::: {.callout-tip}
## Teaching suggestion
For a summer semester, this material can be taught in 8 to 12 weeks. Each major part can be a week or a two-class unit, depending on the pace of the course and how much practice time students need.
:::
## Learning goals
By the end of this document, students should be able to:
1. Explain what a program is and how Python runs code.
2. Use **variables**, expressions, functions, **conditionals**, loops, and collections.
3. Read error messages and debug small programs.
4. Work with files and structured data.
5. Use Python libraries such as `math`, `random`, `pathlib`, `csv`, `json`, `numpy`, `pandas`, and `matplotlib`.
6. Clean, summarize, filter, group, and visualize data.
7. Compare basic Python ideas with JavaScript and C#.
8. Use **AI** tools responsibly as programming assistants, not as replacements for understanding.
## Suggested course structure
| Unit | Topic | Main skills |
|---|---|---|
| 1 | What programming is | Algorithms, syntax, variables, expressions |
| 2 | Basic Python | Types, strings, input/output, operators |
| 3 | Control flow | `if`, `elif`, `else`, Boolean logic |
| 4 | Loops | `for`, `while`, `range`, `break`, `continue` |
| 5 | Collections | Lists, tuples, dictionaries, sets |
| 6 | Functions | Parameters, return values, scope, type hints |
| 7 | Debugging and files | Errors, exceptions, text files, CSV, JSON |
| 8 | Data analysis | NumPy, pandas, tabular thinking |
| 9 | Plotting | Matplotlib, chart types, visual clarity |
| 10 | Mini-projects | End-to-end analysis and presentation |
| 11 | Python vs. JS/C# | Similar concepts, different syntax and habits |
| 12 | AI-assisted programming | Prompting, verification, testing, ethics |
# Part I: Programming fundamentals
# What is programming?
Programming is the practice of writing instructions that a computer can follow.
A program is not magic. It is a precise set of steps written in a programming language. The computer follows those steps exactly, even when the steps are wrong.
For example, a human instruction might be:
> Calculate the average score for the class.
A computer needs something more precise:
```{python}
scores = [82, 91, 77, 88, 95]
average = sum(scores) / len(scores)
print(average)
```
This program says:
1. Store five scores in a **list**.
2. Add the scores.
3. Count how many scores there are.
4. Divide the total by the count.
5. Print the result.
## Programs, data, and algorithms
Three important ideas appear throughout the course.
| Concept | Meaning | Example |
|---|---|---|
| Data | Information a program uses | Numbers, names, dates, tables |
| Algorithm | A step-by-step method | Sort values from smallest to largest |
| Program | An algorithm written in code | A Python file that reads data and makes a chart |
An algorithm can exist before code. For example, the algorithm for finding the largest value in a **list** is:
1. Start with the first value as the largest value seen so far.
2. Look at each remaining value.
3. If the current value is larger than the largest value seen so far, replace it.
4. After checking all values, report the largest value.
In Python:
```{python}
numbers = [12, 5, 19, 3, 14]
largest = numbers[0]
for number in numbers:
if number > largest:
largest = number
print(largest)
```
## Syntax and semantics
**Programming languages** have syntax and semantics.
Syntax means the grammar of code. It answers: Is the code written in a form Python understands?
Semantics means the meaning of the code. It answers: Does the code do what we intended?
This code has a syntax error because the closing parenthesis is missing:
```{python}
print("Hello"
```
This code has valid syntax but wrong semantics if the goal is to calculate an average:
```{python}
scores = [80, 90, 100]
wrong_average = sum(scores) # forgot to divide by the number of scores
print(wrong_average)
```
A major part of learning programming is learning to diagnose both kinds of problems.
## Why Python?
Python is commonly used for teaching because it has readable syntax and supports many styles of programming. It is also widely used in data analysis, automation, web development, scientific computing, machine learning, and artificial intelligence workflows.
Python is an interpreted language. In beginner terms, that means you can run Python code directly and see results quickly. Python also has a large ecosystem of packages, which are reusable tools written by other programmers.
## A first Python program
```{python}
print("Hello, Python!")
```
The word `print` is the name of a built-in function. A function is a reusable action. Here, the action displays text.
The text `"Hello, Python!"` is a string, which means a piece of text.
## Comments
Comments are notes for humans. Python ignores comments when running the program.
```{python}
# This is a comment.
# It explains what the code is doing.
name = "Maya"
print("Hello,", name)
```
Good comments explain why something is being done, not only what the code already says.
```{python}
# Good: the curve is nonlinear, so a log scale makes the trend easier to see.
# Less useful: print the variable x.
print(x)
```
# Running Python code
Students commonly run Python in three ways.
| Method | Description | Good for |
|---|---|---|
| Interactive shell / REPL | Type one line at a time and immediately see results | Quick experiments |
| Script file | Save code in a `.py` file and run it | Reusable programs |
| Notebook / Quarto document | Mix code, text, output, and plots | Data analysis and teaching |
This document is written in Quarto Markdown (`.qmd`). A Quarto document can contain formatted text and executable code cells. For example:
````markdown
```{python}
print("This code cell can run in Quarto.")
```
````
In this teaching document, the global setting `execute: eval: false` means code cells are displayed but not automatically executed when rendered. In class, an instructor can change that setting or run code interactively.
## Installing packages
Python includes many built-in tools, but data analysis usually needs external packages.
Common beginner packages:
| Package | Purpose |
|---|---|
| `numpy` | Fast numerical arrays and mathematical operations |
| `pandas` | Tables and data analysis |
| `matplotlib` | Plotting and visualization |
| `jupyter` | Interactive notebooks |
A common command-line installation pattern is:
```bash
python -m pip install numpy pandas matplotlib jupyter
```
For a class, it is often easier to provide one controlled environment instead of asking every student to configure their computer from scratch. Options include a university JupyterHub, cloud notebooks, a prebuilt conda environment, or a shared `requirements.txt` file.
# Variables and expressions
A variable is a name that refers to a value.
```{python}
age = 20
name = "Alex"
gpa = 3.72
is_enrolled = True
print(name)
print(age)
```
A useful beginner mental model is:
> A variable is a label attached to a value.
The assignment operator `=` stores a value under a name.
```{python}
x = 10
x = x + 5
print(x)
```
The line `x = x + 5` means:
1. Look up the current value of `x`.
2. Add `5`.
3. Store the new result back into `x`.
It does not mean mathematical equality. In mathematics, `x = x + 5` is impossible. In Python, it is an instruction.
## Expressions
An expression is a piece of code that produces a value.
```{python}
2 + 3
10 * 4
"data" + " analysis"
len("Python")
```
A statement is a complete instruction.
```{python}
message = "Welcome to Python"
print(message)
```
## Naming variables
Good variable names make code easier to understand.
```{python}
# Clear
student_count = 42
average_score = 88.5
# Unclear
sc = 42
x = 88.5
```
Python naming habits:
- Use lowercase words separated by underscores: `average_score`.
- Start with a letter or underscore, not a number.
- Avoid names that are already built in, such as `list`, `dict`, `sum`, or `type`.
- Choose names that describe the data, not just the data type.
# Basic data types
A data type describes what kind of value something is and what operations make sense for it.
| Type | Meaning | Example |
|---|---|---|
| `int` | Integer | `42` |
| `float` | Decimal number | `3.14` |
| `str` | Text string | `"hello"` |
| `bool` | Boolean truth value | `True`, `False` |
| `NoneType` | Absence of a value | `None` |
Use `type()` to inspect a value's type.
```{python}
print(type(42))
print(type(3.14))
print(type("hello"))
print(type(True))
print(type(None))
```
## Numbers
```{python}
a = 10
b = 3
print(a + b) # addition
print(a - b) # subtraction
print(a * b) # multiplication
print(a / b) # division, always produces a float
print(a // b) # integer division
print(a % b) # remainder
print(a ** b) # exponentiation
```
The `%` operator is useful for checking divisibility.
```{python}
number = 17
if number % 2 == 0:
print("even")
else:
print("odd")
```
## Floating-point numbers
Computers approximate many decimal values. This can surprise beginners.
```{python}
print(0.1 + 0.2)
```
The result may not display exactly as `0.3`. For most data analysis this is normal, but students should avoid testing floating-point values for exact equality when small rounding differences are possible.
```{python}
value = 0.1 + 0.2
print(abs(value - 0.3) < 0.000001)
```
## Strings
Strings are text values.
```{python}
first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name
print(full_name)
```
Strings can use single or double quotes.
```{python}
course = 'Python Programming'
semester = "Summer"
```
Use whichever makes the string easier to read.
```{python}
message = "It's a good day to learn Python."
```
## String methods
A method is a function attached to an object. Strings have many useful methods.
```{python}
text = " Data Analysis with Python "
print(text.lower())
print(text.upper())
print(text.strip())
print(text.replace("Python", "pandas"))
print(text.startswith(" Data"))
```
Strings are sequences, so you can index and slice them.
```{python}
word = "Python"
print(word[0]) # first character
print(word[-1]) # last character
print(word[0:3]) # characters at index 0, 1, 2
print(word[3:]) # from index 3 to the end
```
Python uses zero-based indexing: the first position is index `0`.
## Formatted strings
Formatted strings, often called f-strings, make it easy to insert values into text.
```{python}
name = "Sam"
score = 91.236
print(f"{name} scored {score} points.")
print(f"{name} scored {score:.1f} points.")
```
The format `:.1f` means display one digit after the decimal point.
## Booleans
Booleans represent truth values.
```{python}
is_raining = False
has_umbrella = True
print(is_raining)
print(has_umbrella)
```
Booleans are central to decision-making.
```{python}
temperature = 32
is_freezing = temperature <= 32
print(is_freezing)
```
## `None`
`None` represents the absence of a value.
```{python}
middle_name = None
print(middle_name)
```
`None` is useful when a value is unknown, missing, not yet computed, or intentionally empty.
```{python}
best_score = None
scores = [82, 91, 77]
for score in scores:
if best_score is None or score > best_score:
best_score = score
print(best_score)
```
# Input and output
Output means information the program shows to the user. The most basic output tool is `print()`.
```{python}
print("Welcome")
print(2 + 3)
```
Input means information the user gives to the program. The basic input tool is `input()`.
```{python}
name = input("What is your name? ")
print(f"Hello, {name}!")
```
`input()` always returns a string. Convert it when you need a number.
```{python}
age_text = input("How old are you? ")
age = int(age_text)
print(f"Next year you will be {age + 1}.")
```
A shorter version:
```{python}
age = int(input("How old are you? "))
print(f"Next year you will be {age + 1}.")
```
Common conversion functions:
| Function | Converts to |
|---|---|
| `int()` | Integer |
| `float()` | Decimal number |
| `str()` | String |
| `bool()` | Boolean |
::: {.callout-warning}
## Beginner warning
`bool("False")` is `True` because non-empty strings are treated as true. Do not use `bool()` to parse user text like `"yes"` or `"no"` without writing your own logic.
:::
# Practice: basic expressions
1. Create **variables** for your name, major, year in school, and favorite number. Print one sentence using all four variables.
2. Ask a user for a temperature in Celsius and convert it to Fahrenheit using `F = C * 9/5 + 32`.
3. Ask a user for three exam scores and print the average.
4. Write a program that asks for a number of minutes and converts it to hours and minutes.
Example solution for exercise 4:
```{python}
total_minutes = int(input("Enter minutes: "))
hours = total_minutes // 60
minutes = total_minutes % 60
print(f"{total_minutes} minutes is {hours} hours and {minutes} minutes.")
```
# Part II: Control flow
# Making decisions with `if`
Programs often need to choose between different actions.
```{python}
score = 87
if score >= 90:
print("A")
elif score >= 80:
print("B")
elif score >= 70:
print("C")
else:
print("Needs improvement")
```
The keywords mean:
| Keyword | Meaning |
|---|---|
| `if` | Check the first condition |
| `elif` | Check another condition if previous conditions were false |
| `else` | Run this block if no previous condition was true |
## Indentation
Python uses indentation to show which lines belong together.
```{python}
age = 19
if age >= 18:
print("You are an adult.")
print("This line is also inside the if block.")
print("This line always runs.")
```
Indentation is not just style in Python. It changes the meaning of the program.
## Comparison operators
| Operator | Meaning | Example |
|---|---|---|
| `==` | equal to | `x == 5` |
| `!=` | not equal to | `x != 5` |
| `<` | less than | `x < 5` |
| `<=` | less than or equal to | `x <= 5` |
| `>` | greater than | `x > 5` |
| `>=` | greater than or equal to | `x >= 5` |
A common beginner mistake is confusing `=` and `==`.
```{python}
x = 5 # assignment: store 5 in x
x == 5 # comparison: ask whether x equals 5
```
## Boolean operators
Use `and`, `or`, and `not` to combine conditions.
```{python}
age = 20
has_id = True
if age >= 18 and has_id:
print("Entry allowed")
else:
print("Entry denied")
```
```{python}
is_weekend = True
is_holiday = False
if is_weekend or is_holiday:
print("No class today")
```
```{python}
is_logged_in = False
if not is_logged_in:
print("Please log in")
```
## Truthiness
Python can treat values as true or false in conditions.
Usually false:
- `False`
- `None`
- `0`
- `0.0`
- `""` empty string
- `[]` empty **list**
- `{}` empty dictionary
Usually true:
- Nonzero numbers
- Non-empty strings
- Non-empty lists
- Non-empty **dictionaries**
```{python}
name = ""
if name:
print(f"Hello, {name}")
else:
print("Name is missing")
```
Use truthiness carefully. It is convenient, but explicit comparisons are sometimes clearer for beginners.
# Loops
A loop repeats code.
Python has two main kinds of loops:
| Loop | Best when |
|---|---|
| `for` loop | You know what collection or range you want to iterate over |
| `while` loop | You want to repeat until a condition changes |
## `for` loops
A `for` loop repeats once for each item in a sequence.
```{python}
names = ["Ava", "Ben", "Chen"]
for name in names:
print(f"Hello, {name}")
```
The variable `name` takes one value at a time from the **list**.
## `range()`
`range()` creates a sequence of integers.
```{python}
for i in range(5):
print(i)
```
This prints `0`, `1`, `2`, `3`, and `4`.
Useful patterns:
```{python}
for i in range(1, 6):
print(i) # 1 through 5
for i in range(2, 11, 2):
print(i) # 2, 4, 6, 8, 10
```
## Accumulating values
Loops often accumulate a result.
```{python}
scores = [82, 91, 77, 88]
total = 0
for score in scores:
total = total + score
average = total / len(scores)
print(average)
```
Python also has built-in functions for common operations.
```{python}
scores = [82, 91, 77, 88]
print(sum(scores) / len(scores))
```
Students should learn both versions. The manual loop teaches the algorithm. The built-in version is usually the better practical code.
## Counting with a loop
```{python}
scores = [82, 91, 77, 88, 95, 69]
passing_count = 0
for score in scores:
if score >= 70:
passing_count = passing_count + 1
print(passing_count)
```
Shorter version:
```{python}
scores = [82, 91, 77, 88, 95, 69]
passing_count = sum(1 for score in scores if score >= 70)
print(passing_count)
```
The shorter version is idiomatic, but the longer version is easier for beginners to understand first.
## `while` loops
A `while` loop repeats as long as a condition is true.
```{python}
count = 1
while count <= 5:
print(count)
count = count + 1
```
`while` loops are useful for repeated input, simulations, and situations where the number of repetitions is not known in advance.
```{python}
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted")
```
::: {.callout-warning}
## Infinite loops
A `while` loop can run forever if the condition never becomes false. Make sure something inside the loop changes the condition.
:::
## `break` and `continue`
`break` exits a loop early.
```{python}
numbers = [3, 7, 11, 18, 21]
for number in numbers:
if number % 2 == 0:
print(f"First even number: {number}")
break
```
`continue` skips to the next iteration.
```{python}
numbers = [3, -2, 7, -5, 10]
for number in numbers:
if number < 0:
continue
print(number)
```
Use `break` and `continue` when they make code clearer. Avoid using them so heavily that the loop becomes hard to follow.
## `enumerate()`
Use `enumerate()` when you need both an index and a value.
```{python}
names = ["Ava", "Ben", "Chen"]
for index, name in enumerate(names):
print(index, name)
```
Use `start=1` when displaying human-friendly numbering.
```{python}
for rank, name in enumerate(names, start=1):
print(f"{rank}. {name}")
```
## `zip()`
Use `zip()` to loop over two or more sequences at the same time.
```{python}
names = ["Ava", "Ben", "Chen"]
scores = [91, 85, 93]
for name, score in zip(names, scores):
print(f"{name}: {score}")
```
# Practice: conditionals and loops
1. Write a program that asks for a score and prints the letter grade.
2. Write a program that prints every number from 1 to 100 divisible by 7.
3. Given a **list** of temperatures, count how many are above 90.
4. Ask the user to enter numbers until they type `done`, then print the average.
5. Write a guessing game where the computer has a secret number and the user guesses until correct.
Example solution for exercise 4:
```{python}
total = 0
count = 0
while True:
text = input("Enter a number or 'done': ")
if text == "done":
break
number = float(text)
total = total + number
count = count + 1
if count > 0:
print(f"Average: {total / count}")
else:
print("No numbers were entered.")
```
# Collections
Collections store multiple values.
| Collection | Ordered? | Mutable? | Typical use |
|---|---:|---:|---|
| `list` | Yes | Yes | A sequence of values that may change |
| `tuple` | Yes | No | A fixed group of related values |
| `dict` | In insertion order | Yes | Key-value lookup |
| `set` | No | Yes | Unique values and membership tests |
# Lists
A **list** stores an ordered sequence of values.
```{python}
scores = [82, 91, 77, 88]
print(scores)
```
Lists can contain values of different types, but in data analysis lists usually contain values of the same kind.
```{python}
items = ["notebook", 3, True]
```
## Indexing and slicing lists
```{python}
scores = [82, 91, 77, 88]
print(scores[0]) # first item
print(scores[-1]) # last item
print(scores[1:3]) # items at index 1 and 2
```
## Changing lists
Lists are mutable, meaning they can be changed.
```{python}
scores = [82, 91, 77]
scores.append(88)
print(scores)
scores[0] = 85
print(scores)
scores.remove(77)
print(scores)
```
Common **list** methods:
| Method | Description |
|---|---|
| `.append(x)` | Add `x` to the end |
| `.extend(other_list)` | Add all items from another list |
| `.insert(i, x)` | Insert `x` at position `i` |
| `.remove(x)` | Remove the first matching value |
| `.pop()` | Remove and return the last item |
| `.sort()` | Sort the list in place |
| `.copy()` | Make a shallow copy |
## Sorting lists
```{python}
scores = [82, 91, 77, 88]
print(sorted(scores)) # returns a new sorted list
print(scores) # original list is unchanged
scores.sort() # changes the original list
print(scores)
```
Use `sorted()` when you want a new **list**. Use `.sort()` when you want to modify the existing list.
## List comprehensions
A **list** comprehension creates a list from another sequence in a compact way.
```{python}
numbers = [1, 2, 3, 4, 5]
squares = [number ** 2 for number in numbers]
print(squares)
```
With a condition:
```{python}
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = [number for number in numbers if number % 2 == 0]
print(even_numbers)
```
Equivalent loop:
```{python}
even_numbers = []
for number in numbers:
if number % 2 == 0:
even_numbers.append(number)
```
Comprehensions are useful, but clarity is more important than cleverness.
# Tuples
A tuple is an ordered collection that cannot be changed after creation.
```{python}
point = (3, 4)
print(point[0])
print(point[1])
```
Tuples are often used for fixed groups of related values.
```{python}
student_record = ("Ava", 91)
name, score = student_record
print(name)
print(score)
```
The assignment `name, score = student_record` is called unpacking.
```{python}
x, y = (10, 20)
print(x)
print(y)
```
# Dictionaries
A dictionary stores key-value pairs.
```{python}
student = {
"name": "Ava",
"major": "Biology",
"score": 91
}