Home > Mobile >  How to find the smallest number using a while loop?
How to find the smallest number using a while loop?

Time:03-29

I cannot use min or any other 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 = int(input("Please enter a number "))
  while smallest != 0 :
    num= int(input("Please enter a number "))

    if (smallest > num):
      smallest = num
    if (smallest == 0) or (num == 0):
      print("Program aborted")

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

CodePudding user response:

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

CodePudding user response:

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

  • Related