-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathp_foundations_coding_basics.qmd
681 lines (450 loc) · 17.4 KB
/
p_foundations_coding_basics.qmd
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
---
title: 'Coding basics'
---
{{< video https://youtu.be/3smPFwv5bPU?si=JKcbGrTKfbGxRR1x >}}
## Learning Objectives
1. You can write and use comments in Python (single-line and multi-line).
2. You know how to use Python as a calculator for basic arithmetic operations and understand the order of operations.
3. You can use the math library for more complex mathematical operations.
4. You understand how to use proper spacing in Python code to improve readability.
5. You can create, manipulate, and reassign variables of different types (string, int, float).
6. You can get user input and perform calculations with it.
7. You understand the basic rules and best practices for naming variables in Python.
8. You can identify and fix common errors related to variable usage and naming.
## Introduction
In this lesson, you will learn the basics of using Python.
To get started, open your preferred Python environment (e.g., Jupyter Notebook, VS Code, or PyCharm), and create a new Python file or notebook.
Next, **save the file** with a name like "coding_basics.py" or "coding_basics.ipynb" depending on your environment.
You should now type all the code from this lesson into that file.
## Comments
Comments are text that is ignored by Python. They are used to explain what the code is doing.
You use the symbol `#`, pronounced "hash" or "pound", to start a comment. Anything after the `#` on the same line is ignored. For example:
```{python}
# Addition
2 + 2
```
If we just tried to write `Addition` above the code, it would cause an error:
```{python}
# | eval: False
Addition
2 + 2
```
```
NameError: name 'Addition' is not defined
```
We can put the comment on the same line as the code, but it needs to come after the code.
```{python}
2 + 2 # Addition
```
To write multiple lines of comments, you can either add more `#` symbols:
```{python}
# Addition
# Add two numbers
2 + 2
```
Or you can use triple quotes `'''` or `"""`:
```{python}
'''
Addition:
Below we add two numbers
'''
2 + 2
```
Or:
```{python}
"""
Addition:
Below we add two numbers
"""
2 + 2
```
::: {.callout-note title='Vocab'}
**Comment**: A piece of text in your code that is ignored by Python. Comments are used to explain what the code is doing and are meant for human readers.
:::
::: {.callout-tip title='Practice'}
## Practice Q: Commenting in Python
Which of the following code chunks are valid ways to comment code in Python?
```
# add two numbers
2 + 2
```
```
2 + 2 # add two numbers
```
```
''' add two numbers
2 + 2
```
```
# add two numbers 2 + 2
```
Check your answer by trying to run each code chunk.
:::
## Python as a Calculator
As you have already seen, Python works as a calculator in standard ways.
Below are some other examples of basic arithmetic operations:
```{python}
2 - 2 # two minus two
```
```{python}
2 * 2 # two times two
```
```{python}
2 / 2 # two divided by two
```
```{python}
2 ** 2 # two raised to the power of two
```
There are a few other operators you may come across. For example, `%` is the modulo operator, which returns the remainder of the division.
```{python}
10 % 3 # ten modulo three
```
`//` is the floor division operator, which divides then rounds down to the nearest whole number.
```{python}
10 // 3 # ten floor division three
```
::: {.callout-tip title='Practice'}
## Practice Q: Modulo and Floor Division
Guess the result of the following code chunks then run them to check your answer:
```{python}
# | eval: False
5 % 4
```
```{python}
# | eval: False
5 // 4
```
:::
## Order of Operations
Python obeys the standard PEMDAS order of operations (Parentheses, Exponents, Multiplication, Division, Addition, Subtraction).
For example, multiplication is evaluated before addition, so below the result is `6`.
```{python}
2 + 2 * 2
```
::: {.callout-tip title='Practice'}
## Practice Q: Evaluating Arithmetic Expressions
Which, if any, of the following code chunks will evaluate to `10`?
```{python}
# | eval: False
2 + 2 * 4
```
```{python}
# | eval: False
6 + 2 ** 2
```
:::
## Using the Math Library
We can also use the `math` library to do more complex mathematical operations. For example, we can use the `math.sqrt` function to calculate the square root of a number.
```{python}
import math
math.sqrt(100) # square root
```
Or we can use the `math.log` function to calculate the natural logarithm of a number.
```{python}
import math
math.log(100) # logarithm
```
`math.sqrt` and `math.log` are examples of Python *functions*, where an *argument* (e.g., `100`) is passed to the function to perform a calculation.
We will learn more about functions later.
::: {.callout-note title='Vocab'}
**Function**: A reusable block of code that performs a specific task. Functions often take inputs (called arguments) and return outputs.
:::
::: {.callout-tip title='Practice'}
## Practice Q: Using the Math Library
Using the `math` library, calculate the square root of 81.
Write your code below and run it to check your answers:
```{python}
# Your code here
```
## Practice Q: Describing the Use of the Random Library
Consider the following code, which generates a random number between 1 and 10:
```{python}
import random
random.randint(1, 10)
```
In that code, identify the library, the function, and the argument(s) to the function.
:::
## Spacing in Code
Good spacing makes your code easier to read. In Python, two simple spacing practices can greatly improve your code's readability: using blank lines and adding spaces around operators.
## Indentation
Python uses indentation to indicate the start and end of loops, functions, and other blocks of code. We'll look at this more in later lessons.
For now, one thing to watch out for is to avoid accidentally including a space before your code
For example, consider the following code chunk:
```{python}
# | eval: false
import math
# Get the square root of 100
math.sqrt(100)
```
Trying to run this code will cause an error:
```
IndentationError: unexpected indent
```
This is due to the space before the `math.sqrt` function. We can fix this by removing the space.
```{python}
# | eval: false
import math
# Get the square root of 100
math.sqrt(100)
```
## Blank Lines
Use blank lines to separate different parts of your code.
For example, consider the following code chunk:
```{python}
# Set up numbers
x = 5
y = 10
# Perform calculation
result = x + y
# Display result
print(result)
```
We can add blank lines to separate the different parts of the code:
```{python}
# Set up numbers
x = 5
y = 10
# Perform calculation
result = x + y
# Display result
print(result)
```
Blank lines help organize your code into logical sections, similar to paragraphs in writing.
## Spaces Around Operators
Adding spaces around mathematical operators improves readability:
```{python}
# Hard to read
x=5+3*2
# Easy to read
x = 5 + 3 * 2
```
When listing items, add a space after each comma:
```{python}
# | eval: False
# Hard to read
print(1,2,3)
# Easy to read
print(1, 2, 3)
```
This practice follows the convention in written English, where we put a space after a comma. It makes lists of items in your code easier to read.
## Variables in Python
As you have seen, to store a value for future use in Python, we assign it to a *variable* with the *assignment operator*, `=`.
```{python}
my_var = 2 + 2 # assign the result of `2 + 2 ` to the variable called `my_var`
print(my_var) # print my_var
```
Now that you've created the variable `my_var`, Python knows about it and will keep track of it during this Python session.
You can open your environment to see what variables you have created. This looks different depending on your IDE.
So what exactly is a variable? Think of it as a named container that can hold a value. When you run the code below:
```{python}
my_var = 20
```
you are telling Python, "store the number 20 in a variable named 'my_var'".
Once the code is run, we would say, in Python terms, that "the value of variable `my_var` is 20".
Try to come up with a similar sentence for this code chunk:
```{python}
first_name = "Joanna"
```
After we run this code, we would say, in Python terms, that "the value of the `first_name` variable is Joanna".
::: {.callout-note title='Vocab'}
A text value like "Joanna" is called a **string**, while a number like 20 is called an **integer**. If the number has a decimal point, it is called a **float**, which is short for "floating-point number".
Below are these three types of variables:
```{python}
# string variable
first_name = "Joanna"
# integer variable
age = 5
# float variable
height = 1.4
```
You can check the type of a variable using the `type()` function.
```{python}
print(type(first_name))
print(type(age))
print(type(height))
```
:::
::: {.callout-note title='Vocab'}
**Variable**: A named container that can hold a value. In Python, variables can store different types of data, including numbers, strings, and more complex objects.
:::
## Reassigning Variables
Reassigning a variable is like changing the contents of a container.
For example, previously we ran this code to store the value "Joanna" inside the `first_name` variable:
```{python}
first_name = "Joanna"
```
To change this to a different value, simply run a new assignment statement with a new value:
```{python}
first_name = "Luigi"
```
You can print the variable to observe the change:
```{python}
first_name
```
## Working with Variables
Most of your time in Python will be spent manipulating variables. Let's see some quick examples.
You can run simple commands on variables. For example, below we store the value `100` in a variable and then take the square root of the variable:
```{python}
import math
my_number = 100
math.sqrt(my_number)
```
Python "sees" `my_number` as the number 100, and so is able to evaluate its square root.
------------------------------------------------------------------------
You can also combine existing variables to create new variables. For example, type out the code below to add `my_number` to itself, and store the result in a new variable called `my_sum`:
```{python}
my_sum = my_number + my_number
my_sum
```
What should be the value of `my_sum`? First take a guess, then check it by printing it.
------------------------------------------------------------------------
Python also allows us to concatenate strings with the `+` operator. For example, we can concatenate the `first_name` and `last_name` variables to create a new variable called `full_name`:
```{python}
first_name = "Joanna"
last_name = "Luigi"
full_name = first_name + " " + last_name
full_name
```
::: {.callout-tip title='Practice'}
## Practice Q: Variable Assignment and Manipulation
Consider the code below. What is the value of the `answer` variable? Think about it, then run the code to check your answer.
```{python}
# | eval: False
eight = 9
answer = eight - 8
answer
```
:::
## Getting User Input
Though it's not used often in data analysis, the `input()` function from Python is a cool Python feature that you should know about. It allows you to get input from the user.
Here's a simple example. We can request user input and store it in a variable called `name`.
```{python}
#| eval: false
name = input()
```
And then we can print a greeting to the user.
```{python}
#| eval: false
print("Hello,", name)
```
We can also include a question for the input prompt:
```{python}
#| eval: false
name = input('What is your name? ')
print("Hello,", name)
```
Let's see another example. We'll tell the user how many letters are in their name.
```{python}
#| eval: false
name = input('What is your name? ')
print("There are", len(name), "letters in your name")
```
For instance, if you run this code and enter "Kene", you might see:
```
What is your name? Kene
There are 4 letters in your name
```
::: {.callout-tip title='Practice'}
## Practice Q: Using Input()
Write a short program that asks the user for their favorite color and then prints a message saying "xx color is my favorite color too!", where xx is the color they entered. Test your program by running it and entering a color.
:::
## Common Error with Variables
One of the most common errors you'll encounter when working with variables in Python is the `NameError`. This occurs when you try to use a variable that hasn't been defined yet. For example:
```{python}
# | eval: False
my_number = 48 # define `my_number`
My_number + 2 # attempt to add 2 to `my_number`
```
If you run this code, you'll get an error message like this:
```
NameError: name 'My_number' is not defined
```
Here, Python returns an error message because we haven't created (or *defined*) the variable `My_number` yet. Recall that Python is case-sensitive; we defined `my_number` but tried to use `My_number`.
To fix this, make sure you're using the correct variable name:
```{python}
my_number = 48
my_number + 2 # This will work and return 50
```
Always double-check your variable names to avoid this error. Remember, in Python, `my_number`, `My_number`, and `MY_NUMBER` are all different variables.
------------------------------------------------------------------------
When you first start learning Python, dealing with errors can be frustrating. They're often difficult to understand.
But it's important to get used to reading and understanding errors, because you'll get them a lot through your coding career.
Later, we will show you how to use Large Language Models (LLMs) like ChatGPT to debug errors.
At the start though, it's good to try to spot and fix errors yourself.
::: {.callout-tip title='Practice'}
## Practice Q: Debugging Variable Errors
The code below returns an error. Why? (Look carefully)
```{python}
# | eval: False
my_1st_name = "Kene"
my_last_name = "Nwosu"
print(my_Ist_name, my_last_name)
```
Hint: look at the variable names. Are they consistent?
:::
## Naming Variables
> There are only ***two hard things*** in Computer Science: cache invalidation and ***naming things***.
>
> --- Phil Karlton.
Because much of your work in Python involves interacting with variables you have created, picking intelligent names for these variables is important.
Naming variables is difficult because names should be both **short** (so that you can type them quickly) and **informative** (so that you can easily remember what the variable contains), and these two goals are often in conflict.
So names that are too long, like the one below, are bad because they take forever to type.
```{python}
# | eval: False
sample_of_the_ebola_outbreak_dataset_from_sierra_leone_in_2014
```
And a name like `data` is bad because it is not informative; the name does not give a good idea of what the variable contains.
As you write more Python code, you will learn how to write short and informative names.
------------------------------------------------------------------------
For names with multiple words, there are a few conventions for how to separate the words:
```{python}
snake_case = "Snake case uses underscores"
camelCase = "Camel case capitalizes new words (but not the first word)"
PascalCase = "Pascal case capitalizes all words including the first"
```
We recommend snake_case, which uses all lower-case words, and separates words with `_`.
------------------------------------------------------------------------
Note too that there are some limitations on variable names:
- Names must start with a letter or underscore. So `2014_data` is not a valid name (because it starts with a number). Try running the code chunk below to see what error you get.
```{python}
# | eval: False
2014_data = "This is not a valid name"
```
- Names can only contain letters, numbers, and underscores (`_`). So `ebola-data` or `ebola~data` or `ebola data` with a space are not valid names.
```{python}
# | eval: False
ebola-data = "This is not a valid name"
```
```{python}
# | eval: False
ebola~data = "This is not a valid name"
```
::: {.callout-note title='Side note'}
While we recommend snake_case for variable names in Python, you might see other conventions like camelCase or PascalCase, especially when working with code from other languages or certain Python libraries. It's important to be consistent within your own code and follow the conventions of any project or team you're working with.
:::
::: {.callout-tip title='Practice'}
## Practice Q: Valid Variable Naming Conventions
Which of the following variable names are valid in Python? Try to determine this without running the code, then check your answers by attempting to run each line.
Then fix the invalid variable names.
```{python}
# | eval: False
1st_name = "John"
last_name = "Doe"
full-name = "John Doe"
age_in_years = 30
current@job = "Developer"
PhoneNumber = "555-1234"
_secret_code = 42
```
:::
## Wrap-Up
In this lesson, we've covered the fundamental building blocks of Python programming:
1. **Comments**: Using `#` for single-line and triple quotes for multi-line comments.
2. **Basic Arithmetic**: Using Python as a calculator and understanding order of operations.
3. **Math Library**: Performing complex mathematical operations.
4. **Code Spacing**: Improving readability with proper spacing.
5. **Variables**: Creating, manipulating, and reassigning variables of different types.
6. **Getting User Input**: Using the `input()` function to get input from the user.
7. **Variable Naming**: Following rules and best practices for naming variables.
8. **Common Errors**: Identifying and fixing errors related to variables.
These concepts form the foundation of Python programming. As you continue your journey, you'll build upon these basics to create more complex and powerful programs. Remember, practice is key to mastering these concepts!