Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在不带max()的列表中打印max编号_Python_Python 3.x - Fatal编程技术网

Python 在不带max()的列表中打印max编号

Python 在不带max()的列表中打印max编号,python,python-3.x,Python,Python 3.x,当用户输入一个无效值存储到“number”变量中时,我很难保护脚本不崩溃 程序用途:允许用户输入整数,将其存储到列表中,然后查找并打印最大的数字。不允许在输入中使用字符串或浮动 功能: def getNum(prompt): # Function to call when asking for the numbers later. # Try/except to catch crashes if failing to store integer. try:

当用户输入一个无效值存储到“number”变量中时,我很难保护脚本不崩溃

程序用途:允许用户输入整数,将其存储到列表中,然后查找并打印最大的数字。不允许在输入中使用字符串或浮动

功能:

def getNum(prompt):
    # Function to call when asking for the numbers later.
    # Try/except to catch crashes if failing to store integer.
    try:
        x = input(prompt)
        y = int(x)
        return y

    # Message to print when excepting.
    except:
        print("I was expecting an integer number, please try again... \n")


# Function to swap to highest # in list 'numbers'.
def swap(A, x, y):
    temp1 = A[x]
    A[x] = A[y]
    A[y] = temp1

# Function to perform the looping/swap routine.
# Program can find max with separate function.
## This function is to sort the numbers in the list.
def sortNum(A):
    for i in range(len(A)):
        for k in range(len(A) - 1):
            first = k
            second = k + 1

            if (A[first] > A[second]):
                # Uses Swap function
                swap(A, first, second)

# Function to find the highest number in the list.
def maxIt(numbers):
    maxNum = numbers[0]
    for i in numbers:
        if i > maxNum:
            maxNum = i
    return maxNum

# Start main
def main():

    # Creates the numbers array.
    numbers = []

    # Starts the loop to enter numbers into the array.
    done = False
    while not done:
        numInput = getNum("Please enter an integer or < 0 to finish >: ")

        # Stores every input from numInput into numbers.
        numbers.append(numInput)

        #  Test condition to break out of loop '0'.
        if numInput is 0:

            # Prints the resulting max number once finished.
            print("The maximum value is: " + str(maxIt(numbers)))

            # Flag to stop the program once finished.
            done = True

main()
  • getNum(提示符)
    -测试输入值并将其转换为整数,然后返回y
  • 交换(A,x,y)
    -简单的交换例程函数,用于对数据进行排序。(当前未使用)
  • sortNum(A)
    -对列表中的交换例程进行排序和使用
  • maxIt(numbers)
    -查找列表中的最高数字。(在使用中),如果使用这个max函数,我甚至不需要对列表进行排序
  • main()
  • 代码:

    def getNum(prompt):
        # Function to call when asking for the numbers later.
        # Try/except to catch crashes if failing to store integer.
        try:
            x = input(prompt)
            y = int(x)
            return y
    
        # Message to print when excepting.
        except:
            print("I was expecting an integer number, please try again... \n")
    
    
    # Function to swap to highest # in list 'numbers'.
    def swap(A, x, y):
        temp1 = A[x]
        A[x] = A[y]
        A[y] = temp1
    
    # Function to perform the looping/swap routine.
    # Program can find max with separate function.
    ## This function is to sort the numbers in the list.
    def sortNum(A):
        for i in range(len(A)):
            for k in range(len(A) - 1):
                first = k
                second = k + 1
    
                if (A[first] > A[second]):
                    # Uses Swap function
                    swap(A, first, second)
    
    # Function to find the highest number in the list.
    def maxIt(numbers):
        maxNum = numbers[0]
        for i in numbers:
            if i > maxNum:
                maxNum = i
        return maxNum
    
    # Start main
    def main():
    
        # Creates the numbers array.
        numbers = []
    
        # Starts the loop to enter numbers into the array.
        done = False
        while not done:
            numInput = getNum("Please enter an integer or < 0 to finish >: ")
    
            # Stores every input from numInput into numbers.
            numbers.append(numInput)
    
            #  Test condition to break out of loop '0'.
            if numInput is 0:
    
                # Prints the resulting max number once finished.
                print("The maximum value is: " + str(maxIt(numbers)))
    
                # Flag to stop the program once finished.
                done = True
    
    main()
    
    def getNum(提示):
    #函数在以后询问号码时调用。
    #如果无法存储整数,请尝试/例外捕获崩溃。
    尝试:
    x=输入(提示)
    y=int(x)
    返回y
    #例外时要打印的消息。
    除:
    打印(“我希望是整数,请重试…\n”)
    #用于切换到列表“数字”中最高值的函数。
    def交换(A、x、y):
    temp1=A[x]
    A[x]=A[y]
    A[y]=temp1
    #函数执行循环/交换例程。
    #程序可以使用单独的函数查找max。
    ##此函数用于对列表中的数字进行排序。
    def sortNum(A):
    对于范围内的i(len(A)):
    对于范围内的k(透镜(A)-1):
    第一个=k
    秒=k+1
    如果(A[第一]>A[第二]:
    #使用交换功能
    互换(A、第一、第二)
    #函数以查找列表中的最高数字。
    def maxIt(数字):
    maxNum=数字[0]
    以数字表示的i:
    如果i>maxNum:
    maxNum=i
    返回最大值
    #起动总管
    def main():
    #创建数字数组。
    数字=[]
    #启动循环以在数组中输入数字。
    完成=错误
    虽然没有这样做:
    numInput=getNum(“请输入一个整数或<0以完成>:”)
    #将numInput中的每个输入存储为数字。
    number.append(numInput)
    #断开循环“0”的测试条件。
    如果numInput为0:
    #完成后打印生成的最大数量。
    打印(“最大值为:”+str(最大值(数字)))
    #完成后停止程序的标志。
    完成=正确
    main()
    
    未通过getNum测试(str或float)时的当前输出:

    请输入整数或<0以完成>:222
    请输入整数或<0以完成>:333
    请输入整数或<0以完成>:444
    请输入整数或<0以完成>:555
    请输入整数或<0以完成>:666
    请输入整数或<0以完成>:777
    请输入整数或<0以完成>:888
    请输入整数或<0以完成>:999
    请输入整数或<0以完成>:0
    最大值为:999
    
    在getNum/numInput中输入str或float时出错:

    请输入整数或<0以完成>:222
    请输入整数或<0以完成>:333
    请输入整数或<0以完成>:444
    请输入整数或<0以完成>:测试
    我期待一个整数,请再试一次。。。
    请输入整数或<0以完成>:555
    请输入整数或<0以完成>:666
    请输入整数或<0以完成>:0
    回溯(最近一次呼叫最后一次):
    文件“C:\Users\Bar\Desktop\IS115\Peretz_A9.py”,第64行,在
    main()
    文件“C:\Users\Bar\Desktop\IS115\Peretz_A9.py”,第59行,主目录
    打印(“最大值为:”+str(最大值(数字)))
    文件“C:\Users\Bar\Desktop\IS115\Peretz_A9.py”,第37行,最大值
    如果i>maxNum:
    TypeError:“>”在“NoneType”和“int”的实例之间不受支持
    
    问题在于您的
    尝试..除了在例外情况下不返回任何内容(返回
    ):

    def getNum(prompt):
        # Function to call when asking for the numbers later.
        # Try/except to catch crashes if failing to store integer.
        try:
            x = input(prompt)
            y = int(x)
            return y
    
        # Message to print when excepting.
        except:
            print("I was expecting an integer number, please try again... \n")
            # Returns None resulting in your error
    
    您可以通过将输入放在循环中来避免这种情况:

    def getNum(prompt):
        # Function to call when asking for the numbers later.
        # Try/except to catch crashes if failing to store integer.
        while True:
            try:
                x = input(prompt)
                y = int(x)
                return y
    
            # Message to print when excepting.
            except ValueError:
                print("I was expecting an integer number, please try again... \n")
    

    问题出在函数
    getNum
    中。实际上,当您在输入中键入一些文本时,函数
    getNum
    出现异常,因为您试图将not digit
    str
    强制转换为
    int
    ,然后打印消息,函数返回<代码>无
    None
    存储到numInput中,然后添加到列表中。你知道接下来会发生什么


    为了实现这一点,您应该测试
    getNum
    的输出,您的
    getNum
    返回int或None(打印消息后)
    main
    无条件地追加返回值,即使没有。因此出现了比较消息。改变

        numbers.append(numInput)
    


    问题是,当数字无效时,函数
    getNum
    返回一个None,请尝试以下快速修复方法:

    if numInput is not None:
        numbers.append(numInput)
    
    但我也建议您阅读:


    并尽量避免代码中的empty except子句

    问题是您的try-except返回null而不是循环,因此您应该更具体地处理错误-
    except-ValueError
    ,并使try块尽可能短。