CS50P: 2. Loops¶
control + C 终止循环
while循环¶
for循环¶
i 初始为 0,依次取 1、2
in 可以让 i 按序取遍 list 中的元素,其中元素可以是 int, dict, str, etc.
range(x) 返回 [0, 1, ..., x-1]
_ 是Pythonic的用法,因为 i 只用来计数,之后不会用到
*¶
continue & break¶
如果想让input符合预期,刻意用 while True
当然,还可以写为:
list¶
a datatype
这样可以不考虑list的长度
student会初始化为 Hermoine ,然后取 Harry ……
len¶
len() 返回列表的元素个数
使用列表中的元素 students[i]
dict (dictionaries)¶
associate one value with another, keys(words) and values(definition)
定义变量¶
what do I want to associate Hermoine with? Gryffindor.
keys on the left, values on the right(美观)
引用¶
想输出 Hermoine 的 house?
方法一
和 list 的数字下标不同,dict 使用 actual words as index,得到 value
方法二
这样会输出所有的 key
for student in students: 会使 student 取 "Hermione" 到 "Draco"
如果 student 的名字是 key,那 students[student] 会去取 student 的 value
多个value¶
a list of dictionaries, a list of 4 students, each of the students is a dictionary
引用多个value¶
student 是 dict 型变量
None¶
python关键字,the absence of a value
