Skip to content
Laviyx Learn

Try

Python Variables Practice

Practise creating, updating and printing variables, and converting between types.

Beginner3 problemsUpdated

Review first: Variables, Data Types

  1. 1.Rectangle area

    Beginner

    Store a rectangle's width (8) and height (5) in variables, calculate the area and perimeter, and print Area: 40, Perimeter: 26.

    Show hint

    Area is width * height; perimeter is 2 * (width + height). Use an f-string.

    Show solution
    Python
    width = 8
    height = 5
    
    area = width * height
    perimeter = 2 * (width + height)
    
    print(f"Area: {area}, Perimeter: {perimeter}")
    Output
    Area: 40, Perimeter: 26
  2. 2.Swap two values

    Beginner

    Given left = "tea" and right = "coffee", swap the values so that printing them shows coffee tea. Do it in one line, without a third variable.

    Show hint

    Python can assign two variables at once with tuple unpacking.

    Show solution
    Python
    left = "tea"
    right = "coffee"
    
    left, right = right, left
    
    print(left, right)
    Output
    coffee tea
  3. 3.Age in ten years

    Beginner

    A variable holds an age as text, age_text = "27". Print In 10 years you will be 37.

    Starter code (Python)
    age_text = "27"
    # your code here
    Show hint

    Convert the text to a number with int() before adding.

    Show solution
    Python
    age_text = "27"
    age = int(age_text)
    
    print(f"In 10 years you will be {age + 10}")
    Output
    In 10 years you will be 37

    age_text + 10 would raise a TypeError because you cannot add a string and an integer. Values read from files, forms and input() are always text, so this conversion is something you will do constantly.