【问题标题】:Having trouble formatting code to desired output无法将代码格式化为所需的输出
【发布时间】:2020-09-25 17:04:05
【问题描述】:

我正在尝试让代码以以下格式打印,但似乎没有任何效果。有人能指出代码或逻辑中的错误吗?

所需格式: We have got only 3 oranges and only 1 apple

代码:

excess = {"apple": 5, "orange": 6}
s = ""
for k, v in excess.items():
    n = 1
    if n == 0:
        s = "We have got only {} {} ".format(v, k)
    elif n > 1:
        s += "and {} {}".format(v, k)  
    n += 1
print(bill, s)

输出

We have only 6 orange

【问题讨论】:

  • 我质疑你是如何得到输出“我们只有 6 个橙色”的。首先,bill 未在此代码块中定义,您在循环的每次迭代中设置n = 1。因此n == 0n > 1 总是为假,所以你的代码块应该返回一个空字符串s = ""

标签: python string.format


【解决方案1】:

您需要在循环外定义n,并将n>1 条件替换为n>0(或else

excess={"apple":5,"orange":6}
s=""
n=0

for k,v in excess.items():
    if n==0:
        s="We have got only {} {}".format(v,k)
    else:
        s+=" and {} {}".format(v,k)  
    n+=1
    
print(s)
# We have got only 5 apple and 6 orange

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-21
    • 1970-01-01
    • 2012-03-22
    • 2018-05-02
    相关资源
    最近更新 更多