首页 > 解决方案 > python中的打印功能仅在将数字作为参数而不是变量发送时才有效

问题描述

很难描述,但我的打印函数在发送数字作为参数时有效,但发送整数变量不起作用。我想知道为什么会这样。在 B 部分中调用“prnObj”不起作用,但在 C 部分中调用“prnObj”确实有效

# Validate user's input
def inputNumber(message):
    while True:
        try:
            userInput = int(input(message))
            if userInput < 0 or userInput > 9:
                print('List index range [0-9] Please try again')
                continue
        except ValueError:
            print('Not an integer! Try again.')
            continue
        else:
            return userInput

# resuable print object
def prnObj(listA, listB, start, end):
    print('EmpID\tEmpName')
    for i in range(start, end):
        print('{}\t{}'.format(listA[i], listB[i]))

def main():

    # Create 2 lists
    listA = [15275, 11158, 20046, 20037, 15320,24687, 98728, 45695, 35745,10022]
    listB = ['Stevie', 'Ally', 'Bob', 'Ayesha', 'George', 'Samir', 'Mohammed'
             , 'Zack', 'Eddie', 'Kevin']

    # A) print all names
    print('\nThe list of names are:')
    print(*listB)

    # B) get index from user and print both list(index)
    index = (inputNumber('\nEnter an index #:'))
    prnObj(listA, listB, index, index)
    print('EmpID\tEmpName')
    print('{}\t{}'.format(listA[index], listB[index]))

    # C) Print names from 4th position(not index) to 9th position in list
    print('\nNames from 4th to 9th position in list:\n')
    prnObj(listA, listB, 3, 9)

标签: pythonpython-3.x

解决方案


Python 中的range函数的工作方式是,它从指定的起始索引开始,并且比指定的结束索引小 1。

例如,对于以下代码...

for idx in range(0, 10):
    print(idx, sep=' ')

...输出将是: 0 1 2 3 4 5 6 7 8 9,即从起始索引 (0) 开始,直到小于结束索引 (10 - 1 = 9) 为止。

当您prnObj在 B 部分 ( prnObj(listA, listB, index, index)) 中调用时,您将作为 ' 定义中循环中函数index的开始索引和结束索引发送,因此没有可以采用的值。rangeforprnObji

问题不在于发送整数变量。


推荐阅读