个人认为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
输出结果如下:
前面我已经讲过,print后面加逗号(,)表示输出字符串不会换行。
while关键字行行尾一定要加:
while循环用在计算中:
import random
number1 = random.randint(0,10)
number2 = random.randint(0,10)
if number1
再比如猜数字:
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 !")
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")
for循环
输出顺序元素
for v in range(4,8):
print(v)
间隔输出
for v in range(4,20,2):
print(v)
逆序输出
for v in range(20,4,-2):
print(v)
累和:
sum = 0
for i in range(10):
sum = sum+i
print(sum)