Zjm4192
Zjm4192

Reputation: 103

Using while loop to find smallest user input number

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.

Upvotes: 1

Views: 7971

Answers (3)

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22041

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 !

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81614

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.

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78554

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)

Upvotes: 1

Related Questions