Variables Jump to this section

Variables let you store values (like numbers or text) so your program can use them later.

Basic Idea Jump to this section

  • Assign a value to a variable using =.
  • Use the variable name to use the value later.

Example:

message = "Hello, world!"
print(message)

Output: Hello, world!

Python reads the code top to bottom, one line at a time.

Naming Rules Jump to this section

Allowed

  • user_name
  • age1
  • total_score

Not allowed

  • 1name (cannot start with a number)
  • user name (no spaces)
  • if, for, class (reserved keywords)

Variable names are case-sensitive: age and Age are different.

Common Data Types Jump to this section

Variables can store different kinds of information. Here are the most common:

  • Integers (whole numbers): x = 10
  • Floats (decimal numbers): pi = 3.14
  • Strings (text): name = "John"
  • Booleans (True/False): is_available = True

Make sure to always capitalize the first letter of a boolean (use True and False, you will get an error if you use true/false)


age = 21            # integer
country = "Canada"  # string

The hash symbol # starts a comment. All text following the # to the end of the line is a comment and does not get run as code. Comments are used to help explain code.


Reassigning and Updating Jump to this section

You can change a variable by assigning a new value.

var = "value"
var = "new value"
score = 10
bonus = 5
score = score + bonus        # score is now 15

You can change the type by assigning a different kind of value

value = 5
value = "five"              # now `value` is a string

Changing a variable’s type is allowed, but usually not recommended since it can make programs harder to read/debug.


User Input Jump to this section

Use input() to prompt the user to enter an input. You will have to type the response in the terminal where the output appears.

name = input("What's your name? ")

print("Your name is " + name)

input() always returns a string, even if the user types a number. Convert it if you need to do any math.


F-Strings Jump to this section

F-strings are a way to simplify combining text and variables when using print(). Start the string with f and put expressions in {}.

name = "John"
age = 30
print(f"My name is {name} and I am {age} years old")

F-strings avoid manual string conversion and are easier to read.

# without f-strings
print("My name is " + name + " and I am " + str(age) + " years old")

# with f-strings
print(f"My name is {name} and I am {age} years old")

Anything inside {} is evaluated as Python code, so you can include expressions:

print(f"Next year I will be {age + 1}")

You can control how values look by adding a format after a colon : inside the braces.

pi = 3.14159265
print(f"Pi approx: {pi:.2f}")   # round to 2 decimal places

If you need to show braces in the output (for example in math or templates), double them:

print(f"Use false to show braces")  # output: Use { and } to show braces

Math with variables Jump to this section

You can perform arithmetic using variables that hold numbers (integers and floats). The basic operators are:

  • + addition
  • - subtraction
  • * multiplication
  • / division (always returns a float)

There are also more specialized operators:

  • // floor division (returns the quotient without the remainder)
  • % modulus (remainder after division)
  • ** exponentiation (raise to a power)

Examples:

a = 7
b = 3
print(a + b)    # 10
print(a - b)    # 4
print(a * b)    # 21
print(a / b)    # 2.3333333333333335  (float)
print(a // b)   # 2                  (floor division)
print(a % b)    # 1                  (remainder)
print(a ** b)   # 343                (7 to the power of 3)

Order of operations follows normal math rules: parentheses first, then **, then *, /, //, %, then + and -.

result = 2 + 3 * (4 ** 2)  # 2 + 3 * 16 = 50

Notes:

  • Strings are not numeric, but you can use + to join them and * to repeat them:
name = "John"
greeting = "Hello, " + name    # greeting is now "Hello, John"
repeat = "ha" * 3                # "hahaha"
  • Booleans behave like numbers in arithmetic (True == 1, False == 0) but use them carefully for clarity.

Augmented assignment combines operations to simplify math:

  • += add and assign
  • -= subtract and assign
  • *= multiply and assign

Instead of counter = counter + 1, you can simplify it to counter += 1

counter = 0
counter += 1   # counter is 1

count = 5
count -= 1     

Same as count = count - 1, count is 4


value = 4
value *= 3

Same as value = value * 3, value is 12


Multiple Assignment and Swapping Jump to this section

Assign multiple variables on one line, or swap values quickly:

x, y = 5, 10

# swap
x, y = y, x

# multiple assignment
first, second, third = "a", "b", "c"

Types and Conversion Jump to this section

Use type() to check a variable's type. Convert between types with int(), float(), str():

number_string = "42"   # currently, the type is string
number = int(number_string)     # converts to integer '42'
print(type(number))       # output: <class 'int'>

price = 4.5            # currently a float
print(int(price))      # prints 4 (drops decimal part)

Be careful: converting invalid strings raises an error (you can't convert "hello" to an integer).


Constants (convention) Jump to this section

A constant is a variable whose value cannot be changed. Python has no true constants, but by convention use ALL_CAPS for values you don't plan to change:

PI = 3.14159
MAX_USERS = 100

Challenge Jump to this section

Write a short program that:

  1. Asks the user (using input()) for the width and height of a rectangle.
  2. Converts the inputs to numbers.
  3. Calculates the area and prints a friendly message like: "The area is 24".

If you run into problems, remember that the error message can contain helpful information.


Hint: Input

input() returns a string, convert it with int() or float().

Hint: Area

Multiply width by height to get the area.

Hint: Output

With print(), you can use a comma to combine parts: print("Your name is", user_name)


Show example solution
width = float(input("Width: "))
height = float(input("Height: "))
area = width * height
print("The area is", area)

Optional extra: round the answer with round(area, 2) to show two decimals.


Key Takeaways Jump to this section

  • Variables store values for later use
  • Use = to assign values
  • input() gathers user input & returns a string
  • Convert types before doing math