为什么这个 while 循环不能正确执行

我正在尝试编写一个基本代码,提示用户输入数字列表作为单独的输入,然后识别最大和最小的数字。如果用户输入数字以外的任何内容,代码应返回“无效输入”消息。该代码似乎运行了两个输入一次,但随后 while 输入似乎完全损坏了,我不确定它出了什么问题。


largest = None

smallest = None


try:

    num1 = input("Enter a number: ")

    num1 = int(num1)

    largest = num1

    smallest = num1


    while True:

        num = input("Enter a number: ")

        if num == "done" :

            break

        if num > largest:

            largest = num

        if num < smallest:

            smallest = num

        else: continue

except:

    print('Invalid input')




print("Maximum is ", largest)

print("Minimum is ", smallest)


牧羊人nacy
浏览 108回答 3
3回答

浮云间

如果您检查“完成”的退出条件并且输入不是“完成”,则将字符串转换为整数。然后所有 if 条件都会正确,并且您的 while 循环应该运行。largest = Nonesmallest = Nonetry:&nbsp; &nbsp;num1 = input("Enter a number: ")&nbsp; &nbsp;num1 = int(num1)&nbsp; &nbsp;largest = num1&nbsp; &nbsp;smallest = num1while True:&nbsp; &nbsp; num = input("Enter a number: ")&nbsp; &nbsp; if num == "done" :&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; num = int(num)&nbsp; &nbsp; if num > largest:&nbsp; &nbsp; &nbsp; &nbsp; largest = num&nbsp; &nbsp; if num < smallest:&nbsp; &nbsp; &nbsp; &nbsp; smallest = num&nbsp; &nbsp; else: continueexcept:&nbsp; &nbsp; print('Invalid input')print("Maximum is ", largest)print("Minimum is ", smallest)

宝慕林4294392

这是一个简单的方法:lst = []while True:&nbsp; &nbsp; try:&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; lst.append(int(input("enter a number: ")))&nbsp; &nbsp; except:&nbsp; &nbsp; &nbsp; &nbsp; breakprint(f"max is {max(lst)}")print(f"min is {min(lst)}")enter a number: 10enter a number: 22enter a number: 11enter a number: 22enter a number: 4enter a number: donemax is 22min is 4

繁星淼淼

除了其他更正之外:largest = Nonesmallest = Nonetry:&nbsp; &nbsp; num1 = int(input("Enter a number: "))&nbsp; &nbsp; largest = num1&nbsp; &nbsp; smallest = num1&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; num = input("Enter a number: ")&nbsp; &nbsp; &nbsp; &nbsp; if str(num) == "done" :&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; &nbsp; &nbsp; if int(num) > largest:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; largest = num&nbsp; &nbsp; &nbsp; &nbsp; if int(num) < smallest:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; smallest = num&nbsp; &nbsp; &nbsp; &nbsp; else: continueexcept:&nbsp; &nbsp; print('Invalid input')print("Maximum is ", largest)print("Minimum is ", smallest)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python