Skip to content
aviral gupta

// B1.5 · ~30 min · Beginner

First program: variables, a while loop and a tip calculator

After this lesson you can write a program that asks for numbers, repeats steps with a while loop, and prints a neat result: a tip calculator you build in three steps.

Lesson 5 of 5 in B1 First steps

End of the module

You will be able to

  • Assign several variables in one line, and swap two values with a, b = b, a
  • Repeat code with a while loop, with an indented body and a condition that becomes false
  • Read numbers with float(input()), and keep printing on one line with end=
  1. Warm-up · Activity 1 of 7

    Warm-up from lesson B1.4: what does this print?

    nums = [1, 2, 3]
    nums.append(len(nums))
    print(nums)
  2. Predict · Activity 2 of 7

    Predict before you read on: this prints the Fibonacci numbers below 10. What appears?

    a, b = 0, 1
    while a < 10:
        print(a, end=" ")
        a, b = b, a + b
  3. Practice · Activity 3 of 7

    Fill in the comparison so that the countdown prints 3, 2 and 1, and stops before 0.

    count = 3
    while count ____ 0:
        print(count)
        count = count - 1
    while count 0:
  4. Practice · Activity 4 of 7

    What does this print?

    x, y = 1, 2
    x, y = y, x
    print(x, y)
  5. Practice · Activity 5 of 7

    Put the lines of a countdown program in order. It prints 3, 2, 1 and then Go!

    1. 1.print("Go!")
    2. 2. n = n - 1
    3. 3.n = 3
    4. 4. print(n)
    5. 5.while n > 0:
  6. Brain teaser · Activity 6 of 7

    Brain teaser. The user types 4.5 and presses Enter. What does the program print?

    price = input()
    print(price * 2)
  7. Apply · Activity 7 of 7

    Mini-task. Ask how much the user saves per week with float(input("Saved per week: ")). Starting from 0, add that amount once per week in a while loop until the savings reach at least 100, counting the weeks. Print Weeks: and the count. For 15 per week, it is 7.

    Check your work against this list

Build it yourself

Read the worked example, then write the exercises. Your code runs in your browser or on your computer and is never uploaded.

Worked example

A lily pad that doubles

A lily pad covers 1 % of a pond and doubles in size every day. How many days until the whole pond is covered? The while loop repeats the doubling as long as less than 100 % is covered, printing each day on one line. Multiple assignment updates the area and the day count together. Change the starting 1.0 to 5.0 and run it again.

main.py

# How many days until a doubling lily pad covers the pond?
covered, day = 1.0, 0  # percent of the pond, days passed

while covered < 100:
    print(covered, end=" ")
    covered, day = covered * 2, day + 1

print()
print("Full after", day, "days")

Run it with

python main.py

Output

1.0 2.0 4.0 8.0 16.0 32.0 64.0
Full after 7 days
  • end=" " keeps the numbers on one line; the empty print() then ends that line.
  • 64.0 is the last value printed: after doubling to 128.0, the condition is false.
  • The two indented lines are the body; the lines after the blank line run once, after the loop.
  • covered, day = covered * 2, day + 1 updates both in one step.
Change it and run it

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Exercises

Exercise 1 of 3

Tip calculator, step 1: a 15 % tip

The program reads the bill with input(). Turn it into a number with float(), then print the 15 % tip and the total, both rounded to 2 decimal places. For a bill of 40: Tip: 6.0 Total: 46.0 Use input() without a prompt text, so only these two lines are printed.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    input() gives a string. float(input()) gives a number you can calculate with.

  2. Hint 2

    15 % of the bill is bill * 0.15; round(value, 2) keeps two decimal places.

  3. Hint 3

    tip = round(bill * 0.15, 2), then print("Total:", round(bill + tip, 2)).

Show a solution

One way to solve it. Yours can look different and still pass the checks.

bill = float(input())

tip = round(bill * 0.15, 2)
print("Tip:", tip)
print("Total:", round(bill + tip, 2))
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

bill = input()

# Turn bill into a number, then print the 15 % tip and the total.
print("Tip:", bill)

test_main.py

from learnrun import run_main


def tip_for(bill):
    return run_main(f"{bill}\n").strip().splitlines()


def test_forty():
    """A bill of 40 gets a tip of 6.0"""
    got = tip_for(40)
    assert got == ["Tip: 6.0", "Total: 46.0"], f"for 40 the program printed {got!r}"


def test_hundred():
    """A bill of 100 gets a tip of 15.0"""
    got = tip_for(100)
    assert got == ["Tip: 15.0", "Total: 115.0"], f"for 100 the program printed {got!r}"


def test_decimals():
    """A bill of 12.4 gets a tip of 1.86"""
    got = tip_for(12.4)
    assert got == ["Tip: 1.86", "Total: 14.26"], f"for 12.4 the program printed {got!r}"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Exercise 2 of 3

Step 2: any tip, split between people

Now the program reads three lines: the bill, the tip in percent and the number of people. Print the tip, the total and what each person pays, all rounded to 2 decimal places. For 40, 15 and 4: Tip: 6.0 Total: 46.0 Each: 11.5

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    Each input() reads the next line, in order: bill, percent, people. Convert all three with float().

  2. Hint 2

    percent % of the bill is bill * percent / 100.

  3. Hint 3

    Each person pays round(total / people, 2).

Show a solution

One way to solve it. Yours can look different and still pass the checks.

bill = float(input())
percent = float(input())
people = float(input())

tip = round(bill * percent / 100, 2)
total = round(bill + tip, 2)
print("Tip:", tip)
print("Total:", total)
print("Each:", round(total / people, 2))
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

bill = float(input())
percent = input()
people = input()

tip = round(bill * 0.15, 2)
total = round(bill + tip, 2)
print("Tip:", tip)
print("Total:", total)

test_main.py

from learnrun import run_main


def split(bill, percent, people):
    return run_main(f"{bill}\n{percent}\n{people}\n").strip().splitlines()


def test_fifteen_percent():
    """40 with 15 % for 4 people"""
    got = split(40, 15, 4)
    assert got == ["Tip: 6.0", "Total: 46.0", "Each: 11.5"], f"for 40, 15 and 4 the program printed {got!r}"


def test_other_percent():
    """100 with 20 % for 3 people"""
    got = split(100, 20, 3)
    assert got == ["Tip: 20.0", "Total: 120.0", "Each: 40.0"], f"for 100, 20 and 3 the program printed {got!r}"


def test_decimals():
    """12.4 with 10 % for 2 people"""
    got = split(12.4, 10, 2)
    assert got == ["Tip: 1.24", "Total: 13.64", "Each: 6.82"], f"for 12.4, 10 and 2 the program printed {got!r}"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Exercise 3 of 3

Step 3: a tip table

Read the bill, then use a while loop to print the tip for 10 %, 15 % and 20 %, one line each, rounded to 2 decimal places. For a bill of 40: 10% 4.0 15% 6.0 20% 8.0 print(percent, end="% ") writes the percent and the % sign without ending the line.

Tab indents and Shift+Tab outdents. To leave the editor with the keyboard, press Esc, then Tab.

The first run downloads Python for your browser (up to 6.5 MB) and keeps it cached. Your code stays on your device.

Hints
  1. Hint 1

    The loop should run while percent is at most 20: while percent <= 20:

  2. Hint 2

    Indent both print() lines and add 5 to percent at the end of the body.

  3. Hint 3

    Without percent = percent + 5 inside the loop, the condition stays true and the loop never ends.

Show a solution

One way to solve it. Yours can look different and still pass the checks.

bill = float(input())
percent = 10

while percent <= 20:
    print(percent, end="% ")
    print(round(bill * percent / 100, 2))
    percent = percent + 5
Run it on your computer

Install Python 3.14 or newer. Save these files in one folder, open a terminal in that folder, and run the commands below.

main.py

bill = float(input())
percent = 10

# Repeat for 10, 15 and 20 percent.
print(percent, end="% ")
print(round(bill * percent / 100, 2))

test_main.py

from learnrun import run_main


def table(bill):
    return run_main(f"{bill}\n").strip().splitlines()


def test_three_lines():
    """The table has a line for 10, 15 and 20 percent"""
    got = table(40)
    assert len(got) == 3, f"for 40 the program printed {len(got)} line(s), expected 3: {got!r}"


def test_forty():
    """A bill of 40 gives 4.0, 6.0 and 8.0"""
    got = table(40)
    assert got == ["10% 4.0", "15% 6.0", "20% 8.0"], f"for 40 the program printed {got!r}"


def test_decimals():
    """A bill of 12.4 gives 1.24, 1.86 and 2.48"""
    got = table(12.4)
    assert got == ["10% 1.24", "15% 1.86", "20% 2.48"], f"for 12.4 the program printed {got!r}"

On macOS and Linux, type python3 wherever these commands say python, as in the first lesson.

Run the program:

python main.py

Run the checks (needs learnrun.py in the same folder):

python learnrun.py test
Download learnrun.py

Common mistakes

Calculating with the text from input()

bill = "40"  # what input() gives you: a string
print(bill * 1.15)

What Python prints

TypeError: can't multiply sequence by non-int of type 'float'

Why, and the fix

input() returns a string, even when the user types digits. A string can be repeated with an int, but not multiplied by a float. Convert the input as you read it: bill = float(input()).

A decimal comma

price = float("4,50")

What Python prints

ValueError: could not convert string to float: '4,50'

Why, and the fix

Python writes decimals with a point, and float() does not accept a comma. Type 4.50 when the program asks for a number. Later you will learn to catch this error and ask again.

A loop body that is not indented

n = 3
while n > 0:
print(n)

What Python prints

IndentationError: expected an indented block after 'while' statement on line 2

Why, and the fix

The line after while ... : must be indented, because indentation is how Python knows which lines belong to the loop. Indent the body by four spaces.

A body indented unevenly

n = 3
while n > 0:
    print(n)
      n = n - 1

What Python prints

IndentationError: unexpected indent

Why, and the fix

Every line of one body must be indented by exactly the same amount. Here the last line has two extra spaces. Use four spaces for each level, and let the editor insert them.

Python in the browser: Pyodide 314.0.7, MPL-2.0. Licence and source

Exit ticket

5 questions, no hints. Score 80% or more to complete the lesson.

Finish every activity above to unlock the exit ticket.

Report a problem

Spotted something wrong or unclear? Say what, and it will be checked and fixed.

#

At least 20 characters.

Only if you want a reply.

Key ideas

Multiple assignment

a, b = 0, 1 gives a the value 0 and b the value 1 in one line. Python works out every expression on the right first, from left to right, and only then assigns. That is why a, b = b, a swaps two values, and why a, b = b, a + b uses the old a on the right. Comparisons give True or False: < and > compare, == tests equality (one = assigns), != means not equal, and <= and >= include the boundary.

The while loop

while condition: runs the lines below it again and again, as long as the condition is true. Those lines are the body, and indentation marks them: every line of the body is indented by the same amount, usually four spaces, and the first line that is not indented comes after the loop. Something in the body must change, so that the condition becomes false in the end; otherwise the loop never stops. If the condition is false at the start, the body never runs.

input(), float() and end=

input() waits for the user to type a line and returns it as a string, even when it is digits. "4.5" * 2 is "4.54.5", so turn the text into a number first: float(input()) gives the float 4.5. Python writes decimals with a point: float("4,50") is a ValueError. print() normally ends with a newline; print(x, end=" ") ends with a space instead, so the next print() continues on the same line.

Sources

Last reviewed September 29, 2026