功能定义&变量:
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000 / 10
print statement:
print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, (secret_formula(start_point)))
我得到的错误信息是“%d格式:需要一个数字,而不是一个元组。 请帮我修理一下。我是编程新手......还是不可能将变量和被调用的函数打包到同一个formattet打印中?
答案 0 :(得分:0)
python 2中的变体:
print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % ((start_point, ) + secret_formula(start_point))
我通过将元组(start_point, )
添加到函数的结果来创建一个新元组。
在python 3中,你可以unpack the tuple with a *
:
print("""crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, *secret_formula(start_point)))
答案 1 :(得分:0)
考虑添加*
以解包元组(python 3.x解决方案):
print ("""crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, *(secret_formula(start_point))))
如果你正在使用python 2.x可以输入:
start_point = 10000 / 10
res = secret_formula(start_point)
print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, res[0], res[1], res[2])
答案 2 :(得分:0)
#According to zen of python Explicit is better than implicit, so
bs, js, cs = secret_formula(start_point)
print """crazy different style:
startpoint: %d\n
beans:\t\t %d\n
jars:\t\t %d\n
crates:\t\t %d\n
""" % (start_point, bs, js, cs)
答案 3 :(得分:0)
使用python 3
def secret_formula(started):
jelly_beans = started * 500
jars = jelly_beans / 1000
crates = jars / 100
return jelly_beans, jars, crates
start_point = 10000 / 10
print ("startpoint : {0} \n \
beans:\t\t {1} \n \
jar :\t\t {2}".format(start_point,*secret_formula(start_point)[:2]))
输出
startpoint : 1000.0
beans: 500000.0
jar : 500.0