1.03

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
Prerequisites: [object Object]
Estimated Time: 50 min

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:

python
age = 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:

python
age = 25 name = "Alice" pi = 3.14 is_student = True

C:

c
int age = 25; char name[] = "Alice"; float pi = 3.14;

Java:

java
int age = 25; String name = "Alice"; double pi = 3.14; boolean is_student = true;

JavaScript:

javascript
let 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):

python
count = 10 age = 25

Float (decimal numbers):

python
price = 19.99 temperature = -3.5 pi = 3.14159

Reassigning Variables

You can change a variable's value by assigning a new value to it:

python
x = 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):

  1. Exponentiation (**, ^)
  2. Multiplication, Division, Modulo (*, /, //, %)
  3. 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:

python
user_input = input("Enter a number: ") number = int(user_input) # Convert string to integer result = number + 10 print(result)

Java:

java
String user_input = "42"; int number = Integer.parseInt(user_input); // String β†’ int double value = Double.parseDouble(user_input); // String β†’ double

C:

c
char 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:

python
age = 25 message = "I am " + str(age) + " years old" print(message) # Outputs: I am 25 years old

Java:

java
int 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:

java
public 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