-3

This is the code I came up with. It is not iterating after the second input, it's only printing after 3rd, why is it so?

smallest =  None
while True:
    num = input('Enter a number:')
    if smallest is None:
        smallest = num
        continue
    elif num < smallest:
        smallest = num
        print(smallest)
    elif num == "done":
        break
takendarkk
  • 3,347
  • 8
  • 25
  • 37
  • 1
    Note that `input` returns a string. You're doing ([lexicographic](/q/45950646/11082165)) string comparisons, not numeric comparisons (i.e, `'2' > '10'`). – Brian61354270 Jun 09 '21 at 17:45
  • Does this answer your question? [How can I read inputs as numbers?](https://stackoverflow.com/q/20449427/6045800) – Tomerikoo Jun 09 '21 at 18:09

2 Answers2

0

The problem with your code is that you are taking input.

input() function in python takes input as a string, so you need to typecast this. I am assuming you wanted to compare the integral values so for that, you should use instead int(input("YOUR MSSG")) or if you want to typecast to float then just replace int with float.

Scenarios where your code will show awkward behavior: -

-> Let's say that you want to compare 11 and 2, then if you consider this as an integer, obviously 11 > 2 but when you consider the same thing as a string and do a string comparison then you will see that "11" < "2". As the code in the question is taking the inputs as string and doing the string comparison that's why you are not getting the expected result.

The below code should work perfectly for you: -

smallest =  None
while True:
    num = int(input('Enter a number:'))
    if smallest is None:
        smallest = num
        continue
    elif num < smallest:
        smallest = num
        print(smallest)
    elif num == "done":
        break

You can modify the code as per your requirement.

Pratap Alok Raj
  • 1,098
  • 10
  • 19
0

As Brian said input returns a string, so you would have to pass elif int(num) < int(smallest): to allow it to compare the values as numbers.

If you do this however I would recommend moving elif num == "done": before that statement as int("done") will otherwise cause an error.

bio_dan
  • 78
  • 5