Reputation:
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.)
Upvotes: 0
Views: 65
Reputation: 45736
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:
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.
Upvotes: 4