B2.1.1Construct and trace programs using a range of global and local variables of various data types
0/11
B2.1 Programming fundamentalsB2.1.1

Construct and trace programs using a range of global and local variables of various data types

Construct and trace programs using a range of global and local variables of various data types

SL + HL≈ 60 minCommand term: ConstructFree lesson

In this lesson

  • Declaring and assigning variables of the types Boolean, char, decimal (float/double), integer and String in Java and Python
  • Choosing a suitable data type for a piece of data
  • Explaining the scope of global and local variables
  • Tracing programs that use global and local variables

LearnVariables

In this unit every program is shown in Java and in Python. Choose your language with the switch above any program; your choice is remembered.

    0 of 4

    CodeVariables of five data types

    students = 28
    price = 7.99
    isOpen = True
    grade = "B"
    city = "Stuttgart"
    print(students, price, isOpen, grade, city)
    Output
    28 7.99 True B Stuttgart

    Java prints true; Python prints True. Python has no separate char type: a single character is a string of length 1.

    LearnData types

    TypeStoresJavaPythonExamples
    BooleanOne of two values: true or falseboolean done = false;done = Falsetrue/false, True/False
    CharA single characterchar c = 'a'; (single quotes)No char type: c = "a"J, q, 4, %
    DecimalA number with a fractional partdouble d = 7.99; (or float f = 7.99f;)d = 7.99 (type float)1.5, −594.39
    IntegerA whole numberint i = 0;i = 0 (type int)29399, 4, −2992
    StringA sequence of charactersString s = "hello";s = "hello" (type str)Hello, 45 Main Street

    In Java, double is the usual decimal type; a float literal needs an f suffix (7.99f). Python can show the intended type with a type hint, e.g. price: float = 7.99, but does not enforce it.

    CheckChoose the data type

    A library system stores these items. Which data type suits each one best?

    1. The number of books a member has borrowed
    2. The fine owed, in euros, e.g. 1.50
    3. Whether a book is overdue
    4. The shelf section, a single letter from A to H
    5. A member’s phone number, e.g. 0711 2045 88
    6. The title of a book

    LearnPrimitive types, objects and conversion

      0 of 3

      CodeDivision and conversion

      a = 7
      b = 2
      print(a / b)
      print(a // b)
      print(a % b)
      d = 7.9
      print(int(d))
      print(int("42") + 1)
      Output
      3.5
      3
      1
      7
      43

      Compare the outputs in both languages with the switch: the first line differs because of integer division in Java.

      CheckQuick check

      In Java, int total = 17; and int count = 4;. What is the value of total / count?

      LearnGlobal and local variables

        0 of 7

        LabWatch global and local variables

        Step through the program. The Variables panel groups the variables by scope: the global ones, and the local variables of each function or method that is running (in Java this includes main).

        count = 0
        def addPoints(points):
        global count
        bonus = points * 2
        count = count + bonus
        return bonus
        earned = addPoints(5)
        earned = addPoints(3)
        print(count, earned)
        Variables

        Press Start. The highlighted line is the next one to run.

        Output

        Click a line number to set or remove a breakpoint. “Step over” runs a whole function call in one go; “Step out” finishes the current function.

        When the program has finished, bonus is not listed. Why?

        Run the program to the end and answer the question to complete this activity.

        CheckQuick check

        In the Python version of the program above, the line global count is deleted. What happens when addPoints(5) is called?

        CheckQuick check

        In Java, for (int i = 0; i < 3; i++) { ... } is followed by System.out.println(i);. What happens?

        CodeA local variable with the same name

        level = 1
        def play():
        level = 5
        print("inside:", level)
        play()
        print("outside:", level)
        Output
        inside: 5
        outside: 1

        play creates its own local level; the global level is still 1 afterwards.

        CodeA program to trace

        total = 0
        n = 1
        while n < 10:
        total = total + n
        n = n * 2
        print(total, n)

        CheckTrace the program

        Complete the trace table for the program above: one row for each time round the loop, then the output.

        Iterationtotaln
        Start01
        1
        2
        3
        4

        Output:

        ExamWorked exam answer

        Trace the program below. Identify its global and local variables and state its output.

        [4]
        rate = 2
        def convert(amount):
        result = amount * rate
        return result
        first = convert(3)
        second = convert(5)
        print(first + second)
          Try writing your own answer first.

          ReviewMistakes examiners see

          Misconception

          Using = to compare values. = assigns; == compares.

          Misconception

          Forgetting that Java’s int / int is integer division: 5 / 2 is 2.

          Misconception

          Storing phone numbers or postcodes as integers. Data that is not used in arithmetic, or may start with 0, is a string.

          Misconception

          Assuming a local variable keeps its value between calls. It is created again on every call.

          Exam tip

          In a trace table, give each variable its own column and record its value every time it changes.

          Exam practiceExam-style questions

          6 questions · 15 marks. Answer each one first, then mark it yourself against the markscheme. Your answers are saved in this browser only.

          Scenario

          A cinema uses a program to work out ticket prices. Each ticket costs 9.50 and members get a discount. The program stores the customer’s name, the number of tickets, whether the customer is a member, the row letter of the seats and the total cost.

          (a)Identify · AO2[3]

          Identify the most suitable data type for each of: the row letter of the seats, the total cost, the number of seats still free in the screen.

          (b)State · AO1[1]

          State the output of the program below.

          discount = 0.2
          def ticketCost(tickets, member):
          price = tickets * 9.5
          if member:
          price = price - price * discount
          return price
          cost = ticketCost(4, True)
          print(cost)
          (c)Identify · AO2[2]

          Identify one global variable and one local variable in the program in part (b).

          (d)Explain · AO3[2]

          In the program in part (b), the price of a ticket, 9.5, is written directly inside ticketCost. Explain one advantage of storing it in a global variable named ticketPrice instead.

          (e)Explain · AO3[3]

          A programmer adds the line discount = 0.5 (Python) or double discount = 0.5; (Java) as the first line inside ticketCost, and adds a last line to the program that outputs discount. State the two values the program now outputs, and explain the second one.

          (f)Construct · AO3[4]

          The cinema also sells popcorn at 4.25 per box. Construct a function (method) snackCost that takes the number of boxes and returns the total cost; if 3 or more boxes are bought, one box is free.

          0 / 15

          0 of 6 questions marked. Mark every question to see your total.

          Exam-style questions written for Praxis IB in the format of the 2027 specimen papers. They are not IB past-paper questions.