Table of Contents | |
Python print()
Function
Think of the Python print() function as your program’s way of communicating with you, the user. It’s like a display window where you can show text messages, the current value of variables, or the results of calculations. The Print function takes what you tell it and sends it directly to the screen, making it useful for understanding how your program works and sharing information as it runs. Here’s an example:
Python print()
Example (Python 3)
# Print a greeting
print("Hello, Python!")
# Print a variable's value with a label
name = "Mark"
print(f"His name is: {name}")
Code Explanation
- Line 2: Prints the message “Hello, Python!”.
- Line 5: Assigns the string “Mark” to the variable
name
. - Line 6: Uses an f-string to print a label “His name is:” followed by the value stored in the variable
name
.
Output
Hello, Python!
His name is: Mark
Python print()
Syntax (Python 3)
print(*objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
- objects (required): The data to print (strings, numbers, variables, etc.). Separate multiple objects with commas.
- sep=’ ‘ (optional): Separator between objects (defaults to space).
- end=’\n’ (optional): String printed at the end (defaults to newline).
- file=sys.stdout (optional): Output destination (defaults to console).
- flush=False (optional): Controls output buffering (defaults to not flushing immediately).
Single Quotes
Single quotes ('
) are similar to double quotes in Python, letting you create text strings. They’re particularly useful when your text contains double quotes you want to display or if you need to include a single quote character within the string.
Example
# Print a message containing double quotes using single quotes
message = 'This string says "Hello, world!"'
print(message)
Code Explanation
- Line 2: Assigns the text ‘This string says “Hello, world!”‘ (including the double quotes within single quotes) to the variable
message
. Here, the single quotes allow the double quotes within the message to be displayed literally. - Line 3: Prints the contents of the
message
variable usingprint()
.
Output
This string says “Hello, world!”
Double Quotes
Double quotes ("
) are the most common way to wrap text you want to display in Python. They allow you to include various characters, spaces, and even special symbols within your string.
Example
# Print a greeting with double quotes
message = "Hello, world! This is a string with double quotes."
print(message)
Code Explanation
- Line 2: Assigns the text “Hello, world! This is a string with double quotes.” (including the quotes themselves) to the variable
message
. - Line 3: Prints the contents of the
message
variable usingprint()
.
Output
Hello, world! This is a string with double quotes.
Triple Quotes (Multiline Strings)
Triple quotes ("""
or '''
) are for multi-line strings or including code snippets within your Python code. They offer more flexibility compared to single or double quotes.
Example
# Print a multi-line poem using triple quotes
poem = """Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky."""
print(poem)
Code Explanation
- Line 2: Assigns a poem using triple-double quotes (
""
) to the variablepoem
. Notice how the newlines and formatting are preserved within the string. - Line 6: Prints the contents of the
poem
variable usingprint()
. The poem will be displayed with its original line breaks.
Output
Twinkle, twinkle, little star,
How I wonder what you are!
Up above the world so high,
Like a diamond in the sky.
Printing Strings
Displaying text on the screen is a breeze using the Python print() function. You can use it to print simple strings or even combine them with variables.
Example
# Print a string and a variable's value
greeting = "Hi there!"
name = "Mark"
print(greeting, name) # You can separate objects with commas
Code Explanation
- Line 2: Assigns the string “Hi there!” to the variable
greeting
. - Line 3: Assigns the string “Mark” to the variable
name
. - Line 4: Uses
print()
to display both thegreeting
and the value stored inname
separated by a space (the default separator).
Output
Hi there! Mark
String Concatenation
Imagine you have messages or bits of text you want to combine. String concatenation in Python allows you to combine multiple strings into one. The + operator acts like glue, merging the strings.
Example
# Create a full name by combining strings
first_name = "Bob"
last_name = "Smith"
full_name = first_name + " " + last_name # Add a space in between
print(full_name)
Code Explanation
- Line 2: Assigns the string “Bob” to the variable
first_name
. - Line 3: Assigns the string “Smith” to the variable
last_name
. - Line 4: Creates a new string
full_name
by concatenatingfirst_name
, a space, andlast_name
using the+
operator. - Line 5: Prints the value of
full_name
, which is “Bob Smith”.
Output
Bob Smith
Printing Variables
In Python, variables act like containers containing information you can use throughout your program. The print() function is your bridge to displaying the values stored in these variables.
Example
# Print the value stored in a variable
age = 30
print(age) # Print the variable directly
Code Explanation
- Line 2: Assigns the number 30 to the variable
age
. - Line 3: Uses
print()
to display the value stored in the variableage
.
Formatted Output with f-strings
F-strings (formatted string literals) are a modern and convenient way to create formatted output in Python. They’re like magic boxes where you can embed variables and expressions directly within a string.
Syntax
f’text {expression} more text’
The f
before the quote tells Python, it’s a formatted string.
expression: The variable or calculation you want to include in the formatted string.
Example
# Use an f-string to format a greeting
name = "Charlie"
age = 37
print(f"Hello, {name}! You are {age} years old.")
Code Explanation
- Line 2: Assigns the string “Charlie” to the variable
name
. - Line 3: Assigns the number 37 to the variable
age
. - Line 4: Uses an f-string to create a formatted message. The curly braces
{}
act as placeholders where the values ofname
andage
are inserted directly into the string.
Output
Hello, Charlie! You are 37 years old.
Printing Integers
Printing integers is straightforward. Integers are whole numbers (like 1, -10, or 42). You use the familiar Python print() function to display an integer’s value.
Example
# Print an integer
age = 25
print(age)
Code Explanation
- Line 2: Assigns the integer 25 to the variable
age
. - Line 3: Uses
print()
to display the value stored in the variableage
.
Printing Floats
Python makes printing float values (numbers with decimals) just as easy as printing whole numbers. Floats are useful for representing quantities that aren’t whole, such as distances, temperatures, or prices. You use the friendly print() function to display them.
Example
# Print a float
height = 175.3 # A floating-point number with a decimal
print(height)
Code Explanation
- Line 2: Assigns the floating-point value 175.3 to the variable
height
. - Line 3: Uses
print()
to display the value stored in the variableheight
.
Printing Multiple Objects
Imagine you want to display more than one piece of information at a time in Python. The print() function is handy for printing multiple objects, like strings, variables, or calculations.
Example
# Print a name, age, and greeting
name = "David"
age = 40
greeting = "Hello!"
print(name, age, greeting) # Notice commas separate each object
Code Explanation
- Line 2: Assigns the string “David” to the variable
name
. - Line 3: Assigns the integer 40 to the variable
age
. - Line 4: Assigns the string “Hello!” to the variable
greeting
. - Line 5: Uses
print()
to display the values ofname
,age
, andgreeting
separated by spaces (the default separator).
Output
David 40 Hello!
Preventing Line Breaks
In Python, the print() function usually adds a newline character at the end, moving the cursor to the next line. But what if you want to print things on the same line? You can prevent this line break using the end argument within print().
Example
# Print a message without a newline at the end
message = "Printing on the same line"
print(message, end='') # Notice end='' to suppress newline
print(" done.") # This will print on a new line (default behavior)
Code Explanation
- Line 2: Assigns the string “Printing on the same line” to the variable
message
. - Line 3: Uses
print(message, end='')
to display the contents ofmessage
and setend
to an empty string ”, preventing the automatic newline. - Line 4: Prints ” done.” with the default newline behavior, moving the cursor to the next line.
Output
Printing on the same line done.
Printing to a File
By default, the print() function displays output on the console screen. But Python allows you to redirect this output to a file, creating a permanent record of your information. Here’s a simplified way to think about it:
- You’re opening a file for writing (like opening a notebook to write in).
- You’re using print() to write the data to the opened file (like writing your message in the notebook).
- You’re closing the file (like closing your notebook to save your work).
Example
# Write a message to a file
with open("my_message.txt", "w") as file: # Open for writing ("w")
print("This message is written to a file.", file=file)
print("This message is still printed to the console.") # Default behavior
Code Explanation
- Line 2: Opens a file named “my_message.txt” in write mode (“w”) and assigns it to the variable
file
. Thewith
statement ensures the file is closed properly. - Line 3: Uses
print()
withfile=file
to write the message “This message is written to a file.” to the opened filefile
. - Line 4: Prints “This message is still printed to the console.” using the default behavior, which displays output on the screen.