Search code examples
listloopswhile-loopappendmax

Programm tries to append list with a string although it's not allowed


Hello i am pretty new to python and i am currently writing this program, where i try to find the min and max in a list that is created through inputing numbers sequentialy. When i give the programm the input: 5, a, 1 it gives me the following Error:

Traceback (most recent call last):
  File "/home/juli/PycharmProjects/pythonProject/main.py", line 27, in <module>
    mx = max(list,key=float)
ValueError: could not convert string to float: 'a'

Code:

def check_for_float(p_input):
    try:
        ipt = float(p_input)
        return ipt
    except (ValueError, TypeError):
        print("Error, not a numeric input")
        return False

list = []

while True:
    ipt = input("Please enter a numeric value: ")

    if ipt == "done":
        break

    check_for_float(ipt)

    if ipt == type(float) or type(int):
        list.append(ipt)
    elif ipt == type(str):
        continue

if list == []:
    quit()

mx = max(list,key=float)
mn = min(list,key=float)

print(f"Maximum = {mx}; Minimum = {mn}")




I don't know why he has trouble converting the str into a float, because normally there shouldn't even be a str in the max() function. My goal is, that the programm leaves str out that's why i put the continue function there. Thanks for any help.


Solution

  • Just remove this part of your code

    if ipt == type(float) or type(int):
            list.append(ipt)
        elif ipt == type(str):
            continue
    

    and add this code instead

    check = check_for_float(ipt)
        if check:
            list.append(ipt)
        else:
            continue
    

    This code will now filter out any character input and only append the valid numeric values into the list. The complete code should look like this

    def check_for_float(p_input):
        try:
            ipt = float(p_input)
            return ipt
        except (ValueError, TypeError):
            print("Error, not a numeric input")
            return False
    
    list = []
    
    while True:
        ipt = input("Please enter a numeric value: ")
    
        if ipt == "done":
            break
    
        check = check_for_float(ipt)
        if check:
            list.append(ipt)
        else:
            continue
    
        
    
    if list == []:
        quit()
    
    mx = max(list,key=float)
    mn = min(list,key=float)
    
    print(f"Maximum = {mx}; Minimum = {mn}")