《Python for Beginners》为LearnStreet上的Python入门课程。本节主要学习内容为循环语句。
一、基本语法
1. while循环
下面两种写法是等价的:
while flag:
while flag == True:
2. for循环
for x in range(0,3):
range(0,3) 执行的有效值范围为[0,1,2], 并且同range(3)是等价的。
二、编程练习
1. Incrementing and Decrementing
1 def run(first, second): 2 #your code here 3 first +=1 4 second -=1 5 return (first, second) 6 7 #This is just for you to see what happens when the function is called 8 print run(1, 20)
输出结果:
(2, 19)
#注意本函数有两个返回值。
2. while循环练习
函数功能:输出1-10
1 def run(): 2 count = 1 3 #your code here 4 while count <=10: 5 print count 6 count +=1 7 return count 8 9 #This is just for you to see what happens when the function is called 10 print run()
输出结果:
1
2
3
4
5
6
7
8
9
10
11
思考:为什么会输出11?因为函数以print run()方式进行调用,将输出函数的返回值(值为11),若无返回值则输出None。
3. for循环练习1
函数功能:计算1-10共10个数的和。
1 def run(): 2 sum = 0 3 for i in range(11): 4 #your code here 5 sum +=i 6 return sum 7 8 #This is just for you to see what happens when the function is called 9 print run()
输出结果:
55
4. for循环练习2
1 def run(): 2 #your loop here 3 for i in range(10): 4 print "#" * i 5 6 #This is just for you to see what happens when the function is called 7 run()
输出结果:
#
##
###
####
#####
######
#######
########
#########
注意:输出结果的第一行为空行
5. for循环练习3
实现功能:输出所有小于20的奇数,并返回这些数的和。
代码:
1 def run(): 2 #your code here 3 sum = 0 4 for i in range(10): 5 print i*2+1 6 sum += i*2+1 7 return sum 8 9 #This is just for you to see what happens when the function is called 10 print run()
输出结果:
1
3
5
7
9
11
13
15
17
19
100
6. Iterables
1 def run(): 2 """ 3 print each letter in the string using the for loop syntax and then return the last character sequence 4 """ 5 str = "LearnStreet!" 6 for i in range(len(str)): 7 print str[i] 8 return str[i] 9 10 #This is just for you to see what happens when the function is called 11 run()
输出结果:
L
e
a
r
n
S
t
r
e
e
t
!
注意:如果函数以print run()方式调用,则会输出返回值(值为'!'),若没有return str[i]语句,则返回值输出为None。
7. 复习(条件语句和循环语句)
1 def checkLen(): 2 str = "Ninja Coder!" 3 flag = True 4 while flag: 5 count = 0 6 for i in range(len(str)): 7 count +=1 8 if count == len(str): 9 flag = False 10 print "done" 11 else: 12 print "not yet done" 13 14 #This is just for you to see what happens when the function is called 15 checkLen()
输出结果:
not yet done
not yet done
not yet done
not yet done
not yet done
not yet done
not yet done
not yet done
not yet done
not yet done
not yet done
done
总结:
1. 一个函数可以有多个返回值。
2. Python允许一个字符串与整数n相乘,结果等价于n个字符串串联一起。
3. 注意函数调用时run()与print run()的区别。
(本文完)