Print Single Variable
If you have a single variable, you can pass it to the print() function.
Visual Representation
Example
my_variable = "Hello AppDividend"
num_variable = 13
print(my_variable)
print(num_variable)
Output
Hello AppDividend
13
Print Multiple Variables
Here are following ways to print multiple variables:
- Using print()
- Using f-strings
- Using format() method
- Using % formatting
Method 1: Using print()
If you have multiple variables, you can pass them all to print() function, separated by commas.
Visual Representation
Example
my_variable = "Hello AppDividend"
num_variable = 13
# separated by a space (default behavior)
print(my_variable, num_variable)
# separated by a comma
print(my_variable, num_variable,sep=',')
Output
Hello AppDividend 13
Hello AppDividend,13
Method 2: Using f-strings
You can easily print multiple variables in a single statement by using an f-strings, which allows for easy and readable string formatting.
The curly braces {} are used to insert the variables values into the string.
Visual Representation
Example
my_variable = "Hello AppDividend"
num_variable = 13
# Using an f-string
print(f"My first variable is: {my_variable}, and my second variable is: {num_variable}")
Output
My first variable is: Hello AppDividend, and my second variable is: 13
Method 3: Using format() method
The str.format() method is useful for formatting strings, especially when you want to insert variable values into a string template.
Visual Representation
Example
my_variable = "Hello AppDividend"
num_variable = 13
print("My first variable is: {}, and my second variable is: {}".format(my_variable, num_variable))
Output
My first variable is: Hello AppDividend, and my second variable is: 13
Method 4: Using % formatting
The % formatting method is an older way but still valid way to format strings.
Example
my_variable = "Hello AppDividend"
num_variable = 13
print("My first variable is: %s, and my second variable is: %d" % (my_variable, num_variable))
Output
My first variable is: Hello AppDividend, and my second variable is: 13
In above example, %s is a placeholder for a string and %d is a placeholder for an integer.
University of American Samoa Press
One of the very few useful python tutorials out there!