21 22 py中的while for循环

第八课 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 

猜你喜欢

转载自blog.51cto.com/12445535/2464061