第八課 while循環 # coding:utf-8 # while循環 # 當布爾表達式爲True,就是執行一遍循環體中的代碼。 ''' 如今要從1 輸出到 10 print(1) print(2) print(3) print(4) print(5) print(6) print(7) print(8) print(9) print(10) ''' ''' while condition_expression: statement1 statement2 ... ... statementn otherstatement ''' # 從1 輸出到 10 x = 1 while x <= 10: print(x) x += 1 # 這一行的代碼至關於 x = x +1 輸出的結果爲:1..10 x = 1 while x <= 10: x += 1 # 這一行的代碼至關於 x = x +1 print(x) #輸出的結果爲 1..11 這裏注意一下 shell 中的while循環 [hadoop@dev-hadoop-test03 majihui_test]$ cat b.sh #!/bin/bash x=1 while (( x <= 10 )) do echo "$x" ((x = x+1)) done [hadoop@dev-hadoop-test03 majihui_test]$ sh b.sh 1 2 3 4 5 6 7 8 9 10 [root@localhost day9]# cat while02.sh #!/bin/bash i=1 sum=0 while (( i <= 100 )) do ((sum=sum+i)) ((i=i+1)) done printf "totalsum is :$sum\n" [root@localhost day9]# sh while02.sh totalsum is :5050 —————————————————————————————————————————————————————————— 第九課 for循環 for循環爲了簡化代碼,通常來講,相同的實現 while可能須要更多的代碼行來實現 # coding:utf-8 numbers = [1,2,3,4,5,6,7,8,9,10] # 定義一個序列的列表 # 使用while循環 經過索引 i = 0 while i < 10: print(numbers[i], end=" ") #已空格爲分隔符 輸出結果爲 1 2 3 4 5 6 7 8 9 10 i += 1 print() # 這個的意思表示換行 # 使用for循環 for num in numbers: print(num, end = " ") # 結果爲 1 2 3 4 5 6 7 8 9 10 print() # 這個的意思表示換行 # 從1到1000循環 用for numberss = range(1,100) # 先產生一個範圍 for numm in numberss: print(numm, end=",") print() names = ["Bill", "Mike", "John", "Mary"] for i in range(0, len(names)): print(names[i], end=" ") #輸出結果爲 Bill Mike John Mary print() for i in range(len(names)): print(names[i], end=" ") #輸出結果爲 Bill Mike John Mary # 這兩種的寫法都是同樣的 shell中的for循環: [root@localhost day10]# cat for01.sh #!/bin/bash for i in 5 4 3 2 1 do echo $i done [root@localhost day10]# cat for02.sh #!/bin/bash for i in {5..1} do echo $i done [root@localhost day10]# sh for01.sh 5 4 3 2 1 下面這個是我常常去清空批量的日誌執行的語句 for n in `ls cloudera-scm-server.log*`;do echo "" > $n;done