Search code examples
pythonfor-loopmaxcomputer-sciencemin

How to make my code read more than one digit at a time? One digit input works but two-digit or more inputs does not work


I am a beginner in Python. My code works for one-digit numbers but not two-digit. I know the for-loop is reading user input one digit at a time but I have no idea how to make it read my input like it would in an array. Ex. 5,7,9 is read as 5,7,9 but 5,70, 9 is read 5, 7, 9.

largest = None
smallest = None
while True:
    try:
        num = input("Enter a number: ")
        num1 = float(num)

    except:
        if "done" == num:
            break
        print("Invalid input")
        continue

    for value in num:
        if smallest is None:
            smallest = num
        if num < smallest:
            smallest = num
            #print(smallest, num)
        elif largest is None:
            largest = num
        if num > largest:
            largest = num
            #print("Maximumcc is:", largest)

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

Solution

  • You're looping over the wrong thing.

    You need to split the input at comma characters. Then loop over those elements, converting each of them to float and testing it.

    largest = None
    smallest = None
    while True:
        response = input("Enter numbers separated by comma, or 'done': ")
        if response == 'done':
            break
    
        try:
            nums = [float(num) for num in response.split(',')]
        except:
            print("Invalid input")
            continue
    
        for num in nums:
            if smallest is None or num < smallest:
                smallest = num
            if largest is None or num > largest:
                largest = num
    
    print("Maximum is:", largest)
    print("Minimum is: ", smallest)