library(reticulate)
My older son, Keen, is six years old now and he’s getting interested in coding. So I’m now working on a series of Jupyter notebooks that introduce him to Python.
Although I’m more of an R user, I feel Python is a better language to start for kids.
(Thanks to the reticulate
package, I am able to write and run Python code within RStudio. Mad respect to whoever developed this package!)
Session 1: Python Basics
1. Numbers
1.1. Using Python as a calculator
1 + 5
6
538687445 + 3897886465
4436573910
6 - 3
3
30 - 8
22
1.2. Variables
The equals sign (“=”) means assignment, e.g., \(x = 1\) gives the value \(1\) to variable \(x\).
1 + 5
6
= 1
x = 5
y
+ y x
6
= 3
x
+ y x
8
= x - y
z z
-2
Your turn: - Create two variables: a and b. Assign 5 to a, and 10 to b - Calculate the sum of a and b, save it to a third variable called c - Calculate \(a \times b\) (hint: In Python, the multiplication sign is “*” [asterisk]) - Calculate \(a \div b\) (The division sign is “/” [forward slash])
= 5
a = 10 b
= a + b c
* b a
50
/ b a
0.5
Mini Project:
Calculate \(1 + 2 + ... + 10\).
Hint:
\[1 + 2 + ... + k = \frac{k \times (k + 1)}{2}\]
(Why?)
# step 1: determine k
= 10
k
# step 2: write the equation
* (k + 1) / 2 k
[1] 55
# defining a function to take any k value
def calc_sum(k):
= k * (k + 1) / 2
s return s
= 1_000_000) calc_sum(k
500000500000.0
1.3 Strings
= "hello"
s1 = "Keen"
s2
print(s1)
hello
print(s2)
Keen
print(s1 + s2)
helloKeen
print(s1 + ", " + s2)
hello, Keen
print(s1 + ", " + s2 + "!")
hello, Keen!
print("H" + s1[1:5] + ", " + s2 + "!")
Hello, Keen!
= "4"
a1 = "14"
b5
+ b5 a1
'414'
Project:
# tell me about you
= "huijing"
name = 19
age
print("Hello, " + name + "! You are " + str(age) + " years old.")
Hello, huijing! You are 19 years old.
name
'huijing'
"H" + name[1:]
'Huijing'
1.4 Lists
= ["apple", "banana", "peach"]
fruits = [2, 4, 1]
keen = [0, 1, 3] mom
# how many bananas did Keen eat this week?
print("Keen ate " + str(keen[1]) + " bananas this week.")
Keen ate 4 bananas this week.
# How many peaches did mon eat this week?
print("Mom ate " + str(mom[2]) + " peaches this week.")
Mom ate 3 peaches this week.
# How many bananas were eaten in total?
print("In total, " + str(keen[1] + mom[1]) + " were eaten this week")
In total, 5 were eaten this week