'How to find the smallest number using a while loop?

I cannot use min, boolean or any other keyword or function. they can enter positive or negative number, so the smallest value will be set as their first number. If they enter 0 as the first number, a program aborted message will appear. Otherwise, they can enter number and then, hit 0. Then a message will pop up stating the smallest number.

    def main():
  smallest = 0

  while smallest == 0 :

    num = int(input("Please enter a number "))
    if num==0:
      print("Program aborted")
    elif smallest == 0:
      smallest = num
    elif num < smallest:
        num = smallest

    num = int(input("Please enter a number "))
    print("Your smallest number was", smallest)
main()

so with this code, it will print two numbers and it will give the smallest. but it shouldn't automatically stop after two numbers, it should stop after 0 is entered.



Solution 1:[1]

You don't need to take seperate input for the smallest. Please use the below code. It will find you the smallest number.

def main():

  smallest = None
  while True :
    num= int(input("Please enter a number "))

    if num == 0:
      print("Program aborted")
      break
    elif smallest is None:
      smallest = num
    elif num < smallest:
        smallest = num

  print("Your smallest number was", smallest)
  
main()

Output:

Please enter a number 5
Please enter a number 3
Please enter a number 2
Please enter a number -10
Please enter a number 6
Please enter a number 0
Program aborted
Your smallest number was -10

Solution 2:[2]

you can do something like this:

nums = [int(i) for i in input("Enter the numbers seperated by a space:\n" ).split()]
smallest  = nums[0]
for num in nums:
  if num < smallest:
    smallest = num;
print(f"The smallest number out of {nums}, is {smallest}");

what the code does is first it allows you to input a string of numbers, (separated by a space of course), and then takes each number and puts it in a list. Then it temporarily sets the smallest number to the first number in the list, and iterates through the list one by one to check the numbers in the list against the smallest number. If the current number that it is checking is smaller than the smallest number variable, then it becomes the new smallest number. At the end, it prints out the smallest number in a print statement.

oops sorry forgot it had to use a while loop

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vishwa Mittar
Solution 2 Luke Wright