Home > Back-end >  i have thes exam and i dont know the answer
i have thes exam and i dont know the answer

Time:11-27

You want to allow a user to build a numerical list of 7 floating-point numbers and print out the list. You then want to compute the maximum value on the list and output that value. How would you complete the 'if' statement to achieve this goal?

nvals=7
message='Input a number: '
zlist=[ ]
for i in range(nvals):
  zlist.append(float(input(message)))
print('The list = ',zlist)
maxval=zlist[0]
for i in range(1,len(zlist)):
  if zlist[i]>maxval:
    # complete this 'if' statement
print('Maximum value =',maxval)

CodePudding user response:

If block in this case: maxval = zlist[i]

CodePudding user response:

nvals=7
message='Input a number: '
zlist=[ ]
for i in range(nvals):
  zlist.append(float(input(message)))
print('The list = ',zlist)
maxval=zlist[0]
for i in range(1,len(zlist)):
  if zlist[i]>maxval:
    maxval = zlist[i] # the idea here is that if the current value you are iterating is higher than the maxval you have seen so far, then the maxval seen so far needs to be updated to hold the current val you are
print('Maximum value =',maxval)

CodePudding user response:

Here's the basic idea:

  1. You set the 'maximum value' to the first element
  2. Check if the next element of the list is greater than the 'maximum value'.
  3. If it is greater, you set it as the new maximum value
  4. Repeat this process for the rest of the list

By the end of the loop, you will have the maximum value in the list stored in the maxval variable

nvals = 7 # Number of values
message = "Enter a number: " # Prompt message for input

zlist = [] # List of numbers

# Get each number as input from the user
for i in range(nvals):
    zlist.append(float(input(message))

print("The list =", zlist) # Print out the list

maxval = zlist[1] # Set the maximum value as 1st element

# iterate over each element and set maximum value to it
# if it is greater than the current maximum value
for i in range(1, len(zlist))
    if zlist[i] > maxval:
        maxval = zlist[i]

print("Maximum value =", maxval) # Print out the maximum value
  • Related