Python程序设计基础——循环语句

本文介绍了Python中的两种循环结构——while和for循环。while循环适用于条件控制,for循环则用于计数控制。文章详细讲解了while循环的无限循环条件和for循环的range函数,强调了在循环内部使用目标变量的重要性。此外,还提到了累加和的概念以及如何使用标记来结束循环,并讨论了输入验证和嵌套循环的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

复习:

>>> print(format(987654.129,',.2f'))
987,654.13//格式化要四舍五入
>>> print("one",end = " ")// 抑制print函数的自动换行
one 
>>> print("two", end= "l")
twol
>>> print('one','two','three', sep = '~~')//插入间隔符
one~~two~~three

循环结构:
1。条件控制的循环——while循环
使用条件:只知道程序执行的条件,不知道程序执行的次数
基本格式:


>>> while condition:
	statement
	statement
	etc.

特点:

1.只要布尔条件为真,循环就会不断执行语句,造成无限循环。
2.condition后面要加冒号。
3.语句要向内缩进。
4. while循环时先测试的循环。所以必须在循环之前采取某些措施让while最少循环一次。

无限循环
while循环就像一根绳子,必须要首位相接才能形成一个闭环的圆圈,例如:

Max_temp= 102.5

temperature = float(input("Enter the substance's Celsius temperature: "))

while temperature > Max_temp:
    print("the temperature is too high")
    print("turn the thermostat down and wait")
    print("5 minutes.Take the temperature again and enter it")
    temperature = float(input("Enter the substance's Celsius temperature: "))

print("the temperature is acceptable")
print("Check it again in 15 minutes")

前后总共输入了两次temperature,这样子才能保证不陷入死循环,这样子条件才能更新,从而重新判断条件。也就是说,在循环内部需要编写让测试条件为假的代码。(按下Ctrl+C来中断程序)

for循环:计数控制的循环-----只知道程序执行的次数。
基本格式:

for variable in [value1,value2,etc.]:
    statement
    statement
    etc.

for循环的基本原理:

>>> for num in [1,2,3,4,5]://其中num被成为目标函数
	print(num)

1
2
3
4
>>> for name in ['ketty','kevin','rob']:
	print(name)//name是目标变量

	
ketty
kevin
rob

range函数
功能:简化计数控制的for循环的编写过程。
原理:range函数创建一个叫做iterable(迭代器)的对象类型,包含了供循环迭代处理的一组数据(从小到大的有序数列)
例如:

>>> for num in range(5):
	print(num)

	
0
1
2
3
4
>>> for num in [0,1,2,3,4]:
	print(num)

	
0
1
2
3
4

两者等价。
**在循环内部使用目标变量 **
目的:在迭代循环中逐个引用数据列表中的每项数据,由于目标变量在不断改变,所以可以将其应用于循环内部的计算中。
例如:实现公里和英里的换算:

Start_Speed = 60
End_Speed = 131
Increasment = 10
Conversion_Factor = 0.614

print('KPH\tMPH')
print('--------------')


for kph in range(Start_Speed,End_Speed,Increasment):
    mph = kph * Conversion_Factor
    print(kph,'\t',format(mph,'.1f'))


    KPH	MPH
--------------
60 	 36.8
70 	 43.0
80 	 49.1
90 	 55.3
100 	 61.4
110 	 67.5
120 	 73.7
130 	 79.8
      

让用户可以控制循环迭代------可以决定循环迭代几次
作用:增大程序的通用性
解决办法:用多个变量来接收数据序列初始值和终止值。
例如:
输出相应数据的平方:

print("This program displays a list of numbers and their squares.")

start = int(input('Enter the start number: '))
end = int(input('how high should I go? '))

print('Number\tSquares')
print('---------------')

for i in range(start, end+1):
    square = i**2
    print(i,'\t', square)

This program displays a list of numbers and their squares.
Enter the start number: 5
how high should I go? 10
Number	Squares
---------------
5 	 25
6 	 36
7 	 49
8 	 64
9 	 81
10 	 100
    
    

生成一个取值范围从高到低的迭代序列

for x in range(10,0,-1): //方法:改变步长的正负性
    print(x)
10
9
8
7
6
5
4
3
2
1
    

计算累加和
关键词解释:

  1. 累加和(running total):通过循环每一次迭代累加得到的一组数据的总和
  2. 累加器(accumulator):保存累加和的变量
    计算累加和的关键:
    累加器在循环迭代之前要设置为0;
MAX = int(input())

print('This program caculates the sum of ')
print(MAX,'numbers you will enter')

total = 0 

for num in range(MAX):
    number =int(input('Enter a number: '))
    total += number

print('the total is ',total)

程序运行:
5
This program caculates the sum of 
5 numbers you will enter
Enter a number: 1
Enter a number: 2
Enter a number: 3
Enter a number: 4
Enter a number: 5
the total is  15

标记-----往往是一个while循环(条件判断)
概念:标记(Sentinel)是用来标记数列序列结尾的特殊数值。
使用情况:不知道需要输入多少数据的情况下,指定一个特殊的数据为循环结束标志。
注意:一定要选择一个与众不同的数值作为标记
例子:
设计一个方法计算每年的财产税,以财产编号为0 作为标记:

TAX_FACTOR = 0.0065

print('Enter the property lot number')
print('or enter 0 to end.')

lot = int(input('Lot number: '))

while lot != 0:
    value = float(input('Enter the property value: '))
    tax = value * TAX_FACTOR
    print('Property tax: $',format(tax,',.2f'),sep=' ')
    print('Enter the property lot number')
    print('or enter 0 to end.')
    lot = int(input('Lot number: '))

程序运行:
Enter the property lot number
or enter 0 to end.
Lot number: 100
Enter the property value: 200000
Property tax: $ 1,300.00
Enter the property lot number
or enter 0 to end.
Lot number: 200
Enter the property value: 10000
Property tax: $ 65.00
Enter the property lot number
or enter 0 to end.
Lot number: 0

验证输入的循环-------就是一个if判断语句而已
概念:

  1. 输入验证(input validation):在输入将输入到程序中的数据用于计算之前,先对它们加以验证,以确保它们是有效合法的,并且识别出坏数据(bad data)。
  2. 启动读(priming read):在循环开始之前的“获取输入”。另一个获取输入(重新获取输入)在循环内部
    作用:为验证输入的循环提供第一个用于验证的输入值
  3. 错误陷阱(error trap)或者 错误处理(error handle):验证输入的循环名称。

嵌套循环
概念:
1.一个位于其他循环内部的循环被称为嵌套循环
时钟就是一个最典型的嵌套循环

for hours in range(24):
    for minutes in range(60):
        for seconds in range(60):
            print(hours,':',minutes,':',seconds)

用该程序可以用于表示时间:

0 : 5 : 44
0 : 5 : 45
0 : 5 : 46
0 : 5 : 47
0 : 5 : 48
0 : 5 : 49
0 : 5 : 50
0 : 5 : 51
0 : 5 : 52
0 : 5 : 53
0 : 5 : 54
0 : 5 : 55
0 : 5 : 56
0 : 5 : 57
0 : 5 : 58
0 : 5 : 59
0 : 6 : 0
0 : 6 : 1
0 : 6 : 2
0 : 6 : 3
0 : 6 : 4
0 : 6 : 5
0 : 6 : 6
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值