在Python中使用循环显示计算
我正在尝试编写代码,使用户输入车辆的速度和行驶时间。使用此信息计算每小时的总距离。如果用户输入30 MPH的速度和4小时的时间,则所需输出的样本将显示4小时和30小时的距离1、60小时2、90小时3等 但是,下面的代码生成的输出仅显示最终的数字。意思是(使用上面的输入)它只显示四次小时4和120英里的距离 代码如下:在Python中使用循环显示计算,python,loops,Python,Loops,我正在尝试编写代码,使用户输入车辆的速度和行驶时间。使用此信息计算每小时的总距离。如果用户输入30 MPH的速度和4小时的时间,则所需输出的样本将显示4小时和30小时的距离1、60小时2、90小时3等 但是,下面的代码生成的输出仅显示最终的数字。意思是(使用上面的输入)它只显示四次小时4和120英里的距离 代码如下: #This program uses a loop to display #distance traveled over time. print('This program ca
#This program uses a loop to display
#distance traveled over time.
print('This program calculates distance traveled')
print('for a vehicle traveling at a constant speed.')
#Gets speed of the vehicle
speed = int(input('Enter the vehicle speed in MPH: '))
#Gets the hours
hours = int(input('Enter time of trip in hours: '))
#creates headings for table displaying output
print()
print('Hour\tDistance Traveled')
print('-------------------------')
for number in range(1, hours + 1):
distance = hours*speed
print(hours, '\t', distance)
这是因为您在计算中使用的是终端值(
hours
),而不是循环变量(number
)
如果您将循环中的hours
更改为number
,它将按预期工作
for number in range(1, hours + 1):
distance = number*speed
print(number, '\t', distance)
此外,命名变量编号是一种非常糟糕的做法。如果不通读整个代码,就很难理解它是什么类型的数字,因此我还建议将其重命名为更具信息性的名称,例如中间小时
,或仅小时
:
for intermediate_hour in range(1, hours + 1):
distance = intermediate_hour * speed
print(intermediate_hour, '\t', distance)
将循环内的hours
更改为number
。