Variables and Calculations
Learn to store and manipulate data with variables. Master arithmetic operations and type conversion.
Learning Objectives:
- β’Declare and use variables of different types
- β’Perform arithmetic operations and understand operator precedence
- β’Work with integers, floats, and strings
- β’Apply type conversion to solve real-world problems
Variables and Calculations
What is a Variable?
A variable is a named container that stores a value. Think of it as a labeled box where you can put data and retrieve it later.
Instead of hardcoding values like 5 or "Alice" directly in your code, you store them in variables:
pythonage = 25 name = "Alice" price = 19.99
Variables have names (like age) and values (like 25).
Declaring Variables in Different Languages
The syntax varies, but the concept is the same:
Python:
pythonage = 25 name = "Alice" pi = 3.14 is_student = True
C:
cint age = 25; char name[] = "Alice"; float pi = 3.14;
Java:
javaint age = 25; String name = "Alice"; double pi = 3.14; boolean is_student = true;
JavaScript:
javascriptlet age = 25; let name = "Alice"; let pi = 3.14; let is_student = true;
Data Types
Different languages support different data types. Here are the most common:
| Type | Description | Examples |
|------|-------------|----------|
| int (integer) | Whole numbers | 42, -5, 0 |
| float/double (decimal) | Numbers with decimals | 3.14, -0.5, 2.0 |
| string | Text | "Hello", "Alice" |
| bool (boolean) | True or False | True, False |
Integer vs. Float
Integer (whole numbers):
pythoncount = 10 age = 25
Float (decimal numbers):
pythonprice = 19.99 temperature = -3.5 pi = 3.14159
Reassigning Variables
You can change a variable's value by assigning a new value to it:
pythonx = 10 print(x) # Outputs: 10 x = 20 print(x) # Outputs: 20 x = x + 5 print(x) # Outputs: 25
Arithmetic Operations
Once you have variables, you can perform calculations with them.
Basic Operations
| Operator | Name | Example |
|----------|------|---------|
| + | Addition | 5 + 3 β 8 |
| - | Subtraction | 10 - 4 β 6 |
| * | Multiplication | 3 * 7 β 21 |
| / | Division | 15 / 3 β 5.0 |
| // | Floor Division | 15 // 4 β 3 |
| % | Modulo (remainder) | 17 % 5 β 2 |
| ** or ^ | Exponentiation | 2 ** 3 β 8 |
Examples
python# Addition and subtraction total = 100 + 50 result = total - 30 print(result) # Outputs: 120 # Multiplication and division area = 5 * 4 price_per_unit = 100 / 4 print(price_per_unit) # Outputs: 25.0 # Modulo (useful for checking if a number is even or odd) remainder = 17 % 5 print(remainder) # Outputs: 2
C:
c#include <stdio.h> int main() { int a = 10; int b = 3; printf("a + b = %d\n", a + b); // 13 printf("a - b = %d\n", a - b); // 7 printf("a * b = %d\n", a * b); // 30 printf("a / b = %d\n", a / b); // 3 printf("a %% b = %d\n", a % b); // 1 return 0; }
Operator Precedence
When you combine multiple operations, the order matters. Operators follow a precedence (priority):
- Exponentiation (
**,^) - Multiplication, Division, Modulo (
*,/,//,%) - Addition, Subtraction (
+,-)
Operations of the same precedence are evaluated left to right.
Examples
python# Without parentheses: multiplication happens first result = 2 + 3 * 4 print(result) # Outputs: 14 (not 20) # Because 3 * 4 = 12, then 2 + 12 = 14 # With parentheses: changes the order result = (2 + 3) * 4 print(result) # Outputs: 20
Rule of thumb: Use parentheses to make your intentions clear!
python# Clear and unambiguous total_cost = (price * quantity) + tax discount_price = (original_price * (1 - discount_rate))
Type Conversion
Sometimes you need to convert a value from one type to another.
String to Number
When you read input from the user, it's always a string. To do math, convert it to a number:
Python:
pythonuser_input = input("Enter a number: ") number = int(user_input) # Convert string to integer result = number + 10 print(result)
Java:
javaString user_input = "42"; int number = Integer.parseInt(user_input); // String β int double value = Double.parseDouble(user_input); // String β double
C:
cchar input[10]; int number; scanf("%s", input); number = atoi(input); // String β integer
Number to String
Sometimes you need to convert numbers to strings for display:
Python:
pythonage = 25 message = "I am " + str(age) + " years old" print(message) # Outputs: I am 25 years old
Java:
javaint age = 25; String message = "I am " + age + " years old"; // Auto-conversion System.out.println(message);
Real-World Example: Currency Conversion
Let's apply what we've learned to a practical problem.
Problem: Convert US dollars to euros, given an exchange rate.
Python:
python# Given values dollars = 100 exchange_rate = 0.92 # 1 USD = 0.92 EUR # Calculate euros = dollars * exchange_rate # Display result print(f"${dollars} USD = β¬{euros:.2f} EUR") # Output: $100 USD = β¬92.00 EUR
Java:
javapublic class CurrencyConversion { public static void main(String[] args) { double dollars = 100; double exchange_rate = 0.92; double euros = dollars * exchange_rate; System.out.printf("$%.2f USD = β¬%.2f EUR\n", dollars, euros); // Output: $100.00 USD = β¬92.00 EUR } }
C:
c#include <stdio.h> int main() { double dollars = 100; double exchange_rate = 0.92; double euros = dollars * exchange_rate; printf("$%.2f USD = β¬%.2f EUR\n", dollars, euros); return 0; }
Key Takeaways
- Variables store data with a name and a value
- Types determine what kind of data a variable holds (int, float, string, bool)
- Arithmetic operations (+, -, *, /, //, %) let you perform calculations
- Operator precedence determines the order of evaluation
- Type conversion lets you change data between types
- Parentheses make complex expressions clear and correct
Summary
You've learned to work with variables and perform calculations. These are the building blocks of all programs. In the next chapter, you'll learn how to read input from the user β turning your static programs into interactive tools.
Progress: 3/8 chapters complete in Level 1
Exercises
Exercise 1: Declare Variables
Create variables and use their values in the requested output.
Exercise 2: Arithmetic Operations
Use arithmetic operators to calculate the requested results.
Exercise 3: Division and Modulo
Calculate the quotient and remainder of integer division.
Exercise 4: Swap Variables
Exchange the values stored in two variables.
Exercise 5: Complex Expression
Evaluate an arithmetic expression while respecting operator precedence.
Exercise 6: Currency Converter
Convert an amount from one currency to another using the rate specified in the exercise.