Skip to content

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.

  Print function  

To print anything, we just need to pass that in the print() function in double quotes.

Example 3.1.1

print("Hello World")
Example 3.1.1 - Output

Hello 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

name = "Thea"
age = 14
print("Name:", name, "Age:", age)
Example 3.1.2 - Output

Name: Thea Age: 14

 

Example 3.1.3 - Comma-separated arguments approach to print multiple data types

pi = 3.14159
is_holiday = True
print("Value of pi:", pi, "Is it a holiday?", is_holiday)

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 an end 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 a sep 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

name = "Thea"
age = 14
print("Name: " + name + " Age: " + str(age))
Example 3.1.3 - Output

Name: 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 the birth_country variable.

Exercise 3.1.1 - Model Answer - Make sure to work out the exercise before checking the model answer.