简体   繁体   中英

python maximum minimum code problem without using builtin function

Heading ##The code is:

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

It only gives output like: Invalid input and maximum is 10, why it can't generate a minimum number, can anyone help me with the problem, please

I your code you use elif so at time only one block is executed.

You print statement is inside the if block so it only executed if condition is true. that's why it print only Invalid input and maximum is 10

Try below code:

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

print should be written outside to get the final value.one possible answer.

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

 print("Maximum is",largest)
 print("Minimum is",smallest)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM