不使用内置函数的python最大最小代码问题

问题描述 投票:-2回答:2

标题##代码为:

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)

它只给出输出:无效的输入,最大值为10,为什么它不能生成最小值,有人可以帮助我解决这个问题,请

python python-3.7
2个回答
0
投票

我是您使用的代码elif,所以在时间上仅执行一个块。

您的print语句位于if块内部,因此仅在条件为true时才执行。这就是为什么只打印无效输入,最大为10

尝试以下代码:

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)

0
投票

打印出来的纸应该写在外面以获得最终的价值。一个可能的答案。

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)
© www.soinside.com 2019 - 2024. All rights reserved.