0%

This was CS50 - Lecture 6 (Python)

Built-In Data Types (節錄自 Notes)

  • bool, True or False
  • float, real numbers
  • int, integers
  • str, strings
  • range, sequence of numbers
  • list, sequence of mutable values, or values we can change
    • like arrays in C, can grow and shrink automatically in Python
  • tuple, collection of ordered values like x- and y-coordinates, or longitude and latitude
  • dict, dictionaries, collection of key/value pairs, like a hash table, constant time: O(1)
1
2
3
4
5
6
7
8
9
from cs50 import get_string
people = {
"Tom": "tom@123.com",
"Mary": "mary@123.com"
}
name = get_string("name:") # type "Tom"
if name in people:
print(f"Email: {people[name]}")
#Email:tom@123.com
  • set, collection of unique values, or values without duplicates

Examples

1
2
3
4
from cs50 import get_string

answer = get_string("What's your name?") #type "Tom"
print(f"Hello, {answer}") #Hello, Tom
  • f: format string,可以在字串裡使用變數,變數需要使用 {}
  • 每一行的最後面可以不打 semicolon
  • 變數前不用宣告 data type,type 由數值定義,python 是 loosely type 的語言。

1
2
3
4
5
for i in [1,2,3]:
print(i)
# 1
# 2
# 3

class range(start, stop[, step])
Official Doc - range()

1
2
3
4
5
6
7
for i in range(0, 10, 2):
print(i)
#0
#2
#4
#6
#8

1
2
answer = input("What's your name?") # type "Tom"
print(f"Hi, {answer}")# Hi, Tom
  • input: prompt questions
    • python 內建的語法,與 cs50 library 中的 get_string 相等作用
  • string 使用 single quote '' 或是 double quotes "" 都可以

1
2
3
4
x = int(input("x:")) #1
y = int(input("y:")) #2

print(x / y) #0.5
  • 注意 input("x:") 輸入的值為 string,要加 int 轉型成數字。
  • 在 python 中,每一個東西都是 Object
    • Objects第一等公民

1
2
for i in range(4):
print("*", end="") #****

相當於以下

1
print("*"*4) #****

1
2
3
4
5
6
7
for i in range(3):
for x in range(3):
print("*", end="")
print() # add a new line
# ***
# ***
# ***

1
2
3
scores = [1,2,3]
print(f"Average: {int(sum(scores)/ len(scores))}")
#Average: 2

1
2
3
4
5
scores = []
for i in range(3):
scores.append(i) #scores = [0,1,2]

print(f"Average: {sum(scores)/ len(scores)}") #Average: 1.0

1
2
3
4
5
6
ints = [1,2]
if 1 in ints:
print("Found 1!")
else:
print("Not Found.")
#Found 1!

輕鬆做到 SWAP

1
2
3
4
5
6
x=1
y=2

print(f"x is {x}, y is {y}") #x is 1, y is 2
x, y = y, x
print(f"x is {x}, y is {y}") #x is 2, y is 1