Variables in Python can hold text and numbers. For example:
x = 2 price = 2.5 word = 'Hello'
The variable names are on the left and the values on the right. Once a variable is assigned, it can be used in other places of the program.
In the example above, we have three variables: x, price and word.
Text in variables
Text variables may be defined in 3 ways:
word = 'Hello' word = "Hello" word = '''Hello'''
The type depends on what you prefer.
Once defined variables can be replaced or modified:
x = 2 # increase x by one x = x + 1 # replace x x = 5
Python supports the operators +, -, / and * as well as brackets. Variables may be shown on the screen using the print statement.
x = 5 print(x) y = 3 * x print(y) # more detailed output print("x = " + str(x)) print("y = " + str(y))
The first output of the program above is simply the raw value of the variables. If you want to print a more detailed message like “x = 5”, use the line ‘print(“x = ” + str(x))’. This str() function converts the numeric variable to text.