0

I am trying to complete exercise 5.2 in the book, "Python for Everybody".

I have looked at different solutions but I am trying to write it in my own way. I understand that this code is probably inefficient, but it is the only way that makes sense to me right now.

My idea here is to have the user dump numbers into a list. I have two variables, smallest_value and largest_value, containing some initial values.

Is there a way that I do not need to start out with initial values for smallest_value and largest_value? I have tried "None," but I ran into a problem where a float can't be compared to a None.

I very much appreciate the help!

number_list = []
smallest_value = 1000000
largest_value = -1000000

print('Type in "done" when you are done with the program.')

while True :
    input_data = input("Type in a value: ")
    if input_data == "done" :
        break
    try:
        float_input_data = float(input_data)
    except:
        print('Invalid Input')
        continue
    # Adds user input numbers into a list, number_list
    number_list.append(float_input_data)
    for small_num in number_list:
        if small_num == 1000000:
            smallest_value = small_num
        elif small_num < smallest_value:
            smallest_value = small_num
            #print("The smallest value so far is", smallest_value)
    for large_num in number_list:
        if large_num == -1000000:
            largest_value = large_num
        elif large_num > largest_value:
            largest_value = large_num
            #print("The largest value so far is", largest_value)

#print("All done")
print("The smallest value is", smallest_value)
print("The largest number is", largest_value)
Vinel
  • 5
  • 1

1 Answers1

1

I'd use positive and negative infinity here:

smallest_value = float("inf")  # or math.inf
largest_value = float("-inf")  # or -math.inf

Everything will compare as less than smallest_value, and everything will compare as greater than largest_value initially.

It's certainly possible to use a sentinel value like None to mark "not yet found", but that complicates the logic quite a bit. It's far cleaner to simply use a value that's already valid in your existing code. Infinity, or the largest/smallest valid values of the type are common placeholders for this reason.

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117