Google News
logo
Python Program to Output both Text and a Variable
In the following example of Python program that demonstrates how to output both text and a variable :
Program :
# Creating a variable
name = "John"

# Outputting text and a variable
print("Hello, " + name + "!")
Output :
Hello, John!
In this program, we create a variable named name and assign it the value "John". We then use the print function to output a message that includes both text and the value of the name variable. The + operator is used to concatenate (join) the pieces of text and the variable into a single string.

When we run the program, it will output the message "Hello, John!" in the console. This is a common technique used in Python to output dynamic messages that include data stored in variables.

You can also use formatted string literals (f-strings) in Python 3.6 and later versions to output text and variables together in a simpler way.

Here's an example :
Program :
# Creating a variable
name = "John"

# Outputting text and a variable using an f-string
print(f"Hello, {name}!")
Output :
Hello, John!
In the above program, we use an f-string to include the value of the name variable inside the message. The f at the beginning of the string tells Python to look for variables or expressions enclosed in curly braces ({}) and replace them with their values.

This is a more concise and readable way to output dynamic messages that include variables.