The print() Function (Python Programming)
Learn The print() Function (Python Programming) step by step with clear examples and exercises.
Title: The print() Function (Python Programming)
Why This Matters
The print() function is a fundamental aspect of Python programming, allowing you to output text and variables to the console during runtime. Understanding its usage is crucial for debugging, testing, and developing your programs effectively. In interviews, interviewers often test your knowledge about this function, so it's essential to master it.
Prerequisites
Before diving into the print() function, you should have a basic understanding of Python syntax, variables, data types, control flow, and functions. If you are new to Python, we recommend reviewing our previous lessons on Python basics, variables, data types, control flow, and functions before proceeding.
Core Concept
The print() function is used to display output in the console during runtime. It can print text, variables, and even formatted strings. Here's a basic example:
print("Hello, World!")
To include variables within the string, you can use the + operator or Python's f-string syntax (introduced in Python 3.6):
name = "John"
print(f"Hello, {name}! Welcome to Python.")
You can also print variables on their own:
x = 10
y = 20.5
z = True
print(x)
print(y)
print(z)
The end and sep parameters allow you to customize the end separator and the separator between multiple values, respectively. For example:
numbers = [1, 2, 3]
print(*numbers, sep=", ", end="\n")
Output:
1, 2, 3
Formatted Strings (f-strings)
Introduced in Python 3.6, f-strings provide a more readable and concise way to include variables within strings. Here's an example using f-strings:
name = "John"
age = 25
print(f"Hello, {name}! You are {age} years old.")
Escaping Characters
In some cases, you may need to print special characters like quotes or backslashes. To do this, you can use escape sequences:
print("John said, \"Hello, World!\"")
print(r"John said, \"Hello, World!\"")) # raw string for literal backslashes
String Formatting (Older Method)
Before f-strings were introduced in Python 3.6, you could use the .format() method to include variables within strings:
name = "John"
age = 25
print("Hello, {}! You are {} years old.".format(name, age))
Worked Example
Let's create a simple program that takes user input for their name and age, calculates their BMI (Body Mass Index), and prints the result.
Ask the user for their name, weight, and height
name = input("What is your name? ")
weight = float(input("What is your weight in kilograms? "))
height = float(input("What is your height in meters? "))
Calculate BMI (Body Mass Index)
bmi = weight / (height 2)
Print the result
print(f"Hello, {name}! Your Body Mass Index (BMI) is {bmi:.2f}")
Common Mistakes
- ### Forgetting to add parentheses
Incorrect: print Hello, World!
Correct: print("Hello, World!")
- ### Using the wrong separator or end character
Incorrect: print(1, 2, 3)
Correct: print(*[1, 2, 3], sep=", ", end="\n")
- ### Forgetting to include quotes around strings containing variables
Incorrect: print x
Correct: print(x) or print(f"{x}")
- ### Using the wrong data type for a variable (e.g., using a string instead of a float for a numerical calculation)
Incorrect: weight = "10"
Correct: weight = 10.0 or weight = 10
- ### Forgetting to convert user input to the appropriate data type (e.g., converting string input to float for numerical calculations)
Incorrect: age = input("What is your age? ") + 1
Correct: age = int(input("What is your age? ")) + 1 or age = float(input("What is your age? ")) + 1
- ### Forgetting to escape special characters in strings (e.g., using a backslash without an escape sequence)
Incorrect: print("Hello, \World!")
Correct: print("Hello, \\World!") or print(r"Hello, \World!")
- ### Using the wrong syntax for f-strings (e.g., forgetting to use the
fprefix)
Incorrect: print "Hello, {name}!"
Correct: print(f"Hello, {name}!")
Practice Questions
- Write a program that prints the sum of two numbers entered by the user using f-strings.
- Write a program that calculates and prints the area of a rectangle with length and width input by the user.
- Write a program that takes three strings as input, concatenates them in reverse order, and prints the result.
- Write a program that takes a list of numbers as input and prints their sum using f-strings.
- Write a program that takes a string as input and counts the number of vowels it contains (case-insensitive).
- Write a program that takes two strings as input, reverses each string, and checks if they are anagrams (i.e., the same letters but in a different order).
- Write a program that takes a list of numbers as input, sorts them in ascending order, and prints the median number.
- Write a program that takes a string as input, counts the number of occurrences of each letter, and prints the result.
- Write a program that takes two dates (year-month-day) as input, calculates the number of days between them, and prints the result.
- Write a program that takes a list of numbers as input, finds the largest prime number in the list, and prints its index.
FAQ
### How can I print multiple variables on the same line, separated by spaces?
You can use the print() function with the sep parameter set to a space:
x = 5
y = 10
z = "Hello"
print(x, y, z, sep=" ")
### How can I prevent the newline character at the end of each print() statement?
You can set the end parameter to an empty string:
for i in range(10):
print(i, end="")
### How can I print a tab-separated list of numbers?
You can use the sep parameter with a tab character (\t):
numbers = [1, 2, 3]
print(*numbers, sep="\t")
### How can I print a string multiple times?
You can use the * operator to repeat the string:
message = "Hello"
print(message * 5) # prints HelloHelloHelloHelloHello
### How can I print a table with headers and rows?
You can create a list of lists, where each inner list represents a row, and use nested loops to iterate through the data and print it in a tabular format:
data = [["Name", "Age", "BMI"], ["John", 25, 23.4], ["Sarah", 30, 21.2]]
for row in data:
print(*row)
Output:
Name Age BMI
John 25 23.4
Sarah 30 21.2