如何在Python中的函数range()中传递参数

时间:2019-03-17 21:06:12

标签: python input range

我正在尝试为range函数设置三个参数作为输入。该代码仅需一个参数即可正常工作。我已经搜索了官方文档和pyanative,但没有找到答案。

def range_lister():
    trange=list(range(int(input('Please enter your range: '))))
    print(trange)
range_lister()

2 个答案:

答案 0 :(得分:1)

您可以这样做:

def range_lister():
            '''Example 5:10:2 -> [5,7,9]
            '''
    query = input('Please enter your range start:stop[:step]\n> ')
    values = [int(q) for q in query.split(':')]
    trange = list(range(*values))
    print(trange)


range_lister()

答案 1 :(得分:0)

该方法如何呢?该方法将三个args作为单独的输入行,并提供后备功能以防止(某些)异常:

def safeint(s, fallback):
    try:
        return int(s)
    except ValueError:
        return fallback

def range_lister():
    start = safeint(input("start: "), 0)
    stop = safeint(input("stop: "), 0)
    step = safeint(input("step: "), 1)  # Zero is not valid here
    trange=list(range(start, stop, step))
    print(trange)

....一些测试:

>>> range_lister()
start: 1
stop: 14
step: 3
[1, 4, 7, 10, 13]
>>> range_lister()
start: 
stop: 
step: 14
[]
>>> range_lister()
start: 14
stop: 2000
step: 24
[14, 38, 62, 86, 110, 134, 158, 182, 206, 230, 254, 278, 302, 326, 350, 374, 398, 422, 446, 
470, 494, 518, 542, 566, 590, 614, 638, 662, 686, 710, 734, 758, 782, 806, 830, 854, 878,
902, 926, 950, 974, 998, 1022, 1046, 1070, 1094, 1118, 1142, 1166, 1190, 1214, 1238, 1262,
1286, 1310, 1334, 1358, 1382, 1406, 1430, 1454, 1478, 1502, 1526, 1550, 1574, 1598, 1622,
1646, 1670, 1694, 1718, 1742, 1766, 1790, 1814, 1838, 1862, 1886, 1910, 1934, 1958, 1982]
>>> range_lister()
start: 
stop: 22
step: 
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]