02. Python Basics, Branching, and Iteration#
Last time#
Course information
Setup the environment
Homework
Today#
Introduction to Python#
An interpreted programming language, not a compiled programming language
Can be typed directly in a Python Shell or in a file
print("Hello, world!")
print("Xi Winnie the Pooh")
print("蔡EE - 天棄之子")
Hello, world!
Xi Winnie the Pooh
蔡EE - 天棄之子
Objects#
It’s something that Python can manipulate. In other words, you can write a program to manipulate it.
There are different types of objects in Python, which defines what kinds of things the programs can do to them.
Common objects in Python:
Name
Type
Example
String
str
9527
Integer
int
87
Floating-point number
float
3.14152
Complex number
complex
1.3+4j
Boolean
bool
True
orFalse
Nonetype
None
None
Tuple
tuple
(1, 2, 3)
List
list
[4, 5, 6]
Dictionary
dict
{"key1": (1, 2, 3)}
type(5487)
int
type("5487")
str
type("5487")
type(5487)
int
print(type(5487))
print(type("5487"))
<class 'int'>
<class 'str'>
Data type conversion#
You can convert the type of object.
print(type(5487))
print(type(str(5487)))
print(type(float(5487)))
<class 'int'>
<class 'str'>
<class 'float'>
Variables and assignment#
=
is an assignment of an object to a variable.Example:
Values are stored in the computer memory.
An assignment binds name to value.
Binding values can be invoked by typing variables.
Multiple assignments is also allowed in Python.
pi = 3
radius = 10
circum = 2*pi*radius
print("pi =", pi)
print("radius =", radius)
print("circum =", circum)
pi = 3
radius = 10
circum = 60
pi, radius = 3, 10
circum = 2*pi*radius
print("pi =", pi)
print("radius =", radius)
print("circum =", circum)
pi = 3
radius = 10
circum = 60
radius = 94
print("radius =", radius)
radius = radius + 1
print("radius =", radius)
radius = 94
radius = 95
String#
Letters, special characters, spaces, … can be a
string object
.Using quotes to specify the object type
Strings can be concatenated or multiplied by an integer.
hi = "你好"
name = "Winnie the Pooh"
# Concatenated
greeting1 = hi + ", " + name
print(greeting1)
greeting2 = "Xi " + name
print(greeting2)
# Multiplied by an integer
greeting3 = "You f" + "o"*10 + "l"
print(greeting3)
你好, Winnie the Pooh
Xi Winnie the Pooh
You fooooooooool
More about print
#
Different types of objects can be concatenated by
print
.Use
sep
andend
to change its functionality.
Try this#
# 1
print("hello," + 3)
# 2
print("hello,", 3)
# 3
print("hello,", 3, sep="", end="!")
# 4
print("塔綠班"*1.3)
Function input
#
A function to interact with users
Be careful with the data type
xxx = input("Please tell me something: ")
print("type(xxx):", type(xxx))
Indexing#
The indexing in Python is zero-based
Slicing#
Using slicing to extract the objects
Try this
xxx = "0123456789" # 1 print(xxx[0]) # 2 print(xxx[-1]) # 3 print(xxx[2:5]) # 4 print(xxx[:7]) # 5 print(xxx[7:])
String formatting#
# Example of %-formatting
text = 'world'
# %s: string
print('hello %s!' % text)
# %x: hexadecimal
print('%x' % 10)
# multiple %-formatting
print('Xi %s %s' % ('Winnie', 'the Pooh'))
hello world!
a
Xi Winnie the Pooh
str-format
# Example of str-formatting
text = 'world'
# {}: string
print('Hello {}!'.format(text))
# {:x}: hexadecimal
print('{:x}'.format(10))
# multiple str-formating
print('Xi {} {}'.format('Winnie', 'the Pooh'))
Hello world!
a
Xi Winnie the Pooh
f-string
# Example of f-string
text = 'world'
print(f'Hello {text}!')
first = 'Winnie'
title = 'the Pooh'
print(f'Xi {first} {title}')
Hello world!
Xi Winnie the Pooh
# String formatting
a = 50
b = 4
# %-formatting
print("%d/%d = %f" % (a, b, a/b))
# str-formatting
print("{:d}/{:d} = {:f}".format(a, b, a/b))
# f-string
print(f'{a}/{b} = {a/b}')
50/4 = 12.500000
50/4 = 12.500000
50/4 = 12.5
Exercise 2.1#
Please write a program that aims to print an arbitrary number into the following format:
Binary (
b
)Octal (
o
)Decimal (
d
)Hexadecimal (
x
)
For example, 9487:
Binary: 10010100001111
Octal: 22417
Decimal: 9487
Hexadecimal: 250F
Logistic operators#
Logical operators
and
,or
,not
A = 0 #False B = 1 #True print(A and B) print(A or B) print(not A)
Logical operators with none boolean objects
Object
Result
0
False
()
,[]
,{}
False
None
False
False
False
others
True
print(not 0)
print(not ())
print(not None)
print(not 8)
print(not "string")
True
True
True
False
False
Multiple objects#
From left to right
Priority:
not
and
or
and
:return the far right object if all objects are
True
, return the firstFalse
object otherwise.
or
:return the far right object if all objects are
False
, return the firstTrue
object otherwise.
print(3 and 4 and 5) # return 5
print(3 and 0 and 5) # return 0
print(3 or 4 or 5) # return 3
print(() or None or {}) # return {}
print(2 and 3 or 4) # return 3
print(2 and 0 or 4) # return 4
5
0
3
{}
3
4
Bitwise operators
and:
&
or:
|
xor:
^
Input | Result | ||
A | 1 | 0 | 1 |
B | 0 | 1 | 1 |
A & B | 0 | 0 | 1 |
A | B | 1 | 1 | 1 |
A ^ B | 1 | 1 | 0 |
A = 5
B = 3
# format(Number, '{number to filled}{width}{format}')
print(' A binary:', format(A, '03b'), A)
# f-string
print(' B binary:', f'{B:03b}', B)
print('A&B binary:', f'{A & B:03b}', A & B)
print('A|B binary:', f'{A | B:03b}', A | B)
print('A^B binary:', f'{A ^ B:03b}', A ^ B)
A binary: 101 5
B binary: 011 3
A&B binary: 001 1
A|B binary: 111 7
A^B binary: 110 6
A = 5
B = 3
# str-format
print(' A binary: {:03b} {}'.format(A, A))
print(' B binary: {:03b} {}'.format(B, B))
print('A&B binary: {:03b} {}'.format(A & B, A & B))
print('A|B binary: {:03b} {}'.format(A | B, A | B))
print('A^B binary: {:03b} {}'.format(A ^ B, A ^ B))
A binary: 101 5
B binary: 011 3
A&B binary: 001 1
A|B binary: 111 7
A^B binary: 110 6
Exercise 2.2#
Please write a program that can print a variable
a
as the following string:94.8700
0.949%
00095
Here is your sample code:
a = 94.87
print("自己想")
print("自己想")
print("自己想")
Identity operators
is
Operators
Meaning
Example
is
Is A same object as B?
True is True
is not
Is A not same objest as B?
True is not False
Do not confuse with comparison operator
==
.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
print(a is b)
print(id(a), id(b))
True
False
2461526278464 2461526224192
Branching & conditional#
Using branching to control the flow of algorithm
your_id = "113514087"
if your_id[:3] == "112":
# branch 1
print("Welcome, freshman!")
elif your_id[0:3] == "108":
# branch 2
print("Why are you still here?")
else:
# branch 3
print("You have to pass this if you want to graduate.")
You have to pass this if you want to graduate.
Iterations and loops#
A method for executing repeatable instructions
while
loop#
Keep iterating the loop while the condition is
True
# Syntax while <condition>: <expression> <expression> <expression> ...
# Example of while loop
# Example 1
n = 0
ans = 0
while n < 11:
print("(n, ans) = ({}, {})".format(n, ans))
ans += n
n += 1
(n, ans) = (0, 0)
(n, ans) = (1, 0)
(n, ans) = (2, 1)
(n, ans) = (3, 3)
(n, ans) = (4, 6)
(n, ans) = (5, 10)
(n, ans) = (6, 15)
(n, ans) = (7, 21)
(n, ans) = (8, 28)
(n, ans) = (9, 36)
(n, ans) = (10, 45)
# Example 2
n = 0
ans = 0
while n < 11:
ans += n
n += 1
print("(n, ans) = ({}, {})".format(n, ans))
(n, ans) = (1, 0)
(n, ans) = (2, 1)
(n, ans) = (3, 3)
(n, ans) = (4, 6)
(n, ans) = (5, 10)
(n, ans) = (6, 15)
(n, ans) = (7, 21)
(n, ans) = (8, 28)
(n, ans) = (9, 36)
(n, ans) = (10, 45)
(n, ans) = (11, 55)
Exercise 2.3: sum of harmonic series#
Please write a program with
while
that aims to return you the sum of a harmonic series
Note: \(n\) is a positive integer
Test your program with different \(n\), for example, \(n = 1, 2, 3, ...\)
for
loop#
Keep iterating the loop for a specific number of times
# Syntax for idx in <iterable object>: <expression> <expression> <expression> ... # Simple version for idx in <number of times>: <expression> <expression> <expression> ...
We will explain what is
iterable object
in the future
# Example of for loop
# Example 1
ans = 0
for n in range(11):
print("(n, ans) = ({}, {})".format(n, ans))
ans += n
(n, ans) = (0, 0)
(n, ans) = (1, 0)
(n, ans) = (2, 1)
(n, ans) = (3, 3)
(n, ans) = (4, 6)
(n, ans) = (5, 10)
(n, ans) = (6, 15)
(n, ans) = (7, 21)
(n, ans) = (8, 28)
(n, ans) = (9, 36)
(n, ans) = (10, 45)
# Example 2
ans = 0
for n in range(11):
ans += n
print("(n, ans) = ({}, {})".format(n, ans))
(n, ans) = (0, 0)
(n, ans) = (1, 1)
(n, ans) = (2, 3)
(n, ans) = (3, 6)
(n, ans) = (4, 10)
(n, ans) = (5, 15)
(n, ans) = (6, 21)
(n, ans) = (7, 28)
(n, ans) = (8, 36)
(n, ans) = (9, 45)
(n, ans) = (10, 55)
Exercise 2.4: sum of harmonic series#
Please write a program with
for
that aims to return you the sum of a harmonic series
Note: \(n\) is a positive integer
Test your program with different \(n\), for example, \(n = 1, 2, 3, ...\)
Function enumerate
#
# Example of for loop
text = "3.14159265359"
# 1
for i in range(len(text)):
print("{}: {}".format(i, text[i]))
# 2
for idx, string in enumerate(text):
print(str(idx) + ": " + string)
0: 3
1: .
2: 1
3: 4
4: 1
5: 5
6: 9
7: 2
8: 6
9: 5
10: 3
11: 5
12: 9
0: 3
1: .
2: 1
3: 4
4: 1
5: 5
6: 9
7: 2
8: 6
9: 5
10: 3
11: 5
12: 9
Exercise 2.5: the factorial#
Please write a program that aims to return you a factorial of a non-negative integer \(n\).
Note: \(n\) is a non-negative integer
Test your program with different \(n\), for example, \(n = 1, 2, 3, ...\)