By reading this article your following problems will be answered.
How to use variables in Python.
How to define variables in Python.
How to assign values to variables in Python.
How to combine variables in Python.
Using variables in Python
- In Python, a variable can be defined as following.
name = “Content”
- In above code ‘name’ is the variable (or the name of the variable) and ‘Content’ is the content of the particular variable.
Numbers in variables in Python
- Numbers can be assigned to variables in Python as following.
number = 3
- Also we can add numbers which are stored in variables as following.
- Use of any mathematical operator (+, -, *, /) is possible to calculate numbers stored variables.
number_a = 10
number_b = 2
print(number_a + number_b)
print(number_a * number_b)
print(number_a - number_b)
print(number_a / number_b)
Combining variables in Python
- In Python, two variables can be combined by adding ‘+’ or ‘,’ in between them.
1. name = “Python”
2. type = “Language”
3. print(name + type)
4. print(name, type)
- Line 3 output will be “PythonLanguage“.
- Line 4 output will be “Python Language“.
- To add a space between two text variables, we can use ‘comma (,)’ between them (Refer code 4 above) or we can do as in the following example.
print(name + “ ” + type)
- To combine variables that contain different data types it is required to use ‘,’ between them.
- As an example, to combine different variable that contains a text and and numbers, it is required to use ‘,’ between them.
- If you use ‘+’ symbol to combine variables that contain different data types, it will result an error.
currency = “LKR”
amount = 100
print(currency, amount)
print(“Total is”, amount, currency)