注:这是自己跟着慕课嵩天老师的课程写的笔记。笔记若有错误,希望大家批评指正。
一、 交互式循环(无限循环while的一种)
允许用户用交互的方式重复程序的特定部分,该方法交互十分烦人
def Jiaohu():
sum = 0.0
count = 0
moredata = "yes"
while moredata[0] == "y":
x = eval(input("Enter a number >>"))
sum = sum + x
count = count + 1
moredata = input("Do you have more numbers (yes or no)?")
print("\nThe average of the numbers is ",sum/count)
二、哨兵循环:
直到遇到用户输入某个特定值的时候,循环语句才终止执行的循环结构设计方法
def Shaobing():
sum = 0.0
count = 0
teststr = input("Enter a number(No digital input, please press space) >>")
while teststr != "":
#这里利用空字符串""(引号之间没有空格)作为哨兵,用户输入为enter回车时,返回空字符串
x = eval(teststr)
sum = sum + x
count = count + 1
teststr = input("Enter a number(No digital input, please press space) >>")
print("\nThe average of the numbers is ",sum/count)
三、文件循环for:
求平均数不再用手动输入,而使用文件输入大量数字,这里假定文件里面一行只有一个数字
def WenjianFor():
fileName = input("What file are the numbers in?")
#文件位置:E:\本科\Python自学\零基础学Python语言\第三讲\Test有空行.txt
#文件位置:E:\本科\Python自学\零基础学Python语言\第三讲\Test无空行.txt
infile = open(fileName, 'r')
sum = 0
count = 0
for line in infile:
#line会按照文件的行来遍历,一次循环操作遍历一行
if line != "\n":
sum = sum + eval(line)
count = count + 1
else:
continue
print("\nThe average of the numbers is ",sum/count)
四、文件循环while:
将end-of-file哨兵循环应用到平均数问题中,上面的程序中,循环变量line遍历文件的每一行,将每行都转成数字然后加到sum中,这里想用while完成文件每行的遍历,Python提供函数readline()来读取,在文件尾部,readline()返回的一个空字符串可以作为哨兵值。
注 不要理解文件没结束前的空行也可以返回""空字符串,空行返回的是\n
def WenjianWhile():
fileName = input("What file are the numbers in?")
#文件位置:E:\本科\Python自学\零基础学Python语言\第三讲\Test有空行.txt
#文件位置:E:\本科\Python自学\零基础学Python语言\第三讲\Test无空行.txt
infile = open(fileName, 'r')
sum = 0
count = 0
line = infile.readline()
while line != "":
#line会按照文件的行来遍历,一次循环操作遍历一行
if line != "\n":
sum = sum + eval(line)
count = count + 1
line = infile.readline()
else:
line = infile.readline()
continue
print("\nThe average of the numbers is ",sum/count)
五、嵌套循环:
假设文件中每行不只是存一个数字,而是用逗号分割的多个数字,采用循环里面套循环方法
def Qiantao():
fileName = input("What file are the numbers in?")
#文件位置:E:\本科\Python自学\零基础学Python语言\第三讲\Test一行多数有空行.txt
infile = open(fileName, 'r')
sum = 0
count = 0
line = infile.readline()
while line != "":
#line会按照文件的行来遍历,一次循环操作遍历一行
if line != "\n":
for splitstr in line.split(","):
sum = sum + eval(splitstr)
count = count + 1
line = infile.readline()
else:
line = infile.readline()
continue
print("\nThe average of the numbers is ",sum/count)
主函数
def main():
n = input("Please input a alphabet:")
if n == "A":
print("------测试交互式循环-----")
Jiaohu()
elif n == "B":
print("------测试哨兵循环-----")
Shaobing()
elif n == "C":
print("------测试文件循环for-----")
WenjianFor()
elif n == "D":
print("------测试文件循环while-----")
WenjianWhile()
else:
print("------测试嵌套循环-----")
Qiantao()
main()