python - 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)
解决方案
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
的开始索引和结束索引发送,因此没有可以采用的值。range
for
prnObj
i
问题不在于发送整数变量。
推荐阅读
- powershell - PowerShell Invoke-Command 连接错误
- python - 冒泡排序算法中的循环究竟是如何工作的?(Python 3)
- python - Dialogflow v2 api 在 Python 中的身份验证失败
- python - Trying to copy files with a specific extension from source folder to destination folder
- node.js - socket.io 连接在生产中失败,在 localhost 中工作
- javascript - Uncaught TypeError: this.getView is not a function inside the onPress event in meassage box in sap UI5
- vb.net - DateTime 格式和 ToString 格式
- pouchdb - 从客户端删除 PouchDB 文档而不清除浏览器
- reactjs - 在 React 中更改受控输入的值
- json - 如何通过 sed 命令将单行 json 转换为多行