0

This is my code which iterates and takes inputs as the number and when user input "done", it comes out of loop and print smallest and largest of the input numbers.

largest = None
smallest = None
while True:
num = input("Enter a number: ")
if num == "done" : 
    break
try:
    a = int(num)
except:
    print("Invalid input")
if largest is None:
    largest = num
if smallest is None:
    smallest = num
if smallest > num:
    smallest = num
if largest < num:
    largest = num  
print(smallest, largest)    #for dry run
print("Maximum is", largest)
print("Minimum is", smallest)

Now my problem is whenever I input a non-number such as bob, it gets assigned to largest and print maximum number as bob.

  • Looks like the indenting got messed up. You can [edit] to fix it. – wjandrea Jul 24 '20 at 16:48
  • Move the `if` statements to inside the `try` block so they only get executed if no exception. – 001 Jul 24 '20 at 16:49
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) - tl;dr use `continue` if you get invalid input – wjandrea Jul 24 '20 at 16:50
  • BTW, you can simplify: `if largest is None or largest < num: largest = num` – wjandrea Jul 24 '20 at 16:56
  • Or even: `largest = max(a, largest) if largest else a` – 001 Jul 24 '20 at 16:59
  • @Johnny That will fail on `largest = 0`. Fixed: `largest = max(a, largest) if largest is not None else a` – wjandrea Jul 24 '20 at 17:03
  • @wjandrea True. – 001 Jul 24 '20 at 17:06

1 Answers1

2

You are acknowledging that int(num) failed, but then using the value of num (rather than a) anyway. You could continue the loop instead. With correct indentation, your code should look something like

largest = None
smallest = None

while True:
    num = input("Enter a number: ")
    if num == "done": 
        break

    try:
        a = int(num)
    except ValueError:
        print("Invalid input")
        continue

    if largest is None:
        largest = a
    if smallest is None:
        smallest = a
    if smallest > a:
        smallest = a
    if largest < a:
        largest = a  

print(smallest, largest)    #for dry run
print("Maximum is", largest)
print("Minimum is", smallest)
chepner
  • 497,756
  • 71
  • 530
  • 681