简体   繁体   English

我如何/可以只在一行中输入此代码?

[英]How can i/can i type this code in only one line?

I made a really simple calculator with this code:我用这段代码做了一个非常简单的计算器:

while True:
    calc_input = input("enter calculation")
    print(f"{calc_input} = {eval(calc_input)}")

Me, and my friend (We both are new in programming) tried to convert this to a one line code, but we failed.我和我的朋友(我们都是编程新手)试图将其转换为一行代码,但我们失败了。 I need an understandable explanation of how can i type this code in one line (or can i).我需要一个可以理解的解释,说明如何在一行中输入此代码(或者我可以)。 (I don't need the same code in one line, any code in one line that can do the same job as my code would be okay for me.) (我不需要在一行中使用相同的代码,任何可以与我的代码完成相同工作的代码对我来说都可以。)

For the sake of answering the question, this should work:为了回答这个问题,这应该有效:

while True: print(f"{(calc_input := input("enter calculation")} = {eval(calc_input)}")

Or, by just using print 's var-arg behavior:或者,仅使用print的 var-arg 行为:

while True: print((calc_input := input("enter calculation")), '=', eval(calc_input))

:= is like = , but it's an expression, so it can be used anywhere. :=类似于= ,但它是一个表达式,所以它可以在任何地方使用。

For the love of God though, please don't do this.不过,看在上帝的份上,请不要这样做。 This may be nice if you're code-golfing or something, but it fails the readability test.如果您正在打代码或其他什么东西,这可能会很好,但它无法通过可读性测试。 This code over several lines is fine.这段代码多行很好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM