How do you write multiple statements in python?


More than one statements in a block of uniform indent form a compound statement. Normally each statement is written on separate physical line in editor. However, statements in a block can be written in one line if they are separated by semicolon. Following is code of three statements written in separate lines

a=10
b=20
c=a*b
print (c)

These statements can very well be written in one line by putting semicolon in between.

a=10; b=20; c=1*b; print (c)

A new block of increased indent generally starts after : symbol as in case of if, else, while, for, try statements. However, using above syntax, statements in block can be written in one line by putting semicolon. Following is a straight forward example of a block of statements in a for loop

for i in range(5):
   print ("Hello")
   print ("i=",i)

This block can also be written in single line as follows −

for i in range(5): print ("Hello"); print ("i=",i)

However, this practice is not allowed if there is a nested block of statements.

How do you write multiple statements in python?

Updated on 20-Feb-2020 08:08:54

  • Related Questions & Answers
  • How is it possible to enter multiple MySQL statements on a single line?
  • How can we combine multiple print statements per line in Python?
  • Multiple Statements in Python
  • Multi-Line Statements in Python
  • How to execute Python multi-line statements in the one-line at command-line?
  • How to indent multiple if...else statements in Python?
  • How to provide new line in JavaScript alert box?
  • How to Transpose a matrix in Single line in Python?
  • Plotting a horizontal line on multiple subplots in Python using pyplot
  • How do we write Multi-Line Statements in Python?
  • Group buttons on a single line with Bootstrap
  • How to concatenate multiple C++ strings on one line?
  • How to write a single line in text file using Python?
  • Multiple Assignments to Single Value in Python
  • Multiple ALV grids on a single screen in SAP ABAP

For a python -c oriented solution, and provided you use Bash shell, yes you can have a simple one-line syntax like in this example:

Suppose you would like to do something like this (very similar to your sample, including except: pass instruction):

python -c  "from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n" OUTPUT_VARIABLE __numpy_path

This will not work and produce this error:

  File "", line 1
    from __future__ import print_function\ntry: import numpy; print( numpy.get_include(), end='\n' )\nexcept:pass\n
                                                                                                                  ^
SyntaxError: unexpected character after line continuation character `

This is because the competition between Bash and Python interpretation of \n escape sequences. To solve the problem one can use the $'string' Bash syntax to force \n Bash interpretation before the Python one.

To make the example more challenging, I added a typical Python end=..\n.. specification in the Python print call: at the end you will be able to get both \n interpretations from Bash and Python working together, each on its piece of text of concern. So that finally the proper solution is like this:

python -c  $'from __future__ import print_function\ntry:\n import numpy;\n print( numpy.get_include(), end="\\n" )\n print( "Hello" )\nexcept:pass\n' OUTPUT_VARIABLE __numpy_path

That leads to the proper clean output without an error:

/Softs/anaconda/lib/python3.7/site-packages/numpy/core/include
Hello

Note: this should work as well with exec-oriented solutions, because the problem is still the same (Bash and Python interpreters competition).

Note 2: one could work around the problem by replacing some \n by some ; but it will not work anytime (depending on Python constructs), while my solution allows to always "one-line" any piece of classic multi-line Python program.

Note 3: of course, when one-lining, one has always to take care of Python spaces and indentation, because in fact we are not strictly "one-lining" here, but doing a proper mixed-management of \n escape sequence between bash and Python. This is how we can deal with any piece of classic multi-line Python program. The solution sample illustrates this as well.

Problem: Given multiple Python statements. How to write them as a Python One-Liner?

Example: Consider the following example of four statements in a block with uniform indentation:

a = 1
b = 2
c = a + b
print(c)

Each of the four statements is written in a separate line in a code editor—this is the normal procedure. However, what if you want to one-linerize those:

How to write all four statements in a single line of code?

Solution: The answer is simple if all statements have a uniform indentation and there’s no nested block. In this case, you can use the semicolon as a separator between the statements:

a = 1; b = 2; c = a + b; print(c)

Let’s do some practice testing to learn and improve your Python skills:

Exercise: one-linerize the given code! Run the code and check if the one-liner does the same as the original code!

  • Indented Block
  • Nested Indentation Blocks
  • Python One-Liners Book: Master the Single Line First!

Indented Block

While this works beautifully, if all statements are not indented—does it still work if you have an indentation block that starts with the colon : symbol after if, elif, else, for, while, or try/except statements?

Here’s an example of such a block:

for i in range(10):
   c = i ** 2
   print (c)

You try the following one-liner using the semicolon as a separator between the two statements in the block

for i in range(10): c = i ** 2; print(c)
'''
0
1
4
9
16
25
36
49
64
81
'''

This works beautifully and Python understands what you are trying to do. However, if you have nested indentation blocks, this doesn’t work anymore.

Consider the following example:

for i in range(3):
    for j in range(3):
        print(i, j)

If you write this in a single line, Python throws a syntax error:

How do you write multiple statements in python?

While you can discuss if this makes sense or not—given that the syntax is not ambiguous here—it doesn’t change the fact: nested block cannot be one-linerized in a straightforward way. But this doesn’t prevent us from doing it, right?

Nested Indentation Blocks

Read the following article to learn how to compress multiple lines of code into a single line!

Summary: To make a Python one-liner out of any multi-line Python script, replace the new lines with a new line character '\n' and pass the result into the exec(...) function. You can run this script from the outside (command line, shell, terminal) by using the command python -c "exec(...)".

[Don't Do This At Home] How To One-Linerize Every Multi-Line Python Script & Run It From The Shell

This method is very powerful and it allows you to compress any complicated multi-line script in a single line of Python code!

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

How do you write multiple statements in python?

Python One-Linerswill teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

How do you write multiple statements in python?

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners (NoStarch 2020), coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

How do you make multiple statements in Python?

You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.

What is multiple statements in Python?

Multiple Statement Groups as Suites A group of individual statements, which make a single code block are called suites in Python. Compound or complex statements, such as if, while, def, and class require a header line and a suite.

What is multiline statement in Python explain with example?

Statements in Python typically end with a new line. Python does, however, allow the use of the line continuation character (\) to denote that the line should continue. For example − total = item_one + \ item_two + \ item_three.

How do you add statements in Python?

Basically, to add new statements, you must edit Python/ast. c (among other things) and recompile the python binary. While it's possible, don't. You can achieve almost everything via functions and classes (which wont require people to recompile python just to run your script..)