Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/asp.net-mvc-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用循环显示计算_Python_Loops - Fatal编程技术网

在Python中使用循环显示计算

在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

我正在尝试编写代码,使用户输入车辆的速度和行驶时间。使用此信息计算每小时的总距离。如果用户输入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 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