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.
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.
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)
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 !
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.