打印两个整数之间的两个数字 python

print two numbers between two integers python

我们得到了一个练习,其中用户必须输入两个数字,输出必须是两个给定数字之间的数字,条件是唯一的输入是数字,如果用户输入除此之外的任何内容,将打印“输入无效!”

这是我尝试过的:

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")

您有语法错误,请在 if 和 else 条件后添加冒号 :,例如

if condition:
    pass
elif condition2:
    pass
else:
    pass

你应该试试这个。当您尝试将数字以外的任何内容转换为整数时,会引发 ValueError。你可以抓住它来打印错误

while True:
    try:
        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+1,num2)))
            break
    except ValueError:
        print("Invalid Input")
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.")