# Learning Python with Keen (Session 1)

Life
Python
Author

Chen Tang

Published

July 1, 2022

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!)

library(reticulate)

## 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
x = 1
y = 5

x + y
6
x = 3

x + y
8
z = x - y
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])

a = 5
b = 10
c = a + b
a * b
50
a / b
0.5

Mini Project:

Calculate $$1 + 2 + ... + 10$$.

Hint:

$1 + 2 + ... + k = \frac{k \times (k + 1)}{2}$

(Why?)

# step 1: determine k
k = 10

# step 2: write the equation
k * (k + 1) / 2
 55
# defining a function to take any k value
def calc_sum(k):
s = k * (k + 1) / 2
return s

calc_sum(k = 1_000_000)
500000500000.0

#### 1.3 Strings

s1 = "hello"
s2 = "Keen"

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!
a1 = "4"
b5 = "14"

a1 + b5
'414'

Project:

# tell me about you
name = "huijing"
age = 19

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

fruits = ["apple", "banana", "peach"]
keen = [2, 4, 1]
mom = [0, 1, 3]
# how many bananas did Keen eat this week?
print("Keen ate " + str(keen) + " bananas this week.")
Keen ate 4 bananas this week.
# How many peaches did mon eat this week?
print("Mom ate " + str(mom) + " peaches this week.")
Mom ate 3 peaches this week.
# How many bananas were eaten in total?
print("In total, " + str(keen + mom) + " were eaten this week")
In total, 5 were eaten this week