Python中的循環
阿新 • • 發佈:2017-08-02
python 循環 for...in while range
# 循環 # Python的循環有兩種,一種是for...in循環,一種是while循環 # for...in循環 print(‘for...in循環‘) print(‘#1 依次把list或tuple中的每個元素叠代出來‘) names = [‘Micheal‘, ‘Bob‘, ‘Tracy‘] for name in names: print(name) print(‘#2 計算1-10的整數之和‘) s = 0 for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: s += x print(s) print(‘#3 計算1-100的整數之和‘) s = 0 # range()生成序列是左閉右開區間,從0開始 # range(101)生成[0,1,2...100] l = list(range(101)) for x in l: s += x print(s) print(‘------------------------------‘) # while循環 print(‘while循環‘) print(‘計算100以內所有奇數之和‘) s = 0 n = 99 while n > 0: s += n n = n - 2 print(s)
Python中的循環