Python Programming · Week 3
Hyeongmin Lee · SeoulTech, Dept. of Electronic Engineering
A variable is a box with a name on it. = puts a value into the box.
the box x
x
after x = 5
x
after x = x + 1
a new value replaces the old one
right side first, then store
trace it by hand
line
a
b
a = 3
3
–
b = a
3
3
a = 10
10
3
so b shows 3: b = a stored the value a had at that moment
a variable keeps its value until you store a new one · in math, x = x + 1 is impossible · in Python, it is an instruction
letters, digits, and _
no digit first · no spaces · no hyphens
not a Python word
capital letters matter
a good name says what the value is: days, not d · lowercase words joined by _
with quotes, without quotes
two kinds of quotes
"Kim" · 'Kim'
the same string
"It's"
a quote inside: use the other kind outside
three kinds so far
with quotes: a string, shown as it is · without quotes: a variable, and Python uses its value · "3" and 3 look alike on the screen: type() tells you the kind
>>>"3" + "4"
'34'
+ joins strings
>>>"-" * 10
'----------'
* repeats a string
>>>len("Kim Lee")
7
len() counts characters · the space counts
>>>"3" + 4
TypeError
a string can only be joined to a string
the same +, a different meaning: numbers add, strings join · a loud error is good news: read its last line
the user typed 20
print(age * 3)
202020no error, and a wrong answer: the worst case
print(age + 1)
TypeErrorcan only concatenate str (not "int") to str
age = int(input("Age: "))
from the inside out: input() gives "20", int() turns it into 20, = stores it
changing the kind
digits typed by the user are still a string · "20" is not 20
print(f"{name}, you are about {days} days old.")
print(f"{days * 24} hours")
print(f"{1 / 3:.2f}")
print("Hello, {name}")
one string · no plus signs · no str()
No computer. Say the answer, then I press Enter.
>>>x = 4
>>>x = x * 2
>>>x
>>>a = 3
>>>b = a
>>>b = b + 1
>>>a
>>>"2" + "10"
>>>4 + "3"
>>>"4" * 2
>>>int("4") * 2
>>>n = input("Number: ")
Number: 5
>>>n + n
>>>int(2.99)
>>>f"{2.99:.1f}"
predict first, then check · that is how you read code
Solved live, from the empty file.
typed Kim
typed 7, 4
typed 175
typed 5, 0.2
typed Kim
Next week
Videos and exercise 3: up Tuesday–Wednesday.
Exercise 3: due before next Monday's class.
Slides: hyeongminlee.github.io/slides/python-programming