pythonstatements

print two numbers between two integers python


We were given an exercise where a user must input two numbers and the output must be the numbers between the two given numbers, with the condition that the only input are numbers, and if the user types anything besides that will print "INVALID INPUT!"

Here is what I have tried:

num1 = int(input('Give me a #:'))

num2 = int(input('Give me another#:'))


if num1>num2

print("First number should be lesser than second number")


elif num1<num2

print(list(range(num1,num2)))


else:

print("Invalid Input")

Solution

  • num_list = [] # create a list to append all numbers between user's chosen numbers
    while True:
        try:
            num1 = int(input("Enter first number: "))
            num2 = int(input("Enter second number: "))
    
            for i in range(num1+1, num2): # iterate over the range between first number and second number. Add 1 to num1 so that num1 is not included in list
                num_list.append(i) 
    
            print(f'First number: {num1}n\Second number: {num2}')
            print(f'The numbers between {num1} and {num2} are:\n{num_list}')
            break
        except:
            print("Input must be a number. Try again.")