脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python通用循环的构造方法实例分析

Python通用循环的构造方法实例分析

2021-05-04 14:40oOo右右 Python

这篇文章主要介绍了Python通用循环的构造方法,结合实例形式分析了Python常见的交互循环、哨兵循环、文件循环、死循环等实现与处理技巧,需要的朋友可以参考下

本文实例讲述了Python通用循环构造方法。分享给大家供大家参考,具体如下:

1.交互循环

是无限循环的一种,允许用户通过交互的方式程序的特定部分

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
def main():
  sum =0.0
  count =0
  moredata ='yes'  #字符串
  while moredata[0] =='y': #获取字符串第一个字符,true执行下面的
    x =eval(input('enter a number>>'))
    sum =sum+x
    count = count +1
    moredata =input("你有更多的number(yes or no)")
  print("pingjunshushi:\n",sum/count)
main()
enter a number >>3
你有更多的number(yesor no)y
enter a number >>4
你有更多的number(yesor no)n
pingjunshushi:
 3.5

2.哨兵循环:

执行循环要遇到设定的特殊数据,循环语句才会终止。

哨兵循环求平均数的方法:

1)设定一个哨兵值作为循环终止的标识;

2)任何值都可以看做哨兵,但是要与实际数有所区别;

python中空字符串以双引号""表示,注意引号中间没有空格!!!

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def main():
  sum =0
  count =0
  xStr = input("enter a number")
  while xStr != "":  #空字符串
    x = eval(xStr)  #转换字符串为数字的过成
    sum = sum + x
    count =count +1
    xStr = input("enter a number :")
  print("average is",sum/count)
main()
enter a number6
enter a number :6
enter a number :6
enter a number :  这里确认输入不是哨兵空字符才将输入字符串转换为数字
average is 6.0

eval() 函数参数是字符串可以当成有效python表达式来求值,并返回计算结果

3.文件循环

?
1
2
3
4
5
6
7
8
9
10
def main():
  fileName = input("file denumber:") #这个相当于一个文件
  infile = open(fileName,'r') #open(文件名,方式'r'/'w')函数用来打开这个文件的一行保存在infile列表(相当一个数组)中
  sum =0
  count = 0
  for line ininfile:   #循环变量line遍历文件的每一行(文件每一行已经保存在infile列表中),将每一行执行下面的代码
    sum = sum+eval(line)
    count = count +1
  print("aveage is:",sum/count)
main()

循环遍历文件,通常的方法是用哨兵方法一次读取文件的一行

这个可以用来读取excel中的测试用例;

python中采用readline()方法的end-of-file循环模式:

readline()将文件的一行读取到字符串中,在文件尾部readline()返回一个空字符串可以作为哨兵值;

?
1
2
3
4
line=infile.readline()
while line != "":
#处理每一行
line =infile.readline()

这段代码会让人误以为遇到一个空行时就会退出,其实不然文本文件的空行包括一个换行符\n  这样readline()函数返回值是换行符,而不是哨兵值空字符串,循环继续

open()  打开文件读取保存到list中

readline()读取文件,每次读取一行

4.死循环

python中可以用python完成特定的功能:

?
1
2
3
4
5
6
while True:
  try:
    x = int(input("输入一个数字:"))
    break
  except ValueError:
    print("重新输入:")

copy()函数:

返回字典的浅拷贝;

?
1
2
3
dict1={"name":"liyue"}
dict2=dict1.copy()
print("dict2 is:",str(dict2))

运行结果:

dict2 is: {'name': 'liyue'}

python读取excel:

注意读取时候加上表头,没表头不行,所以测试用例要有表头。

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/JOJOY_tester/article/details/53231603

延伸 · 阅读

精彩推荐