1

Hey guys I cannot figure out how to use a while loop to find the smallest number entered by a user. I know I have to assign a number entered to stop the program then print the smallest number that was entered. This is what I have so far:

while(True):
    A = int(input("Enter a Number (Use -1 to Stop): " ))
    if(A == -1):
        break

Any help would be appreciated, thank you.

3 Answers 3

1

Initialize the number before the loop, then update its value if the new number is less. This should do:

# initialize minimum
minimum = int(input("Enter a Number: " ))
while(True):
    A = int(input("Enter a Number (Use -1 to Stop): " ))
    if(A == -1):
        break
    if minimum > A:
        minimum = A
print(minimum)
Sign up to request clarification or add additional context in comments.

2 Comments

this worked, thank you so much! How did you know to initialize it?
If you're going to compare with new values, you should at least have an initial value :-)
1

You could easily store all the values in a list and then use min, but if you insist not to:

min_val = None
while True:
    A = int(input("Enter a Number (Use -1 to Stop): " ))
    if A == -1:
        break
    if not min_val or A < min_val:  
        min_val = A

The if checks whether it is the first value the user inputs or if the new value is smaller than the previous minimum.
When the while breaks, min_val will either be None (if the first value the user inputs is -1) or the minimum value the user entered.

Comments

1

Code below would suit your need:

b = -1
while(True):
    A = int(input("Enter a Number (Use -1 to Stop): " ))
    if(A == -1):
        print b
        break
    b = b if A > b else A

Good Luck !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.