关于#python#的问题:问题遇到的现象和发生背景

为什么我给定begin 和 end 的值时就可以运行,而我使用input函数赋值运行时却显示错误?

img

input()默认从键盘得到的是字符串类型,所以需要使用int()将其转化成整数再交给函数运算

因为input()函数返回的对象是“字符串”型数据,而程序中range()函数不将字符串作为参数。
range()函数一般将整数型数据作为参数。
对代码作如下修改即可成功运行:

begin=int(input())
end=int(input())
def get_even_numbers(begin,end):
    result =[]
    for i in range(begin,end):
        if i % 2 == 0:
            result.append(i)
    return result
print(f"begin= [begin), end= [end), even numbers: ",get_even_numbers(begin,end))

另外,其实可以对这段代码作如下修改,使其更可读、更易操作:

print('欢迎使用检索偶数程序。\n运行过程中按Ctrl+C随时退出。')
def get_even_numbers(begin,end):
    result =[]
    for i in range(begin,end+1):
        if i % 2 == 0:
            result.append(i)
    return result
while True:
    value=1
    try:
        begin=int(input('请输入起始数字:').strip())
        end=int(input('请输入终止数字:').strip())
    except ValueError:
        print('您输入的不是整数,请重新输入。')
        value=0
    if value:
        print(f"begin={begin}, end={end}, even numbers: ",get_even_numbers(begin,end))

因为input()得到的值类型是字符串,你的代码只需要将前两行改为这样就行:


begin=int(input())
end=int(input())