Skip to content
Advertisement

Define variable in for loop with an unknown number or user number – Noob CS Student

I am a noob CS student trying to get a program running using if/else and while for. I am using the debugger and stepping through the code. I can see that my “current_min” starts at 0 by default and doesn’t change. I know I should grab the user input to define max/min, but when I try to put it in the for loop, it overwrites the max/min exiting with the max and min being the same number. With the current code it works, so long as there is a number less than 0 that goes in. What would be the best course of action here?

# python 3.7
current_max = int()
current_min = current_max

print("How many integers would you like to enter?")
number_of_ints = int(input())  # number of integers user would like to compare
print("Please enter " + str(number_of_ints) + " integers")  # requesting x integers based on user input on previous line

for numints in range(number_of_ints):
    number = int(input())
    if number > current_max:
        current_max = number
    elif number < current_min:
        current_min = number

print("min: ", current_min)
print("max: ", current_max)

Advertisement

Answer

The only issue here is that you initialize your current_min and current_max to 0. The loop will thus check against 0 and only update the values if it is less than (or greater than) 0.

To fix, you should set your current_min and current_max to the first value that the user provides:

number = int(input())
current_min = number
current_max = number

for numints in range(numints-1):
    # your logic from above.
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement