I am new to using the timeit module, and I'm having a hard time getting multi-line code snippets to run inside timeit.
What works:
timeit.timeit(stmt = "if True: print('hi');")
What does not work (these all fail to even run):
timeit.timeit(stmt = "if True: print('hi'); else: print('bye')")
timeit.timeit(stmt = "if True: print('hi') else: print('bye')")
timeit.timeit(stmt = "if True: print('hi');; else: print('bye')")
I have found that I can use triple-quotes to encapsulate multi-line code segments, but I'd rather just type on one line.
Is there any way to use an else statement inside one line in timeit?
The string you provide is interpreted as a source code, so you can use multiline strings with three quotation marks, like
or
\n
for newlines (but it looks pretty messy)You can also use ternary
if-else
condition if you need only a single branch (so no newline is required):