Python for Beginners 05: Basic Output

In this post, we are going to explain something that we have used already in more detail. You already know that to produce output you need to use the function print() from the previous lessons.

How to use the function print():

You can print a variable by just putting its name in the brackets of the print() function, but if you want to write text as output, you have to write the text inside quotation marks “” inside the brackets.

  • If you want to combine different elements, you have to use a comma in between.
  • If you want to combine strings, you can use a + plus. In this case, you have to add a blank space before the second string to create a separation.

Remember: Capital letters make a difference so never write print() with a capital P.

How to format the output:

Since there are so many ways to format your output, I recommend you just search on the Internet for whatever you need. For now, there are three frequent examples

  • By default, there is just a blank space between the different elements in a print(). You can replace the blank spaces by commas by adding sep=”,” before closing the bracket of the print function. Of course, you can just modify it by substituting the comma by a point or any other symbol or text you want.
  • If you want spread your text over multiple lines, you add a backslash followed the letter n (\n) between the words you want to separate.
  • To shorten the amount of digits displayed for a float number, you put ‘%.2f’% (“apostrophe + % + . + number of digits displayed + f + %”) in front of the variable. Here, the number 2 indicates that you only want two digits, but of course you can modify it. Alternative you can use the function round(), but this affects the value of the variable for future operations, whereas formatting only changes the visual appearance of the output.

To practice your newly acquired knowledge (#mastery05), look at the next lesson on basic user input where there is going to be an exercise that includes both output and input.

Leave a comment