Variables in Expressions

Code Examples

Example 1

Basic arithmetic operations. Variables can be used in any arithmetic operation. The values stored in x and y are used in the calculations. The results are stored in new variables.

x = 10
y = 5

sum_result = x + y        # 15
difference = x - y        # 5
product = x * y           # 50
quotient = x / y          # 2.0 (division always returns float)
integer_division = x // y # 2 (floor division returns integer)
remainder = x % y         # 0 (modulo - remainder after division)
power = x ** y            # 100000 (exponentiation: 10^5)

Example 2

Complex calculations. Variables make complex formulas readable. Parentheses control the order of operations (PEMDAS). This makes mathematical calculations intuitive.

length = 10
width = 5
height = 2

area = length * width               # 50
volume = length * width * height    # 100
perimeter = 2 * (length + width)    # 30

# Using parentheses to control order of operations
result = (length + width) * height  # 30

Example 3

String concatenation. The + operator joins strings together. Variables containing strings can be combined with string literals.

first_name = "John"
last_name = "Doe"

full_name = first_name + " " + last_name  # "John Doe"
greeting = "Hello, " + full_name + "!"    # "Hello, John Doe!"

Example 4

String repetition. The * operator repeats a string multiple times. Useful for creating patterns or padding.

symbol = "*"
line = symbol * 10  # "**********"

word = "python"
repeated = word * 3  # "pythonpythonpython"

Example 5

Numeric comparisons. Comparison operators (>, <, >=, <=, ==, !=) compare values. Results are boolean values (True or False). Used in conditional statements to make decisions.

age = 25
voting_age = 18

can_vote = age >= voting_age                 # True 
is_teenager = age >= 13 and age <= 19        # False
is_senior_citizen = age >= 65                # False