【问题标题】:How to print a returned dictionary output from a function inside a string(a sentence) in python? (Processing)如何从python中的字符串(句子)中的函数打印返回的字典输出? (加工)
【发布时间】:2019-05-22 17:25:42
【问题描述】:

我正在创建一个程序,通过以下输入来计算一顿饭的总成本: 餐费、税费、小费率、用餐人数

并通过函数调用将它们打印在字符串中。我在 StackOverflow 上查找,但找不到适合我情况的问题(打印从字符串中的函数返回的字典)

我有一个函数,它接受所有输入并返回字典输出。我想通过函数调用将这些返回值打印在字符串中,所有这些都在同一行中。这是我尝试过的:

def calculatedCost(meal_cost,tax_rate,tip_rate,number_eating):
  tax = round(float(meal_cost * tax_rate) / 100,2)
  tip = round(float(meal_cost * tip_rate) / 100,2)
  total_cost = round(meal_cost + tax + tip,2)
  division = round(total_cost / number_eating,2)
  return {'tax': tax, 'tip': tip, 'total_cost':total_cost, 'division':division} 

print("The cost of your meal is: {total_cost}, the tax on your meal is: {tax}, the tip is equal to: {tip}, and the split total is: {division}".format(calculatedCost(62.75,5,20,2)))

我收到此错误:(我正在使用处理)

KeyError: total_cost
processing.app.SketchException: KeyError: total_cost
at jycessing.mode.run.SketchRunner.convertPythonSketchError(SketchRunner.java:240)
at jycessing.mode.run.SketchRunner.lambda$2(SketchRunner.java:119)
at java.lang.Thread.run(Thread.java:748)

【问题讨论】:

  • Err,你不会在 CPython 中遇到 Java 错误。这是 Jython 吗?
  • 是的,它的 Jython。
  • 请确保您以后也这样标记。如果你没有把 traceback 放进去,我们就不会知道,可能会有各种各样的差异
  • @roganjosh 我忘记了标签,但我写了处理

标签: python processing jython


【解决方案1】:

你需要解压dict(注意双星号):

print("The cost of your meal is: {total_cost}, the tax on your meal is: {tax}, the tip is equal to: {tip}, and the split total is: {division}".format(**calculatedCost(62.75,5,20,2)))

【讨论】:

    猜你喜欢
    • 2014-12-06
    • 2018-07-04
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 2021-03-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多