Session 1: Python Basics¶
1. Numbers¶
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
c
15
a * b
50
a / b
0.5
Project¶
Calculate \(1 + 2 +, ..., + k\)
Hint:
\[\frac{k \times (k + 1)}{2}\]
# step 1: determine k
k = 10
# step 2: write the equation
k * (k + 1) / 2
55.0
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!
a = 2
b = 3
s = "Hi"
a + b
5
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
"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[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