Learn various tips and tricks based on print()

Various Tips and Tricks:
To perform this tutorial step-by-step with me, you’ll need Python3 already configured on your local development machine. You can set up everything you need before-hand and then come back to continue ahead.

1. Printing sum of two numbers
Printing sum of two numbers is a two-step process:

Define two variables, say a and b and store their sum in third variable, say c.
Print out the sum stored in the third variable, i.e., c.
Both these steps can be implemented in numerous ways in various languages. But we will be using the most basic syntax available with Python’s print statement.

print(“Sum of”, a, “and”, b, “is”, c)
If you want to use more easier syntaxes for doing the same task or this syntax seems difficult to write when you have loads of variables then you can follow on for more better tricks to use with python( ).

C-inspired syntax 😉 : Most of us are already acquainted with print statement of C-language. So, let’s see the same thing in action in Python (we will still need to take care of data types of variables). Here’s the screenshot for this statement:

str.format( ) 🧐 : We can use format( ) available with each String object in Python. It is used to format the string at runtime, i.e., fill in the values just like last syntax did, we just use { } (curly braces) instead of %d or %s. But, the benefit we get is that we don’t need to worry about commas, ‘+’ signs and even data types. str.format( ) allows us to format strings effortlessly.

str.format( ) with a twist 🐍 : In the above syntax, you can use a little variation. Instead of writing variables in a order in which they should replace curly braces, you can write names of variables inside format( ) in any order, and use indexes inside curly braces to select a particular variable whose value should replace that particular curly braces. Keep in mind, the numbering of variables start from because they act like a tuple. This syntax is very helpful when you have got loads of { } to fill up. You can use this variation like this:

We’ll move forward after these 3 syntaxes to look at the latest and easiest print syntax released in Python 3.7. To do that, we need to

Use f-strings instead of format( ), which are nothing but an improvement over it. For that, we need to write ‘f’ just before our string begins to indicate Python that we want to use f-strings
Use { } containing names of variables, instead of empty curly braces, and omit the format( ) part, which makes the complete statement quite shorter.
Read Full Article Here – https://brain-mentors.com/essential-python-print-statement-tips-and-tricks-for-every-programmer/