Python学习笔记(五)—LOOP 循环

个人认为Python基础学习直到LOOP才算真正开始。

循环有While, do-while, 和for()

比如while

我们要输出100条“you are my sunshine ”可以表达如下:

count = 0
while count< 10:
    print("you are my sunshine "),
    count = count + 1

输出结果如下:

Python学习笔记(五)—LOOP 循环_第1张图片


前面我已经讲过,print后面加逗号(,)表示输出字符串不会换行。

while关键字行行尾一定要加:

while循环用在计算中:

import random
number1 = random.randint(0,10)
number2 = random.randint(0,10)
if number1

Python学习笔记(五)—LOOP 循环_第2张图片

再比如猜数字:

import random
number = random.randint(0,10)
guess = -1
while guess != str(number):
    guess = eval(raw_input("please enter the right number :"))
    print(guess)
    if str(guess) == str(number):
        print("yes,you got the right number",number)
    elif str(guess) > str(number):
        print("please enter a lower number !")
    else:
        print("please enter a larger number !")   
或者不需要str

import random
number = random.randint(0,10)
guess = -1
while guess != number:
    guess = eval(raw_input("please enter the right number :"))
    print(guess)
    if guess == number:
        print("yes,you got the right number",number)
    elif guess > number:
        print("please enter a lower number !")
    else:
        print("please enter a larger number !")   


Python学习笔记(五)—LOOP 循环_第3张图片

LOOP循环中我们最关心的就是耗时时长了,计算耗时的函数是time.time(),需要加import time

比如:

start = time.time()
...
end = time.time()
time_elapsed = int(end - start)
应用到猜数字程序中:

import random
import time
number = random.randint(0,10)
guess = -1
start = time.time()
while guess != number:
    guess = eval(raw_input("please enter the right number :"))
    print(guess)
    if guess == number:
        print("yes,you got the right number",number)
    elif guess > number:
        print("please enter a lower number !")
    else:
        print("please enter a larger number !")   
end = time.time()
time_elapsed = str(end - start)
print("Time elapsed "+time_elapsed+" seconds")
Python学习笔记(五)—LOOP 循环_第4张图片


for循环

输出顺序元素

for v in range(4,8):
    print(v)
Python学习笔记(五)—LOOP 循环_第5张图片
包含4不包含8。


间隔输出

for v in range(4,20,2):
    print(v)
Python学习笔记(五)—LOOP 循环_第6张图片


逆序输出

for v in range(20,4,-2):
    print(v)
Python学习笔记(五)—LOOP 循环_第7张图片


累和:

sum = 0
for i in range(10):
    sum = sum+i
    print(sum)
Python学习笔记(五)—LOOP 循环_第8张图片






你可能感兴趣的:(Python)