In the code below I want the loop to run until user enters 'done' I want the minimum number. I initialized smallest with 0 but didn't work well as you can see in output below the code
smallest= 0
while True:
num = input("Enter a number: ")
if num == "done":
break
if (int(num)<smallest):
smallest=int(num)
print("Minimum is", smallest)
Output:
Enter a number: 2
Enter a number: 5
Enter a number: 100
Enter a number: 15
Enter a number: done
Minimum is 0
Now even if I try with smallest=100 and I start to enter number as 101,102,103 then also it will show 100 but I want a general solution. I hope you can give me the answer and thank you in advance
CodePudding user response:
If you really want to allow any numbers:
import math
smallest = math.inf
CodePudding user response:
I would recommend initializing to None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done":
break
# force num to be saved to smallest if it's the first one
if smallest is None or int(num) < smallest:
smallest = int(num)
print("Minimum is", smallest)
Note also that the if-condition lower down has changed to force the first input number to be saved into smallest
CodePudding user response:
There is also one thing you can do
smallest = 0
a = (input("Enter a number: "))
if a!='done':
smallest = int(a)
while(a!='done'):
a = (input("Enter a number: "))
if a == 'done':
break
if int(a) < smallest:
smallest = int(a)
print("Smallest : ",smallest)
You can first input and initialize smallest to that number
CodePudding user response:
Maybe think about why you are setting smallest to 0 in the first place. In your case, setting smallest to 0 at compile time means that 0 is your smallest number up until this point and if the list of numbers you are inputting don't contain numbers <=0 then 0 will always be the smallest even if it is not found in your input.
Try setting smallest to the first number the user enters, then make your comparisons after.
ie.
smallest = input("Enter a number: ")
while True:
num = input("Enter a number: ")
etc.
CodePudding user response:
You could do,
smallest = float(‘inf’)