下面的程序是一个使用dictionary.get()测试print()执行的例子。
验证码:
miles_between_oil_change = 7500
miles_warning = 500
miles_notify = miles_between_oil_change - miles_warning
def validInput(initial_mileage, final_milege):
if initial_mileage > final_milege:
return False
return True
"""
Return values:
0 - User doesn't need to change oil
1 - User needs to change oil soon
2 - User needs to change oil immediately
"""
def userToBeNotified(initial_mileage, final_mileage):
miles_travelled = final_mileage - initial_mileage
if miles_travelled < miles_notify:
return 0
elif miles_travelled > miles_notify:
return 2
else:
return 1
def readInput():
previous_mileage = int(input('Enter mileage of last oil change: '))
current_milege = int(input('Enter current mileage: '))
return previous_mileage, current_milege
def main():
previous_mileage, current_milege = readInput()
if not validInput(previous_mileage, current_milege):
print('Invalid entry - Current mileage is less than mileage last changed')
exit()
user_notification = userToBeNotified(previous_mileage, current_milege)
switcher = {
0: print("User doesn't need to change oil"),
1: print("User needs to change oil soon"),
2: print("User needs to change oil immediately"),
}
switcher.get(user_notification)
if __name__ == "__main__":
main()
字符串
输出:
Enter mileage of last oil change: 5000
Enter current mileage: 13000
User doesn't need to change oil
User needs to change oil soon
User needs to change oil immediately
型
预期输出:
Enter mileage of last oil change: 5000
Enter current mileage: 13000
User needs to change oil immediately
型
我试着调用switcher.get(),假设它只打印与键值匹配的语句。但是,我看到字典中所有条目的所有值都被打印出来了。
1条答案
按热度按时间ttygqcqt1#
.get()
调用并不是导致打印的原因,它是在调用print的地方创建字典。如果您将代码简化为dict创建并运行它,您仍然可以看到所有三个print
。尝试运行以下命令:字符串
当你写
print('message')
时,你会立即调用print
。同样地,线型
将立即
print
message
。由于print
返回None
,结果将是s = None
。你也在做类似的事情。您可以使用字符串本身替换
print
调用。然后从dict中检索字符串并打印出来型
如果您的意图是模拟switch语句而不是在数据中表示选项,那么您有几种选择
你可以使用和其他-如果梯子
型
或者,如果您可以访问Python 3.10+,则可以使用
match
型