CS50 week 6 - Python 筆記

👀 2 min read 👀

大家好,我是 Cindy,最近跟同事小夥伴相約一起看 CS50 的課程,CS50 (Introduction to Computer Science)是一堂美國哈佛大學知名的通識課程,完全免費,在 edxyoutubeCS50-Study-Group github 都可以非常容易地看到。

這系列的文章會是我的個人筆記,歡迎有興趣的人一定要自己去看看 CS50 的課程歐。

今天這篇是 CS50 week 6 筆記,想先看之前筆記的人可以點選下面連結:

這堂課主要在教 Python 的語法,因為感覺 Python 跟 Ruby 很像,所以這篇文章我想讓這兩個語言的語法進行比較。

hello.py

學任何語言,首先一定要先打招呼XD

1
2
# python
print("hello, world")

這裡語法跟 Ruby 一樣,不過 Ruby 可以省略括號,所以可以寫這樣:

1
2
# ruby
print "hello, world"

但是因為 Ruby 的 print 不會換行,所以感覺還是有點不一樣,這裡如果改用 puts 的話感覺比較像:

1
2
# ruby
puts "hello, world"

Variables

Python 跟 C 不一樣的地方在於,定義一個變數的時候不需要先宣告變數的型別是什麼,這點跟 Ruby 一樣。

F-strings

如果我們想在 String 裡放變數,可以這樣寫:

1
2
3
4
# python
print("hello, " + answer)
# f + "" 告訴 python 要 format string,而不是直接將 {answer} 印出
print(f"hello, {answer}")
1
2
3
4
5
# ruby
puts "hello, " + answer
puts "hello, #{answer}"
# 下面這個方式跟 C 的寫法很像
puts "hello, %s" % answer

Conditions

比較不一樣的是 Python 的 else if 是 elif,而 ruby 的是 elsif

1
2
3
4
5
6
7
# python
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
1
2
3
4
5
6
7
8
# ruby
if x < y
puts "x is less than y"
elsif x > y
puts "x is greater than y"
else
puts "x is equal to y"
end

Loops

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# python
while True:
print("hello, world")

i = 0
while i < 3:
print("hello, world")
i += 1

for i in [0, 1, 2]:
print("cough")

for i in range(3):
print("cough")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# ruby
while true
puts "hello, world"
end

i = 0
while i < 3
puts "hello, world"
i += 1
end

for i in [0, 1, 2]
puts "cough"
end

for i in 0..2
puts "cough"
end

Library

1
2
3
4
5
6
7
8
9
# python
# 引用 Library 的特定方法
from cs50 import get_float
from cs50 import get_int
from cs50 import get_string

import cs50

from cs50 import get_float, get_int, get_string

在 Ruby 可以用 require 來引入 Library

1
2
# ruby
require 'rake'

總結

這篇文章放了好久都沒送出XD
這堂課接下來教授示範了 python 各種實用的用法,例如有做影像處理的 Pillow,Text to Speech 的 pyttsx3face_recognitionspeech_recognition 等等,很多實用的工具可以拿來玩看看囉。