如何简化此代码? (内部打印)

时间:2017-11-04 20:26:13

标签: python optimization printing

我想简化此代码的一部分:

while True:
    print("\nEcris 'quitter' pour quitter")
    try:
        a=float(input("Rentre a: "))
        b=float(input("Rentre b: "))
        c=float(input("Rentre c: "))
    except:
        print("Rentre des chiffres, pas des lettres!")
        continue
    delta=b**2-4*a*c
    print("delta =",delta)
    if delta>0:
        x1=(-b+sqrt(delta))/2*a
        x2=(-b-sqrt(delta))/2*a
        print("Les racines de la fonction"+ str("%+d" % a)+'x²',str("%+d" % b)+'x',str("%+d" % c),"sont x1 =",x1," et x2 =",x2)
    elif delta==0:
        print("La racine de ta fonction",str("%+d" % a)+'x²',str("%+d" % b)+'x',str("%+d" % c),"est x0 =", -b/2*a)
        print("On peut aussi dire que ta fonction est égale à",str(a)+'('+str(b/2*a)+'x)**2')
    elif delta<0:
        print("La fonction",str("%+d" % a)+'x²',str("%+d" % b)+'x',str("%+d" % c),"n'admet pas de racine")

我想这样做,(我试过但是没有用)

fonction = str("%+d" % a)+'x²',str("%+d" % b)+'x',str("%+d" % c)
print("La racine de la fonction"+ fonction +"sont x1 =",x1," et x2 =",x2)

有没有办法让这项工作?

由于

对不起法国人

2 个答案:

答案 0 :(得分:2)

这是第一个:

print("Les racines de la fonction {:+}x²{:+}x{:+} sont x1 = {} et x2 = {}".format(a, b, c, x1, x2))

其他人同样简化。

答案 1 :(得分:0)

如果您使用Python 3.6及更高版本,f-string使其更具可读性,因为变量直接引用到format大括号中:

print(f"Les racines de la fonction {a:+}x²{b:+}x{c:+} sont x1 = {x1} et x2 = {x2}")
相关问题