Python 使用循环从控制台输入数据并找出最大数及其位置
代码如下:
num_list = [] # 定义一个空列表
# 循环8次,从控制台输入8个数并添加到列表中
for i in range(8):
num = int(input('请输入第%d个数:' % (i+1)))
num_list.append(num)
max_num = num_list[0] # 定义最大数为列表中的第一个数
max_index = 0 # 定义最大数的下标为0
# 使用while循环找出最大数和它的下标
i = 1
while i < len(num_list):
if num_list[i] > max_num:
max_num = num_list[i]
max_index = i
i += 1
print('最大的数是%d,它的位置是%d。' % (max_num, max_index))
运行结果如下:
请输入第1个数:3
请输入第2个数:7
请输入第3个数:1
请输入第4个数:9
请输入第5个数:5
请输入第6个数:2
请输入第7个数:8
请输入第8个数:4
最大的数是9,它的位置是3。
原文地址: https://www.cveoy.top/t/topic/oFdP 著作权归作者所有。请勿转载和采集!