无法将代码格式化为所需的输出
Having trouble formatting code to desired output
我试图让代码以下面的格式打印,但似乎没有任何效果。有人可以指出代码或逻辑中的错误吗?
所需格式: 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
您需要在循环外定义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
我试图让代码以下面的格式打印,但似乎没有任何效果。有人可以指出代码或逻辑中的错误吗?
所需格式: 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
您需要在循环外定义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