How to use print() function in Python if statements?

PythonPythonBeginner
Practice Now

Introduction

In this tutorial, we will dive into the world of the print() function in Python, specifically focusing on how to use it within if statements. We will cover the fundamentals of the print() function, understand the role of conditional statements, and explore various formatting techniques to enhance the output. By the end of this guide, you will have a solid grasp of leveraging the print() function to streamline your Python programming.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/conditional_statements("`Conditional Statements`") subgraph Lab Skills python/comments -.-> lab-415792{{"`How to use print() function in Python if statements?`"}} python/strings -.-> lab-415792{{"`How to use print() function in Python if statements?`"}} python/type_conversion -.-> lab-415792{{"`How to use print() function in Python if statements?`"}} python/conditional_statements -.-> lab-415792{{"`How to use print() function in Python if statements?`"}} end

Understanding the print() Function

The print() function in Python is a built-in function that is used to display output to the console or terminal. It is one of the most fundamental and commonly used functions in Python programming. The print() function can be used to display various types of data, including strings, numbers, and variables.

Basic Usage of print()

The basic syntax of the print() function is as follows:

print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False)
  • value1, value2, etc. are the values you want to print, separated by commas.
  • sep is the separator character used between the values, with a default of a space character (' ').
  • end is the character or string used to terminate the printed line, with a default of a newline character ('\n').
  • file is the output stream where the printed values will be written, with a default of the standard output (sys.stdout).
  • flush is a boolean value that determines whether the output is flushed (forced to be written to the buffer) immediately, with a default of False.

Here's a simple example of using the print() function:

name = "LabEx"
age = 25
print("My name is", name, "and I am", age, "years old.")

Output:

My name is LabEx and I am 25 years old.

In this example, the print() function is used to display a message that includes the values of the name and age variables.

Formatting print() Output

The print() function also provides several ways to format the output, such as using string formatting and f-strings. These methods allow you to insert values into a string in a more readable and structured way.

Here's an example using string formatting:

name = "LabEx"
age = 25
print("My name is %s and I am %d years old." % (name, age))

Output:

My name is LabEx and I am 25 years old.

And here's an example using f-strings (introduced in Python 3.6):

name = "LabEx"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:

My name is LabEx and I am 25 years old.

Both of these methods allow you to insert values into a string in a more readable and structured way, making your code more maintainable and easier to understand.

Conditional Statements and print()

Conditional statements, such as if, elif, and else, are used in Python to execute different blocks of code based on certain conditions. The print() function can be used within these conditional statements to display output based on the evaluated conditions.

Using print() in if Statements

The basic structure of using print() in an if statement is as follows:

if condition:
    print("Condition is True")
else:
    print("Condition is False")

Here's a more detailed example:

age = 18
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are an adult.

In this example, the print() function is used to display different messages based on the value of the age variable.

Using print() with elif Statements

You can also use print() within elif statements to handle multiple conditions:

score = 85
if score >= 90:
    print("You got an A.")
elif score >= 80:
    print("You got a B.")
elif score >= 70:
    print("You got a C.")
else:
    print("You failed.")

Output:

You got a B.

In this example, the print() function is used to display different messages based on the value of the score variable.

Combining print() with Formatted Strings

You can also use formatted strings (such as f-strings) within conditional statements to display dynamic output:

name = "LabEx"
age = 25
if age >= 18:
    print(f"{name} is an adult and {age} years old.")
else:
    print(f"{name} is a minor.")

Output:

LabEx is an adult and 25 years old.

In this example, the print() function is used with an f-string to display a message that includes the values of the name and age variables.

By using print() within conditional statements, you can create dynamic and responsive output in your Python programs.

Formatting print() Output

The print() function in Python provides several ways to format the output, making it more readable and organized. These formatting techniques can be particularly useful when working with conditional statements and displaying dynamic data.

Using String Formatting

One way to format the output of the print() function is by using string formatting. Python supports several string formatting methods, including the classic % operator, the format() method, and f-strings (introduced in Python 3.6).

Here's an example using the % operator:

name = "LabEx"
age = 25
print("My name is %s and I am %d years old." % (name, age))

Output:

My name is LabEx and I am 25 years old.

And here's an example using the format() method:

name = "LabEx"
age = 25
print("My name is {} and I am {} years old.".format(name, age))

Output:

My name is LabEx and I am 25 years old.

Finally, here's an example using f-strings:

name = "LabEx"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:

My name is LabEx and I am 25 years old.

All of these methods allow you to insert values into a string in a more readable and structured way, making your code more maintainable and easier to understand.

Aligning and Padding Output

You can also use the print() function to align and pad the output, making it more visually appealing. This can be particularly useful when displaying tabular data or when you need to ensure that the output is consistently formatted.

Here's an example of right-aligning and padding the output:

name = "LabEx"
age = 25
print(f"{name:>20} is {age:>3} years old.")

Output:

                LabEx is  25 years old.

In this example, the name is right-aligned within a 20-character field, and the age is right-aligned within a 3-character field.

You can also use the < and ^ alignment specifiers to left-align and center-align the output, respectively.

Controlling Spacing and Newlines

The print() function also allows you to control the spacing and newlines in the output. You can use the sep and end parameters to customize the behavior.

Here's an example of using sep to change the separator between values:

name = "LabEx"
age = 25
print(name, age, sep=", ")

Output:

LabEx, 25

And here's an example of using end to change the character that terminates the printed line:

print("Hello", end="")
print("World")

Output:

HelloWorld

By mastering these formatting techniques, you can create more readable and visually appealing output in your Python programs, especially when working with conditional statements and dynamic data.

Summary

This Python tutorial has provided a comprehensive overview of using the print() function within if statements. You have learned how to effectively leverage the print() function to display output based on conditional logic, as well as how to format the output to make it more readable and informative. With these skills, you can now confidently incorporate the print() function into your Python programs, enhancing your ability to communicate and debug your code.

Other Python Tutorials you may like