调用一个函数来打印一些东西



我在试图打印printResults函数中的所有内容时遇到了麻烦。我不确定如何使用printResults函数打印maxmin值及其index位置,而不必在其中输入numindex参数,因为我调用该函数来找到这些东西。下面是我的代码:

def minValue(numbers):
num_min = numbers[0]
location = 0
for i in range(len(numbers)):
if numbers[i] < num_min:
num_min = numbers[i]
location = i
return (num_min, location)

def maxValue(numbers):
num_max = numbers[0]
location = 0
for i in range(len(numbers)):
if numbers[i] > num_max:
num_max = numbers[i]
location = i
return (num_max, location)
def printResults(flag, num, index):
if flag == 0:
print("The min value is  ", num, ", it's at index ", index, ".")
else:
print("The max value is  ", num, ", it's at index ", index, ".")
def printList(nums):
last_element = nums[len(nums)-1]
for i in nums:
if last_element == i:
print(i, end=".")
else:
print(i, end=", ")
print()
def createList(start=0, end=50, increment=1):
nums = []
for i in range(start, end, increment):
nums.append(i)
random.shuffle(nums)
return nums

这是我调用函数和打印东西的代码:

#create a list of numbers which are multiples of 3, between 3 and 50
theList = (createList(3, 51, 3))
printList(theList)
minNum = minValue(theList)
maxNum = maxValue(theList)
print(minNum)
print(maxNum)

如果您只想调用printResults()函数(有更好的方法),那么您需要意识到索引也从minValue()maxValue()函数返回,您应该在它们自己的变量中捕获它们:

minNum, minIndex = minValue(theList)
maxNum, maxIndex = maxValue(theList)
printResults(0, minNum, minIndex )
printResults(1, maxNum, maxIndex )

相关内容

  • 没有找到相关文章

最新更新