3.1 Print function
3.1a Print function - "Hello World"
The aim of this program is to print "Hello World" on the output of the screen. To do this, we can use the print()
function. The print()
function is a predefined function in Python that prints the specified message as the output.
To print anything, we just need to pass that in the print()
function in double quotes.
Example 3.1.1
Example 3.1.1 - OutputHello World
3.1b Print function with variables
3.1b.1 Comma-separated arguments approach
You can pass multiple arguments to the print function, separated by commas. Each argument can be a variable or a string.
Example 3.1.2 - Comma-separated arguments approach, basic example
Example 3.1.2 - OutputName: Thea Age: 14
Example 3.1.3 - Comma-separated arguments approach to print multiple data types
Example 3.1.3 - Output
Value of pi: 3.14159 Is it a holiday? True
The comma-separated arguments approach for the print
function is a flexible and convenient way to output multiple items. Here are some key points and additional details about using this approach:
- Automatic space insertion - When you use commas to separate multiple arguments in the print function, Python automatically inserts a space between each argument in the output.
- Multiple data types - You can print multiple variables of different data types without needing to explicitly convert them to strings.
- End parameter - The
print
function has anend
parameter that defines what should be printed at the end of the output. More info in topic 3.3 - Separator Parameter - The
print
function also has asep
parameter that specifies the separator between the arguments. More info in topic 3.3
3.1.b.2 String concatenation approach
You can concatenate strings using the +
operator. Note that you need to convert non-string variables to strings using the str()
function. This approach is explained in further detail in topic 3.4.
Example 3.1.3
Example 3.1.3 - OutputName: Thea Age: 14
Note
There are several other ways to use the print()
function. However the f-strings approach have become the preferred choice due to their simplicity, efficiency, and enhanced readability. This will be explained in topic 3.5.
Exercise 3.1.1 - Using the comma-separated arguments approach, write a Python program that does the following:
- Stores the name of the country where you were born in a variable called
birth_country
. - Prints the statement
Hello
followed by the value of thebirth_country
variable.
Exercise 3.1.1 - Model Answer - Make sure to work out the exercise before checking the model answer.