python自動化測試--流程控制和迭代器

# 先隨便定義一個變量
some_var = 5

# 這是個if語句。注意縮進(jìn)在Python里是有意義的
# 印出"some_var比10小"
if some_var > 10:
    print("some_var比10大")
elif some_var < 10:    # elif句是可選的
    print("some_var比10小")
else:                  # else也是可選的
    print("some_var就是10")


"""
用for循環(huán)語句遍歷列表
打印:
    dog is a mammal
    cat is a mammal
    mouse is a mammal
"""
for animal in ["dog", "cat", "mouse"]:
    print("{} is a mammal".format(animal))

# => dog is a mammal
# => cat is a mammal
# => mouse is a mammal

"""
"range(number)"返回數(shù)字列表從0到給的數(shù)字
打印:
    0
    1
    2
    3
"""
for i in range(4):
    print(i)
print('-------------')

"""
while循環(huán)直到條件不滿足
打印:
    0
    1
    2
    3
"""
x = 0
while x < 4:
    print(x)
    x += 1  # x = x + 1 的簡寫
print('---------------')

# 用try/except塊處理異常狀況
try:
    # 用raise拋出異常
    raise IndexError("This is an index error")
except IndexError as e:
    pass    # pass是無操作,但是應(yīng)該在這里處理錯誤
except (TypeError, NameError):
    pass    # 可以同時處理不同類的錯誤
else:   # else語句是可選的,必須在所有的except之后
    print("All good!")   # 只有當(dāng)try運行完沒有錯誤的時候這句才會運行


# Python提供一個叫做可迭代(iterable)的基本抽象。一個可迭代對象是可以被當(dāng)作序列
# 的對象。比如說上面range返回的對象就是可迭代的。

filled_dict = {"one": 1, "two": 2, "three": 3}
our_iterable = filled_dict.keys()
print(our_iterable)
# => dict_keys(['one', 'two', 'three']),是一個實現(xiàn)可迭代接口的對象

# 可迭代對象可以遍歷
for i in our_iterable:
    print(i)    # 打印 one, two, three

# 但是不可以隨機訪問
# our_iterable[1] # 拋出TypeError
#如果需要取出某一個值可以將集合轉(zhuǎn)換成列表
print(list(our_iterable)[1])
# => two

# 可迭代對象知道怎么生成迭代器
our_iterator = iter(our_iterable)

# 迭代器是一個可以記住遍歷的位置的對象
# 用__next__可以取得下一個元素
our_iterator.__next__()  # => "one"

# 再一次調(diào)取__next__時會記得位置
our_iterator.__next__()  # => "two"
our_iterator.__next__()  # => "three"

# 當(dāng)?shù)魉性囟既〕龊螅瑫伋鯯topIteration
# our_iterator.__next__() # 拋出StopIteration

# 可以用list一次取出迭代器所有的元素
list(filled_dict.keys())  # => Returns ["one", "two", "three"]
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容