First Text Programs in Python

Move from block coding to typed code and write your first Python programs. Learn to display text, store values in variables, ask the user for input, calculate with numbers and work with strings. Read error messages, find and fix bugs, and test your work. By the end, you can plan, write and explain short programs that solve real problems, such as converters and simple calculators.

Grade 7, Grade 9Lesson 3 of 10 in Computing for Ages 11 to 14 Course

What you will learn

  1. Explain what changes and what stays the same when moving from block coding to a text language, then write, save and run Python programs that display text and numbers.
    • Compare block code with text code
      Match familiar blocks to typed Python lines, and explain why typed code needs exact syntax.
    • Write, save and run a Python program
      Use a code editor to type a program, save it as a Python file, run it and read what it shows.
    • Display text and numbers with print
      Use print to show strings, numbers and several values on a line, and predict exactly what appears on the screen.
  2. Create, name and update variables, trace how their values change line by line, and use input to make programs respond to the user.
    • Create variables with assignment
      Use the assignment operator to store values in variables, and use those values in later lines.
    • Choose valid and clear variable names
      Apply Python's naming rules, avoid reserved words, and pick names that explain what a value means.
    • Update variables and trace a program
      Change a variable's value, work out what it holds after each line, and record this in a trace table.
    • Ask the user for input
      Use input with a clear prompt, store the answer in a variable, and use it in the program's output.
  3. Tell the main data types apart, write correct calculations, join strings, and convert values so that text and numbers work together.
    • Tell integers, floats and strings apart
      Identify the data type of a value, choose a suitable type for data, and explain why 5 and "5" are different.
    • Calculate with arithmetic operators
      Use Python's arithmetic operators, including integer division and remainder, and predict the type of each result.
    • Follow the order of operations
      Work out expressions in the order Python uses, and add parentheses so that a calculation means what you intend.
    • Join and repeat strings
      Build messages by joining and repeating strings, and choose between commas and plus signs in print.
    • Convert between strings and numbers
      Use int, float and str to change a value's type, so that typed input can be calculated with and numbers can be joined to text.
  4. Read Python's error messages, tell syntax, runtime and logic errors apart, and use tracing and test data to debug a program.
    • Read error messages and fix syntax errors
      Use the information in an error message to find a syntax error, and fix the mistakes beginners make most often.
    • Tell syntax, runtime and logic errors apart
      Sort errors into three kinds by when and how they appear, and recognize the common runtime errors.
    • Debug and test a program
      Follow a step-by-step debugging routine, and choose test data with expected results to check that a program works.
  5. Plan a program from a problem, read and change existing code, and turn formulas and everyday situations into working, documented Python programs.
    • Plan a program with input, process and output
      Break a problem into its inputs, processing and outputs, and turn a plan into Python one line at a time.
    • Read, predict and change existing code
      Predict what a program does before running it, explain how it works, change it, and document it with useful comments.
    • Turn formulas and real situations into code
      Write programs that calculate with formulas, test them against hand calculations, and use code to explore how changing a value changes the result.

First Programs in Python study guide

5 chapters

1

Your first typed instructions

Block programs already teach you to put instructions in order. Python lets you express those same ideas by typing. You will connect familiar blocks to code, learn where to write and run it, and control what appears on screen. Small details such as quotation marks and capitalization matter because Python reads the exact text you enter.

1.1 From blocks to Python

A program tells a computer what to do. You already make programs when you snap blocks together. Python expresses those instructions as typed text. You still need a clear plan and the right order.

The ideas stay familiar

In Scratch, you choose ready-made blocks from a menu. Their shapes help you connect them correctly. In Python, you type the words and symbols yourself. The language changes how you write an instruction. It does not change the need to think through its steps.

Sequence means the order in which instructions run. Variables still hold data. Input still brings data into a program. Output still gives information to the user. Both kinds of program follow the instructions you wrote, including any mistakes.

Here are some close matches:

Scratch blockPython instruction
say [Hello!]print("Hello!")
set [score] to 0score = 0
change [score] by 1score = score + 1
ask [Name?] and waitname = input("Name? ")

The output appears in different places. Scratch's say shows a speech bubble. Python's print() writes to the output area.

Keep the order of the blocks

Suppose the blocks set lives to 3, say "Game start", then say the value of lives. Write the Python lines in that same order:

lives = 3
print("Game start")
print(lives)

The first line stores a value. It shows nothing. The second line shows "Game start". The third line looks up lives and shows 3. Quotes around "lives" would display the word instead of its value.

Type the syntax carefully

Syntax is a language's set of writing rules. Python checks words, capitalization, quotes, and parentheses. print("Hello!") has matching quotes inside matching parentheses. Print("Hello!") uses a different name because Python is case-sensitive. A missing closing quote also changes how Python reads the line.

Block shapes prevent many writing mistakes. Typed code gives you more choices, so you must check these details yourself. A small typing error can stop a program even when its plan is sound.

Pseudocode helps you plan before dealing with those details. OUTPUT "Hello" becomes print("Hello"). INPUT name becomes name = input(). Pseudocode explains steps to a person; Python needs instructions written in its exact syntax.

Text code is easy to search, copy, and share. For long programs, typing and editing can be quicker than dragging blocks. Python also has many ready-made tools for tasks in science, websites, games, and AI. Other text languages express similar ideas differently: JavaScript uses console.log("Hello") for a message. Learning the underlying ideas helps you recognize them in another language.

Key Takeaways

  • Blocks and typed code both use sequence, variables, input, and output.
  • Keep the planned order when turning blocks into Python lines.
  • Python syntax requires exact capitalization and matching symbols.
  • Quotes display text; an unquoted variable name supplies its value.

1.2 Writing and running code

A code editor gives you a place to write Python. IDLE, Thonny, and online editors also provide an output area. A saved program lets you keep several instructions and run them together.

Save a program, then run it

Type these lines in the editor's program area:

# Starting a race
print("Ready")
print("Set")
print("Go")

Save your work as a Python program. Python program files use the .py ending. Use your editor's Run command, then read the output area. You should see "Ready", "Set", and "Go" on separate lines.

The interpreter carries out the Python instructions. In this sequence, execution moves from top to bottom. Moving the last instruction above the others would show "Go" first. The order in the editor becomes the order on screen.

Work through a short cycle: write, save, run, read, improve. Save again after editing, then run the updated program. Run after adding a few lines. If a new problem appears, you have fewer recent changes to examine.

Know when you are in the shell

The interactive shell shows the prompt >>>. You type an instruction there and press Enter to run it immediately. It is useful for trying an expression:

>>> 3 + 4
7
>>> score = 5

The expression produces a value, so the shell displays 7. The assignment stores a value and displays nothing. These prompt symbols belong to the shell. Do not copy them into a saved program.

A saved program handles expressions differently. A line containing only 3 + 4 calculates but displays nothing. Write print(3 + 4) to show the result. Store the instructions in the editor when you want a reusable program; a shell session is for quick experiments.

Leave useful notes and clear space

A comment begins with #. Python ignores the rest of that line. The race program's first line explains its purpose to a reader. It does not display "Starting a race". Comments can also follow an instruction:

print("Hello, world!")  # Show a greeting

Blank lines can separate parts of your program. They do not add blank lines to the output. Use print() for that.

Write one instruction per line. Start these simple sequence instructions at the left edge. An unexpected space at the beginning can produce an IndentationError. Spaces around the contents of parentheses are different: print( "Hi" ) works just like print("Hi"). Consistent layout makes missing symbols and changed lines easier to spot.

Key Takeaways

  • Write reusable programs in the editor and save them with the .py ending.
  • The shell runs entries immediately; its >>> prompt is not program code.
  • Use print() to display a calculation from a saved program.
  • Comments begin with # and do not appear as output.
  • Save and run again after making a change.

1.3 Showing text and values

Output is information a program gives the user. Python's built-in print() function displays values. Put what you want to show inside its parentheses.

Quotes mark text

A string is text held between quotation marks. Both straight single quotes and straight double quotes work. Match the kind you use at both ends:

print("Good morning")
print('Welcome')

The quotes mark the text for Python. They do not appear in the output. Spaces inside a string do appear. For example, print(" 1. Play") keeps its two starting spaces.

Each ordinary print() ends its output with a move to a new line. These instructions therefore make a three-line menu:

print("Menu")
print("  1. Play")
print("  2. Quit")

Use print() with empty parentheses to add a blank output line.

Text and calculations are different

Compare these instructions:

print("3 + 4")
print(3 + 4)

The first displays 3 + 4 exactly as text. The second calculates and displays 7. Quotes tell Python to keep the characters, including the plus sign. Without quotes, Python evaluates the expression.

An unquoted word is treated as a name. print(Hello) tries to find a variable named Hello. If that name has no value, the program stops with a NameError. To display the greeting itself, write print("Hello").

Put several values on one line

Separate values with commas inside print():

print("Score:", 10)
print("Level", 2, "of", 5)

The output is Score: 10, then Level 2 of 5. Python adds one space between values. The commas are instructions for separating them, so they are not printed. You can combine text and numbers this way without converting the numbers.

Two optional settings give more control. print("A", "B", sep="-") displays A-B: sep replaces the usual space. print("Loading", end="") leaves the next output on the same line: end replaces the usual line ending. The empty string "" adds no characters.

Choose quotes that fit the message

An apostrophe can end a single-quoted string too soon. Use double quotes around "It's raining". For a message containing double quotes, use single quotes around the whole string:

print("It's raining")
print('She said "hi"')

Use straight quotes from the keyboard, not curly quotes copied from formatted text. Write lowercase print and close both parentheses. Python 3 needs those parentheses: print "Hi" is not valid Python 3 syntax.

Key Takeaways

  • Quotes mark strings and are not printed as part of the text.
  • Outside quotes, Python evaluates expressions and looks up names.
  • Commas in print() separate values and add spaces by default.
  • sep changes the separator; end changes the line ending.
  • Use matching straight quotes around text.
  • An empty print() adds a blank output line.
2

Variables and user input

A useful program needs values it can keep and use later. Variables give those values names, and input lets a user supply new data on each run. You will assign values, choose readable names, and follow changes one line at a time. Keeping track of which value exists at each moment makes short programs much easier to understand.

2.1 Names that hold values

A variable is a name that refers to a stored value. You can use that name later in a calculation or an output instruction. The first assignment to the name creates the variable.

Read assignment from right to left

In score = 10, the = sign means assignment. Read it as "score is set to 10". Python works out the right side, then stores that value under the name on the left.

The name must be on the left. 10 = score is a syntax error. Assignment is an instruction to store something, so it does a different job from an equals sign in a math equation.

A labeled box is a useful picture: score is the label, and 10 is the value inside right now. To see the value, ask Python to print the name:

score = 10
print(score)

The assignment shows nothing. The print() line displays 10.

Store text and numbers

Strings need quotes when you write their values. Numbers do not:

name = "Ava"
age = 12
print(name, "is", age)

The output is Ava is 12. The names name and age have no quotes in the final line. Python looks up each stored value. The quoted word "is" is displayed as text.

The same distinction applies to a single value:

city = "Lima"
print(city)
print("city")

The first output is Lima. The second is city. Adding quotes around a name asks for the word itself.

Store a calculated result

The right side can use values from other variables:

width = 6
height = 4
area = width * height
print(area)

When Python reaches the third line, width is 6 and height is 4. It multiplies them and stores 24 in area. The last line displays that result. Keeping the dimensions in named variables also makes the calculation easier to read and change.

A value must exist before a line uses it. This order fails:

print(total)
total = 5

Python reaches print(total) before total has a value. The later assignment cannot help a line that has already failed. Put total = 5 first, then print it.

In Scratch, you use a button to make a variable. In Python, the first assignment does that job. The block set [score] to 0 becomes score = 0. You do not need a separate creation command. Later assignments can give the same name a new value as the program runs.

Key Takeaways

  • Assignment evaluates the right side and stores it under the name on the left.
  • The first assignment creates a variable.
  • Use an unquoted name to retrieve its current value.
  • Assign a value before any line tries to use it.

2.2 Clear and valid variable names

Python checks whether a name is allowed. People reading your code need more: a name should explain its value. A valid name can still be confusing.

Follow the naming rules

Names can contain letters, digits, and underscores. A name cannot start with a digit. It cannot contain a space or a hyphen. Compare these choices:

Valid nameInvalid nameProblem
high_scorehigh scoreA space splits the name.
player22nd_scoreA digit comes first.
total_costtotal-costA hyphen is read as subtraction.

Names are case-sensitive. score, Score, and SCORE are different names. After score = 5, print(Score) cannot find the value assigned to lowercase score. It raises a NameError unless Score was assigned separately.

Avoid names Python already needs

A keyword has a fixed meaning in the language. Words such as if, for, while, class, and True cannot be variable names. class = "7B" causes a syntax error. class_name = "7B" is valid.

Built-in function names need care too. Python allows print = 5, but it replaces what the name print refers to. A later print("Hi") then fails with a TypeError. Keep names such as print, input, int, and str available for their usual jobs.

Make the meaning visible

Python programmers usually use lowercase words separated by underscores. This style is called snake case. first_name and total_cost follow it. Capitalization style is a shared habit; it is separate from the rules that decide whether code runs.

Compare a calculation using a, b, and c with this version:

ticket_price = 12
tickets = 3
total_cost = ticket_price * tickets
print(total_cost)

You can tell which value is a price and which is a count. That makes it easier to check the multiplication and change the right input. Python itself does not understand those meanings. age = "Ava" is allowed, although its name misleads a reader.

Mark values meant to stay fixed

A constant is a value intended to stay unchanged while a program runs. Programmers usually write constant names in capitals, such as CM_PER_INCH = 2.54.

Python does not lock a value because its name is capitalized. Another assignment can still replace it. Capitals tell readers to treat the value as fixed.

Key Takeaways

  • Names may contain letters, digits, and underscores, but cannot start with a digit.
  • Use identical capitalization each time you refer to a name.
  • Keywords cannot be variable names; avoid replacing built-in function names.
  • Snake case uses lowercase words joined by underscores.
  • Capitalized constant names express an intention; Python still allows reassignment.

2.3 Changing and tracing values

A variable refers to its current value. Assigning a new value replaces the earlier one. A trace table helps you follow these changes without guessing the output.

Work out an update in two stages

In score = score + 5, Python first reads the old score. It adds 5, then stores the answer back in score. If the old value was 10, the new value is 15.

The short form score += 5 makes the same update for these numbers. Writing only score + 5 calculates a result but does not store it.

A print() uses the value at the moment that line runs:

points = 1
print(points)
points = points + 1
print(points)

The first output is 1. The update then stores 2, so the second output is 2.

Trace one line at a time

Use a column for each variable and one for output:

coins = 4
bonus = 3
coins = coins + bonus
bonus = bonus * 2
coins = coins - 2
print(coins, bonus)
LinecoinsbonusNew output
14——
243—
373—
476—
556—
6565 6

On line 3, add the current values, 4 and 3. On line 4, only bonus changes. Keep coins at 7 until line 5. This is tracing: following the actual instructions with the values available at each step.

Stored answers do not recalculate themselves

A number stored in a variable is an answer, not a live formula:

width = 6
area = width * 2
width = 10
print(area)

The output stays 12. That calculation ran when width was 6. To obtain 20, run area = width * 2 again after changing width.

Likewise, a = 5, b = a, then a = 9 leaves b at 5. Copying the current number does not create a link between the two names.

Keep an old value when swapping

The sequence a = b followed by b = a loses the old value of a. Both names end up with the old value of b. A temporary variable preserves what you still need:

a = 3
b = 8
temp = a
a = b
b = temp
print(a, b)

temp keeps 3, then a becomes 8 and b becomes 3. Python also permits the compact swap a, b = b, a. Its right side gets both old values before the assignments replace them.

Key Takeaways

  • An update reads the old value before storing the new one.
  • An expression alone does not update a variable.
  • Trace each line using the values available at that moment.
  • Changing an input variable does not rerun an earlier calculation.
  • Preserve an old value before overwriting it when swapping values.
  • a, b = b, a is Python’s direct swap form.

2.4 Asking for answers

Input is data a program receives while it runs. input() waits for the user to type an answer and press Enter. The program can use that answer in later instructions.

Ask clearly and keep the reply

Put a helpful prompt inside the parentheses. Assign the answer to a variable so it stays available:

name = input("What is your name? ")
print("Hello,", name)

If the user types "Maya", name receives "Maya". The second line displays Hello, Maya. The question itself is not stored in name; only the reply is.

The prompt ends with a space inside the quotes. That space keeps the user's typing separate from the question. "Name: " gives a clearer screen than "Name:".

The same code can greet a different person on its next run. The instructions stay the same while the input changes. If the program appears to pause at a prompt, click or type in the output area and press Enter. Waiting for input is normal behavior.

Keep answers you still need

Prompts appear in line order. Store separate answers under separate names when both must remain available:

animal = input("Name an animal: ")
food = input("Name a food: ")
print("The", animal, "ate all the", food)

Typing "tiger" then "pizza" produces The tiger ate all the pizza. Reusing animal for the second answer would replace the first reply. You can reuse a variable when its earlier value is no longer needed.

Scratch's ask block puts the latest response in answer. A later question replaces it. Python lets you choose the names that keep the responses you need.

Digits arrive as text too

input() always returns a string. If the user types 12, the stored value is "12". It may look like a number when printed, but it is still text. To calculate with it as a number, convert it using int() or float().

This distinction matters even when no error appears. Joining two text answers with + joins their characters. It does not add the numbers those characters describe.

Check the call and the assignment

input("Name: ") on its own line asks a question but does not keep the returned answer for later. Add name = when later instructions need that answer.

The prompt is text, so it needs quotation marks. input(What is your name?) breaks the syntax. The parentheses matter too: name = input refers to the function without calling it. Use name = input() to ask for a reply, or include a prompt to make the question clear.

Key Takeaways

  • input() waits for typing followed by Enter and returns a string.
  • A prompt tells the user what to enter; it is not part of the stored answer.
  • Assign each reply you need to keep to a suitable variable.
  • Reusing a name replaces its earlier answer.
3

Working with numbers and text

Text and numbers can look alike on screen while behaving differently in code. A program needs the right types, operators, and calculation order to produce the answer you intend. You will calculate with whole numbers and decimals, build messages from strings, and convert typed answers into useful numeric values. Worked expressions show where grouping and types change the result.

3.1 Numbers and text have types

A data type tells you what kind of value you have. It helps decide which operations make sense. The values 5, 5.0, and "5" look similar, but Python gives them different types.

Choose among three main types

An integer, or int, is a whole number. It can be positive, negative, or zero: 12, -3, and 0 are integers. Use integers for counts such as the number of tickets.

A float is Python's number type for values that can have a fractional part. 3.5, -0.25, and 2.0 are floats. A whole-valued number such as 2.0 is still a float. Many courses use the word real for this kind of numeric data. Measurements and prices may need floats.

A string, or str, is a sequence of characters. It can contain letters, digits, spaces, and symbols. "Ava", "7B", and "12" are strings. Quotes make "12" text even though it contains only digits. The empty string "" contains no characters.

ValueTypeMeaning
5intA whole number
5.0floatA number with a decimal point
"5"strA text character
Check a value's type

Use the built-in type() function:

print(type(5))
print(type(5.0))
print(type("5"))

Python displays <class 'int'>, <class 'float'>, and <class 'str'> on separate lines. You can also put a variable name inside type() to inspect its current value.

Python works out the type from the value you assign. You do not need a separate type declaration. x = 5 followed by x = "five" is allowed. The later value is a string, even though the earlier value was an integer.

Think about how data will be used

A code made of digits may still belong in a string. A ZIP code is an identifier, so arithmetic on it is not useful. zip_code = "02134" keeps the leading zero. Writing 02134 as a plain integer literal causes a syntax error.

Choose a string for a name, a class code, or a phone number. Choose an integer for a count. Choose a float when decimal input or a decimal result matters.

Python code uses a decimal point, never a decimal comma. Numeric literals also need no thousands separators. Write 1000 for one thousand. In print(1,000), the comma separates two values, so the output is 1 0. Punctuation changes how Python reads the data.

Key Takeaways

  • int, float, and str represent whole numbers, decimal numbers, and text.
  • Quotes make a value a string, including text made only of digits.
  • Choose a type by what the data means and how it will be used.
  • type() reports a value’s type.
  • Python infers types from assigned values.
  • Use decimal points and no thousands separators in numeric literals.

3.2 Calculating with Python

An expression produces a value. An operator tells Python which calculation to perform. Most programs use these operators with variables as well as plain numbers.

Know the seven operators
OperatorJobExampleResult
+Add17 + 522
-Subtract17 - 512
*Multiply17 * 585
/Divide17 / 53.4
//Floor division17 // 53
%Find the remainder17 % 52
**Raise to a power2 ** 38

Use * for multiplication and / for division. Python does not read × or ÷ as arithmetic operators. Write 2 * x, including the star. 2x is invalid syntax.

A power needs two stars. 2 ** 3 gives 8. The ^ symbol has another job in Python: 2 ^ 3 runs but gives 1. It is not a power operator.

Share whole items and find leftovers

For positive integers, // gives the number of whole groups and % gives the leftover amount. Share 23 cookies among 4 friends: 23 // 4 gives 5 each and 23 % 4 gives 3 left over. Five groups of four use 20 cookies; adding the remaining three checks the total of 23.

% can also check whether a whole number divides evenly. 14 % 2 gives 0, so 14 is even. 15 % 2 gives 1, so 15 is odd.

The same pair of operators splits time:

total_minutes = 125
hours = total_minutes // 60
minutes = total_minutes % 60
print(hours, "hours and", minutes, "minutes")

Two complete hours use 120 minutes. Five remain, so the output is 2 hours and 5 minutes. With negative numbers, floor division rounds down toward the next lower integer; it does not simply cut off decimal digits.

A remainder also reveals divisibility. 14 % 2 gives 0; 15 % 2 gives 1. The % symbol means remainder, not percent. To calculate 20 percent of 50, write 50 * 20 / 100, giving 10.0.

Expect the right kind of result

With integers and floats, / returns a float. 6 / 2 gives 3.0. Addition, subtraction, and multiplication of two integers return integers. A float in one of those operations gives a float result: 5 + 2.0 gives 7.0.

For tickets priced at 4.50 each, 4.50 * 3 gives 13.5. A float does not keep a fixed number of trailing zeros.

Floats store many decimals as close binary approximations. 0.1 + 0.2 displays 0.30000000000000004. Use round(10 / 3, 2) to get 3.33. Without a second argument, round(3.9) gives the integer 4. When a value is exactly halfway between two integers, Python rounds to the even one: round(2.5) gives 2.

Key Takeaways

  • Use * to multiply, / to divide, and ** for powers.
  • For positive integer data, // counts whole groups and % finds leftovers.
  • % means remainder, not percent.
  • / returns a float for integer and float inputs.
  • Floats may display small approximation effects.
  • round(value, places) rounds a result to a chosen number of decimal places.
  • Floor division rounds down; negative results need care.

3.3 Choosing the calculation order

Python follows an order of operations. It does not simply calculate every expression from the left. Parentheses let you make the intended grouping clear.

Work from higher to lower priority

The usual order is:

  1. Parentheses, starting with the innermost group.
  2. Powers, written with **.
  3. Multiplication and division: *, /, //, and %.
  4. Addition and subtraction: + and -.

PEMDAS is one way to remember the levels. Multiplication and division share a level; addition and subtraction share a level. Work left to right within either shared level.

For 10 - 4 - 3, first subtract 4 from 10, giving 6. Subtract 3 next to get 3. In 8 / 2 * 4, divide first to get 4.0, then multiply to get 16.0. Multiplication does not jump ahead of division at the same level.

Follow a worked expression

Take 10 + 2 * 3 ** 2:

  1. 3 ** 2 gives 9.
  2. 2 * 9 gives 18.
  3. 10 + 18 gives 28.

Parentheses can change which values are combined. In (10 + 2) * 3 ** 2, the grouped addition gives 12. The power gives 9. Multiplying them gives 108.

Extra spaces do not alter priority. 2+3 * 4 still gives 14. (2 + 3) * 4 gives 20, because the parentheses change the calculation itself.

Keep a whole numerator together

To find the mean of 80, 90, and 70, add all three numbers before dividing:

average = (80 + 90 + 70) / 3
print(average)

The sum is 240, and division gives 80.0. Without the parentheses, 80 + 90 + 70 / 3 divides only the final number. It gives about 193.33 and no error message.

A fraction bar groups its whole numerator. The formula a+b2 therefore becomes (a + b) / 2. Implied multiplication also needs rewriting: 2(x+1) becomes 2 * (x + 1). 2(x + 1) tries to call the number 2 as if it were a function and raises a TypeError.

Check powers and negative signs

Repeated powers work from the right. 2 ** 3 ** 2 means 2 ** (3 ** 2). The inner power gives 9, then 2 ** 9 gives 512.

A leading minus comes after a power: -2 ** 2 gives -4. To square the negative number itself, write (-2) ** 2, which gives 4. Use round parentheses for numeric grouping. Square and curly symbols have other jobs in Python.

Key Takeaways

  • Parentheses come before powers, then multiplication/division, then addition/subtraction.
  • Work left to right within a shared arithmetic level.
  • Powers grouped in a chain work from the right.
  • Group a whole sum before dividing to find its mean.
  • -2 ** 2 and (-2) ** 2 have different results.

3.4 Building messages from strings

Strings can be combined into longer messages. The operators look familiar, but their jobs depend on the types of values beside them.

Join text with a plus sign

Concatenation means joining strings end to end. "Hot" + "dog" gives "Hotdog". Python adds no space between the strings. Include any space you need:

first = "Sam"
last = "Lee"
full_name = first + " " + last
print(full_name)

The output is Sam Lee. The middle string contains one space. Without it, the result would be SamLee.

With numbers, + adds. With strings, it joins. 5 + 3 gives 8, while "5" + "3" gives "53". The digit characters do not become numbers just because they look numeric.

Repeat a string with a whole-number count

Use * with a string and an integer to repeat the text. "ha" * 3 gives "hahaha". Each copy follows the previous one with nothing added between them. "5" * 3 gives "555", not the number 15.

Repetition is useful for a simple border. This program builds and displays a team message:

team = input("Team name: ")
banner = "Go " + team + "!"
print("*" * 10)
print(banner)
print("*" * 10)

For the reply "Falcons", the middle line is Go Falcons!. The other two lines each contain ten stars. Changing the input changes the message while leaving its border in place.

The repeat count must be an integer. "ha" * 2.5 causes a TypeError. Strings also do not support subtraction or division: "hello" - "o" cannot remove a letter.

Choose commas or concatenation

Commas inside print() accept mixed types and normally put spaces between them. Concatenation needs strings on both sides and adds no spaces.

print("Score:", 10)
print("Score: " + "10")

Both display Score: 10. In the first line, 10 is a number. In the second, it is text. Writing "Score: " + 10 fails because the types do not fit concatenation.

Spacing matters next to punctuation. With name = "Maya", print("Hello,", name, "!") displays Hello, Maya !. Its separators add a space before the exclamation point. print("Hello, " + name + "!") displays Hello, Maya!. Here the strings specify exactly where each space belongs.

Key Takeaways

  • Concatenation joins strings with + and adds no spaces.
  • Repeat text with * and an integer count.
  • print() commas accept mixed types and normally add spaces.
  • Convert a number to text before joining it to a string with +.

3.5 Turning input into numbers

input() returns text. Type conversion, also called casting, makes a value of a different type. Convert numeric replies before using them in calculations.

Choose a conversion
FunctionJobExample
int()Make a whole numberint("12") gives 12.
float()Make a decimal numberfloat("2.5") gives 2.5.
str()Make textstr(12) gives "12".

Use int() for counts or other whole-number input. Use float() when a measurement or price may have a decimal part. float("3") also works and gives 3.0.

Read a nested call from the inside

You can get and convert an answer on one line:

age = int(input("How old are you? "))
next_year = age + 1
print("Next year you will be", next_year)

If the user types 12, input() first returns "12". Then int() makes the integer 12. The assignment stores that integer in age. Adding 1 gives 13, so the output is Next year you will be 13.

Without conversion, age + 1 tries to add a string and an integer. That raises a TypeError. A different mistake can run silently:

first = input("First number: ")
second = input("Second number: ")
print(first + second)

Replies 4 and 5 give 45, because + joins the strings. Converting both input values with int() makes their sum 9.

Store the converted result

Conversion creates a new value. It does not replace the original variable unless you assign the result. After getting text in age, int(age) alone leaves age unchanged. Write age = int(age) to keep the integer.

Use str() when you need text for concatenation:

score = 42
message = "Your score is " + str(score)
print(message)

The output is Your score is 42. The number becomes a string before the plus sign joins it to the message.

Know which values can be converted

int("3.5") raises a ValueError: the text is not written as a whole number. int(3.9) is different. Its input is already a float, so it drops the fractional part and gives 3. It does not round; round(3.9) gives 4.

Text such as "twelve" cannot be converted by int(). A decimal comma also fails: float("2,5") raises a ValueError. Ask clearly for the kind of number the program needs, including a decimal point where appropriate.

Key Takeaways

  • Convert input with int() for whole numbers or float() for decimals.
  • Nested input conversions run from the inside outward.
  • An unstored conversion leaves the original variable unchanged.
  • str() makes text suitable for concatenation.
  • int() on a float drops its fractional part; it does not round.
  • Text must have a suitable numeric form for conversion to succeed.
4

Finding and fixing bugs

A program can fail to start, stop during a run, or finish with a wrong result. Each outcome gives a different clue. You will use error messages, trace values, and choose tests that reveal mistakes. Following one cause at a time makes a repair easier to explain and check, while expected results help you spot bugs Python cannot report.

4.1 Using error messages

A bug is a mistake in code. Debugging means finding and fixing it. Error messages give you clues about where to look and what Python could not understand.

A syntax error prevents a file from running

A syntax error breaks the language's writing rules. Python checks the whole file's syntax before executing it. Consider:

print("Top")
print("Bad"

The second line lacks a closing parenthesis. Nothing in this file runs, including the correct first line. You see an error message, not the word "Top".

A useful message identifies the line, shows the code, marks a nearby position, and names the error. For example:

SyntaxError: unterminated string literal

"Unterminated string" means a string has no closing quote. Find the named line and inspect its quotation marks. A marker such as ^ points near where Python noticed the problem.

Check the likely writing slips
Broken codeWhat to fix
print("Hi)Add the closing quote before ).
print("Hi')Make the two quotes match.
print("Hi"Add the closing parenthesis.
print("Hi"))Remove the extra parenthesis.
high score = 5Use one name, such as high_score.
5 = scorePut the variable name on the left.
print("Hi" name)Separate the values with a comma.

Curly quotation marks copied from formatted writing also need replacing with straight ones. Check the reported line first, then the line above it if needed. An unfinished expression can make Python notice the problem later.

Repair one error at a time

This program has two unfinished calls:

print("Welcome!)
name = input("Name? "
print("Hi", name)

First close the string on line 1. Run again. Then close the parentheses on line 2. The working program is:

print("Welcome!")
name = input("Name? ")
print("Hi", name)

A different message after the first repair can mean Python has reached the next problem. Fix the earliest reported syntax error and check again. Making several guesses at once hides which change helped.

Not every spelling slip is a syntax error. prnt("Hi") has a valid instruction shape. Python starts running and then fails to find the name prnt. That produces a runtime NameError. Use the named error type to guide your search instead of calling every problem a syntax error.

Key Takeaways

  • A syntax error prevents the whole saved file from executing.
  • Read the error type and reported line, then inspect nearby code.
  • Check matching symbols, valid names, and assignment direction.
  • Fix the first reported problem and run again.
  • A misspelled function name can produce a runtime NameError.

4.2 Three kinds of program error

Some bugs stop a program before it starts. Others stop it partway through or leave it running with a wrong answer. These differences help you choose a useful next step.

Ask when the failure happens
Error kindWhat happensExample
SyntaxThe saved file does not execute.A missing closing parenthesis
RuntimeExecution stops at a problem line.Division by zero
LogicExecution finishes but the result is wrong.Adding side lengths to find area

A runtime error happens while code executes. Lines before it have already run:

print("Start")
print(10 / 0)
print("End")

Python displays Start, then reports a ZeroDivisionError. It never reaches the final line. A traceback identifies where the error happened. Read its last line for the error type, then find the program line named above it.

Match the runtime error to its cause

A NameError means Python cannot find a name. Check spelling, capitalization, and whether the name has been assigned. Print("Hi") uses a capital letter. print(Hello) treats the unquoted greeting as a name.

A TypeError means an operation does not fit the types being used. "Age: " + 12 tries to join a string and an integer. Use print("Age:", 12) or convert the number with str().

A ValueError means a supplied value cannot be used for that operation. int("twelve") has text as its input, but that text is not written as an integer. The same program may work with "12" and fail with "twelve".

A ZeroDivisionError means a divisor is zero. Check the actual input and any calculation that produced the divisor.

Compare the result with the intended job

A logic error has no error message to identify it. Python follows the instructions successfully, but they do the wrong job. area = width + height runs, although rectangle area needs multiplication.

Order can cause a logic error too:

total = 0
print(total)
total = 4 + 3

This displays the old total, 0. Moving print(total) after the calculation displays 7. If total had never been assigned, printing it would cause a runtime NameError instead.

Calculate an expected result by hand, then compare it with the program's output. A missing pair of parentheses can be a logic error even though every line has valid syntax. Testing checks whether the code does the intended job, beyond whether Python can run it.

Key Takeaways

  • Syntax errors prevent execution; runtime errors interrupt execution.
  • Logic errors give wrong results without an error message.
  • Use the traceback to locate a runtime failure.
  • Distinguish an unknown name, unsuitable type, unsuitable value, and zero divisor.
  • Compare expected and actual results to find logic errors.
  • Printing an existing old value differs from using a name before assignment.

4.3 Finding bugs and choosing tests

Debugging works best when each change has a reason. First observe the problem. Then collect enough evidence to decide what to change and how to check the repair.

Use a repeatable routine

Run the code and read its output or error. Find the relevant line. Decide what you think went wrong, make one change, then run again. Several changes at once make it hard to tell which one helped.

For a wrong result, trace the values line by line. A temporary print() can also reveal a hidden value. print("total is", total) shows what total holds at that moment. Remove the diagnostic line after the repair, or put # at its start to stop it running.

Check an average program

This program should average two scores:

first = int(input("First score: "))
second = int(input("Second score: "))
average = first + second / 2
print("Average:", average)

For 8 and 10, the expected average is 9.0. The program gives 13.0. Trace the calculation: 10 / 2 gives 5.0, then adding 8 gives 13.0. Only the second score was divided.

Change the calculation to average = (first + second) / 2. The grouped sum is 18, and dividing gives 9.0. Run the same input again to check the repair before trying further data.

Work out the expected result first

Test data is input chosen to check behavior. A test needs an expected outcome so that you can judge the actual result. Calculate that expectation before running; otherwise a plausible wrong answer may persuade you.

For the fixed average program, a test table could contain:

InputReasonExpectedActual
8, 10Typical scores9.09.0
0, 0Zero values0.00.0
-4, 4Opposite values0.00.0
ten, 4Invalid numeric textValueErrorValueError

The last row records the program's behavior with bad input. It does not make the program capable of recovering from that input. A clear prompt can tell users to enter whole numbers.

Choose varied tests that make sense for the program: typical values, zero, negatives, decimals, or unsuitable text. One passing test can miss a bug. The original wrong formula also returns 0.0 for two zeros.

Read and test borrowed code, including code from AI tools. Predict its behavior yourself. A confident explanation or a successful first run does not replace checking the calculations and trying useful test cases.

Key Takeaways

  • Observe, locate, explain, change one thing, and rerun.
  • Use tracing or temporary output to inspect values.
  • Calculate expected outcomes before running tests.
  • Choose varied test data; one successful run can miss a bug.
  • Retest a repair with both the original input and other useful cases.
5

From a plan to a program

Building a program joins planning, reading, and checking. Start with what the user supplies and what answer they need, then work out the steps between them. You will turn plans and formulas into Python, adapt working code, and explain the choices you make. Clear names, useful comments, and easy test cases help you build programs other people can understand.

5.1 Planning inputs, steps, and results

A short program starts with a problem to solve. Identify what data you need, what to do with it, and what result the user should see. This is the input, process, output pattern.

Name the three parts

For a snack sale, the inputs are the number of bags and the price per bag. The process multiplies them. The output is the total price.

Choose names and types before coding. bags is a count, so use an integer. price may contain a decimal, so use a float. total stores the calculated result. A label tells the user what that result means.

# Snack sale total
bags = int(input("How many bags? "))
price = float(input("Price of one bag: "))
total = bags * price
print("Total:", total)

With 6 bags at 1.25, the calculation gives 7.5. The final output is Total: 7.5. The two input lines must run before the multiplication uses their values.

Translate a plan one line at a time

Pseudocode can list the main steps without the Python details:

INPUT length
INPUT width
area = length * width
OUTPUT area

Choose float inputs to allow decimal lengths, then give prompts and units:

length = float(input("Length in meters: "))
width = float(input("Width in meters: "))
area = length * width
print("Area in square meters:", area)

The plan and code follow the same order. The Python version adds exact function calls, conversion, and a useful label. An area label needs square meters because multiplying two lengths changes the unit.

A flowchart expresses the same sequence with arrows. An input/output parallelogram becomes an input() or print() instruction. A process rectangle becomes a calculation or assignment. Follow the arrows to decide the order of the lines.

Let the data decide the order

A line can use a value only after that value exists. Putting total = bags * price above the input lines raises a NameError in a fresh run. Printing an answer before calculating it also puts the steps in the wrong order.

Build the program in small stages. Get the input working first. Add the processing and check it with easy data. Then make the output clear. Run after each addition so a new bug has a small area to hide in.

A sequence program follows the same steps once on each run. Different data can still produce different answers. This is enough for a calculator, a converter, or a simple story generator.

Key Takeaways

  • Identify the inputs, processing, and output before coding.
  • Choose a clear name and a suitable type for each value.
  • Get data before using it; calculate a result before displaying it.
  • Translate pseudocode steps or flowchart arrows into the same code order.
  • Build and check one small part at a time.
  • Label output with its meaning and unit.

5.2 Reading and adapting a program

You can learn to write programs by studying working ones. Predicting first makes you notice which parts you understand and which parts need a closer look.

Follow the PRIMM routine

PRIMM names five useful actions: predict, run, investigate, modify, and make. Start by reading the code and predicting what it will display. Run it to check. Investigate why each line behaves that way. Modify a small part, then use what you learned to make a program of your own.

Try the prediction step with this sharing program:

apples = 6
friends = 4
each = apples // friends
left = apples % friends
print(each, left)

The result is 1 2. Four friends each receive one whole apple, leaving two. Predicting 1.5 would overlook the // operator. Changing friends to 3 gives 2 0: each receives two, and none remain.

Investigate the values and their jobs

Ask what each variable means and which type it holds. Identify inputs, calculations, and output. Consider whether swapping two lines changes which value is available. Try to predict what happens if a divisor becomes zero.

Make one small change at a time and predict its effect before running. If you change both an operator and an input, it becomes harder to explain the result. Preserve a working version so you can compare it with the changed code.

Adapt a named setting

A value controlling a situation's behavior is sometimes called a parameter. Keeping it near the top lets you adapt the program in one place:

TAX_RATE = 0.08
price = float(input("Price: "))
tax = price * TAX_RATE
print("Tax:", tax)

For a price of 50, the tax is 4.0. Changing the setting to 0.05 makes the result 2.5 for the same input. These are example rates for the calculation. The uppercase name marks a constant by convention; Python still permits reassignment.

Write comments that help a reader

A useful comment explains purpose or a choice. # Convert minutes to hours and minutes tells the reader why a section exists. x = 5 # set x to 5 adds little because it repeats the instruction.

A short opening comment can state the program's purpose and author. When modifying code, update comments that no longer match it. A comment describing an old formula can mislead someone even when the new code runs correctly.

Credit borrowed code in a comment that names where it came from. This helps readers identify the original author and distinguish your changes from the starting program.

Key Takeaways

  • PRIMM means predict, run, investigate, modify, and make.
  • Explain each variable’s role and trace its current value.
  • Predict a small change before testing it.
  • A named parameter can adapt a calculation from one location.
  • Comments should explain purpose, stay accurate, and credit borrowed code.

5.3 Putting formulas into programs

A formula becomes code when you name its quantities and rewrite its operations. Get the needed values, calculate the result, and label the output with the right unit.

Keep the formula's grouping

Convert Celsius to Fahrenheit using F=C×95+32:

celsius = float(input("Temperature in Celsius: "))
fahrenheit = celsius * 9 / 5 + 32
print("Temperature in Fahrenheit:", fahrenheit)

For input 20, multiply by 9 to get 180. Divide by 5 to get 36, then add 32 to get 68. The program displays 68.0.

The reverse formula is C=(F−32)×59. Write celsius = (fahrenheit - 32) * 5 / 9. With 68, subtracting gives 36, multiplying gives 180, and dividing gives 20.0. Without parentheses, the multiplication and division happen before subtraction and give about 50.2.

Use one set of inputs for several answers

A rectangle program can calculate both perimeter and area:

length = 6
width = 4
perimeter = 2 * (length + width)
area = length * width
print("Perimeter:", perimeter)
print("Area:", area)

The grouped side sum is 10, so the perimeter is 20. Multiplication gives an area of 24. If the sides are in meters, perimeter is in meters and area is in square meters.

Other formulas need the same care. A triangle with base 8 and height 3 has area 0.5 * 8 * 3: first 4.0, then 12.0. For a circle, set PI = 3.14159. Radius 5 gives PI * 5 ** 2, or 78.53975, because the square is calculated first.

Whole groups and remainders help with time. 200 // 60 gives 3 complete minutes; 200 % 60 gives 20 seconds left.

Calculate from known values

Python assignment computes a result; it does not solve an equation for an unknown. After x = 4, y = 2 * x + 3 stores 11. Writing 2 * x + 3 = 11 is invalid syntax. The left side of assignment must be a name that can receive the calculated value.

Check the result and explore changes

Test with easy values before trusting a formula. A Celsius converter should give 32.0 for 0 and 212.0 for 100. Compare with a hand calculation so a runnable but wrong expression is caught.

Keep units visible in names or labels. Convert centimeters to meters before adding them to a length in meters. Python cannot tell that two plain numbers describe different units.

Change one input to explore a relationship. A rectangle of width 6 and height 4 has area 24. Keeping height fixed and doubling width to 12 gives area 48.

Key Takeaways

  • Translate formula symbols into explicit Python operators.
  • Preserve grouping with parentheses.
  • Calculate multiple results from the same inputs when useful.
  • Assignment evaluates known values; it does not solve for an unknown.
  • Check easy cases by hand and keep measurement units clear.
  • Change one input at a time to explore how a result responds.

First Programs in Python examples

5 Walkthroughs

1

Type, run, and read a program

12 steps
Connect blocks to typed instructions, save a short program, and predict its output.
  1. 1
    IntroductionThe same plan in a new form

    A block program and a Python program can follow the same plan. Both need instructions in a useful order. Python asks you to type each instruction, including its punctuation. Those typing rules are called syntax, and one slip can stop the program.

    You will translate a short block sequence, choose where to run it, and read the output that print displays. Begin by thinking about what each instruction does, then check how Python writes it.

  2. 2
    ExampleTranslate the sequence

    The blocks set lives to 3, show "Game start", then show the lives value. Keep that order in Python:

    lives = 3
    print("Game start")
    print(lives)
    

    The assignment stores 3 without displaying it. The next two lines show Game start and 3. In the final line, the unquoted name tells Python to look up the stored value.

  3. 3
    ExplanationCheck the writing rules

    Syntax means the rules for writing code. Python needs matching quotes and parentheses. Capitalization matters too: print and Print are different names.

    A block supplies much of its own shape. In typed code, you supply the symbols yourself. Keep a correct plan separate from a correct spelling of its instructions: both are needed for the program to work.

  4. 4
    ChallengeTranslate a new pair of blocks

    Two blocks first set rounds to 4, then show the value of rounds. Write the two matching Python instructions.

    ---reveal---

    rounds = 4
    print(rounds)
    

    The assignment creates the value before the output uses it. print("rounds") would display the word itself, so the name needs no quotes here.

  5. 5
    TipKeep a reusable program

    Write reusable instructions in the editor and save them with the .py ending. Use Run, then read the output.

    Save and rerun after editing. Testing a few new lines at a time narrows the search if a problem appears.

  6. 6
    ExplanationUnderstand the shell

    At the shell's >>> prompt, an expression such as 3 + 4 displays 7 immediately. An assignment such as score = 5 stores a value but displays nothing.

    A saved program does not automatically show expression values. Use print(3 + 4) to display the answer there. The >>> symbols belong to the shell and should stay out of saved code.

  7. 7
    ChallengePredict the saved output

    What appears when this saved program runs?

    # Calculate a sum
    3 + 4
    print("Finished")
    

    ---reveal---

    Only Finished appears. The comment is ignored. The expression is evaluated, but a saved program does not display its value automatically. To show the sum too, replace that expression line with print(3 + 4).

  8. 8
    ExampleChoose text or a calculation

    Quotes decide whether characters stay as text:

    print("3 + 4")
    print(3 + 4)
    

    The output is 3 + 4 and then 7. Quotes do not appear on screen; they tell Python to keep the characters inside them. Without quotes, Python performs the calculation. An unquoted word instead asks Python to look up a name.

  9. 9
    ExplanationControl output spacing

    print("Score:", 10) shows Score: 10. Commas normally add spaces between values.

    sep replaces that separator. end replaces the line ending, so end="" lets the next output continue immediately.

  10. 10
    TipPut punctuation inside the text

    For a string containing an apostrophe, choose double quotes around it:

    print("It's raining")
    

    For double quotes inside a message, use single quotes around the whole string. Matching straight quotes make it clear where the text begins and ends. Curly quotes copied from formatted writing do not work as Python string delimiters.

  11. 11
    ChallengeRead the whole program

    Predict both output lines:

    # Count planets
    planets = 8
    print("Planets:", planets)
    print("planets")
    

    ---reveal---

    The output is Planets: 8, then planets. The comment and assignment display nothing. The first call looks up the stored value and inserts a space; the second call displays a quoted word.

  12. 12
    RecapWhat to check before running

    Keep the planned order when translating blocks. Type matching quotes and parentheses, and use exact capitalization. Save reusable instructions in the editor; use the shell for quick tests.

    When predicting output, separate text from names and calculations. Look for the actual print() calls, then check their spaces and line endings.

2

Follow names and changing values

14 steps
Assign values, keep track of updates, and use typed replies in a program.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack what each name holds
  2. 2
    ExampleEvaluate before storing
  3. 3
    ChallengeFind the needed order
  4. 4
    ExplanationNames help people
  5. 5
    TipKeep Python’s names available
  6. 6
    ChallengeRepair the name consistently
  7. 7
    ExampleUpdate from the old value
  8. 8
    Key InsightStore an answer, not a live formula
  9. 9
    ChallengeTrace several updates
  10. 10
    ExampleKeep a value before replacing it
  11. 11
    ExampleAsk and keep the reply
  12. 12
    ChallengeKeep two replies available
  13. 13
    ChallengeCombine names and input
  14. 14
    RecapRead values at the moment of use
3

Choose types and calculate correctly

18 steps
Use operators, grouping, strings, and conversion to get the intended result.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow data through a calculation
  2. 2
    ExplanationSeparate three kinds of value
  3. 3
    ChallengeChoose types for a project
  4. 4
    ExplanationChoose the operation you need
  5. 5
    ExampleSplit minutes into two parts
  6. 6
    ChallengeWork out groups and leftovers
  7. 7
    TipRead decimal results sensibly
  8. 8
    ExampleApply the order of operations
  9. 9
    ChallengeGroup the total before sharing
  10. 10
    Key InsightRead equal priorities and powers
  11. 11
    ExampleBuild one exact message
  12. 12
    ChallengeRepeat and join text
  13. 13
    TipDisplay a number beside text
  14. 14
    ExampleConvert from the inside outward
  15. 15
    Key InsightKeep the conversion result
  16. 16
    ChallengeRepair numeric input
  17. 17
    ChallengeFollow a complete price calculation
  18. 18
    RecapCheck the type, operator, and grouping
4

Use evidence to fix a bug

12 steps
Read a failure, identify its cause, repair it, and check the change with useful test data.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionMake the next change for a reason
  2. 2
    ExplanationRead the first useful clues
  3. 3
    ChallengeRepair one missing symbol
  4. 4
    ExampleFind where execution stops
  5. 5
    TipUse the error type
  6. 6
    ChallengeCompare a working line with its purpose
  7. 7
    ExampleFind the first wrong value
  8. 8
    ExampleChange and retest
  9. 9
    ChallengeChoose a test that reveals the fault
  10. 10
    Key InsightKeep expected and actual results separate
  11. 11
    ChallengeCheck a complete repair
  12. 12
    RecapKeep the cause and check connected
5

Build a useful calculator

14 steps
Plan a program, adapt code, translate formulas, and check the result with clear units.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart with the result someone needs
  2. 2
    ExamplePlan a snack-sale total
  3. 3
    ConnectionTranslate the plan’s steps
  4. 4
    ChallengePlan a new total
  5. 5
    ExamplePredict before editing
  6. 6
    TipChange a named setting
  7. 7
    ChallengeExplain a modification
  8. 8
    ExampleTranslate a temperature formula
  9. 9
    ExamplePreserve subtraction before scaling
  10. 10
    ChallengeCheck another conversion
  11. 11
    Key InsightGive units their own check
  12. 12
    ChallengeCalculate two rectangle results
  13. 13
    TipLeave a useful explanation
  14. 14
    RecapBuild and check in small parts

First Programs in Python practice questions

50 Practice Questions in 5 sets

Set 1: Read and run your first programs10 Practice Questions

Question 1 of 10

A block sequence says "Open", then "Close". What output order should its direct Python translation keep?
  1. Close, then Open
  2. Open twice
  3. Open, then Close
  4. Close twice
Show answerHide answer
Answer: C
Sequence keeps the instructions in their planned order. The first message should therefore be "Open", followed by "Close". Changing to typed code does not reverse the sequence; reversing the lines would make a different program.

Question 2 of 10

What does this saved program display?

# Enter the library
print("Welcome")
  1. Welcome
  2. Enter the library
  3. # Enter the library
  4. # Enter the library, then Welcome
Show answerHide answer
Answer: A
Python ignores a comment from # to the end of its line. Only the print() instruction produces output, so the screen shows "Welcome". A comment explains the program to a reader; it is not a message sent to the user.

Question 3 of 10

What does print("Board:", 7) display?
  1. Board:7
  2. Board:, 7
  3. "Board:" 7
  4. Board: 7
Show answerHide answer
Answer: D
The comma separates two values inside print(). Python displays them with one space between them, giving Board: 7. It does not display the separating comma or the quotation marks that mark the string in the code.

Question 4 of 10

After pet = "otter", what does print("pet") display?
  1. otter
  2. pet
  3. "otter"
  4. NameError
Show answerHide answer
Answer: B
The quotes make "pet" a string containing the word itself. Python displays that text without looking up the variable. To display the stored animal name, use print(pet) with no quotation marks around the variable name.

Question 5 of 10

What snake-case name could store a player’s second score?
  1. 2nd_score
  2. second score
  3. second_score
  4. second-score
Show answerHide answer
Answer: C
second_score uses lowercase letters and an underscore, so it follows snake case and Python naming rules. Starting with a digit, adding a space, or using a hyphen does not make a valid single variable name. The hyphen is read as subtraction.

Question 6 of 10

The user types "Inez". What value is stored in visitor?

visitor = input("Visitor name: ")
  1. The string "Visitor name: "
  2. The string "Inez"
  3. The string "Visitor name: Inez"
  4. The string "visitor"
Show answerHide answer
Answer: B
The prompt tells the user what to enter, but it is not part of the returned value. input() returns the reply as a string, so visitor holds "Inez". The screen may show the prompt beside the typing, which does not make them one stored answer.

Question 7 of 10

How many complete rows of 7 chairs can be made from 45 chairs?
  1. 6 rows
  2. 7 rows
  3. 3 rows
  4. 6.43 rows
Show answerHide answer
Answer: A
Six full rows use 42 chairs, leaving three chairs that cannot form another complete row. The calculation is 45 // 7. The remainder 3 counts the unused chairs, so it is not the number of complete rows.

Question 8 of 10

A group packs 29 badges into full packets of 6. What does 29 % 6 tell them?
  1. 4 badges remain.
  2. 4.83 badges remain.
  3. 6 badges remain.
  4. 5 badges remain.
Show answerHide answer
Answer: D
Four full packets use 24 badges, leaving 5, so 29 % 6 gives 5. The value 4 comes from 29 // 6 and counts the full packets. Remainder and floor division answer different parts of the packing question.

Question 9 of 10

This saved file has a missing quote on line 2. What happens when it is run?

print("North")
print("South)
  1. A syntax error appears with no program output.
  2. North appears, then a syntax error.
  3. North and South appear, then an error.
  4. A runtime error appears after North.
Show answerHide answer
Answer: A
Python checks the whole file for valid syntax before executing its instructions. The unfinished string prevents this file from starting, so even "North" is not displayed. Earlier output would be possible for a runtime error, which happens after execution has begun.

Question 10 of 10

A program asks for the number of art kits and their decimal price, then shows the total. Which sequence works in a fresh run?
  1. total = kits * price → kits = int(input()) → price = float(input()) → print(total)
  2. kits = input() → price = input() → total = kits + price → print(total)
  3. kits = int(input()) → price = float(input()) → total = kits * price → print(total)
  4. kits = int(input()) → price = float(input()) → print(total) → total = kits * price
Show answerHide answer
Answer: C
Get and convert both inputs before multiplying them, then display the stored total. Whole kit counts need int() and decimal prices need float(). Printing before assignment fails in a fresh run, while joining two unconverted replies produces text instead of the total cost.
Set 2: Trace values and check types10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does print("6 * 4") display?
  1. 24
  2. 6 * 4
  3. 6 4
  4. "24"
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does this program display?

steps = 7
steps + 4
print(steps)
  1. 11
  2. 4
  3. NameError
  4. 7
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

The user types "violet", then "gold". What does this program display after the prompts?

color = input("First color: ")
color = input("Second color: ")
print(color)
  1. gold
  2. violet
  3. violet gold
  4. Second color: gold
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What value does float("6.25") produce?
  1. The string "6.25"
  2. The integer 6
  3. The number 6.25
  4. A ValueError
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What value does 9 + 4 * 2 ** 2 produce?
  1. 52
  2. 41
  3. 100
  4. 25
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

With team = "Lynx", what expression builds exactly "Go Lynx!"?
  1. "Go " + team + "!"
  2. "Go" + team + "!"
  3. "Go " + team + " !"
  4. "Go " + "team" + "!"
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

The user types 6, then 7. What does this program display?

a = input()
b = input()
int(a)
print(a + b)
  1. 13
  2. TypeError
  3. 67
  4. ValueError
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What appears before this program stops?

print("Blue")
print(12 / 0)
print("Green")
  1. No output, then a SyntaxError
  2. Blue, then a ZeroDivisionError
  3. Blue and Green, then a ZeroDivisionError
  4. Blue, then a NameError
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program should calculate a rectangle’s area, but uses area = length + width. What test best exposes this bug?
  1. Length 2, width 2; expected area 4.
  2. Length 3, width 5; expected area 8.
  3. Length 1, width 1; expected area 2.
  4. Length 3, width 5; expected area 15.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

The purpose is to share 31 beads equally among 5 people, showing whole beads each and leftovers. After replacing // with /, what changes?

beads = 31
people = 5
each = beads // people
left = beads % people
print(each, left)
  1. each stays 6; left becomes 0.
  2. each becomes 6.2; left stays 1.
  3. each becomes 6.2; left becomes 0.2.
  4. each stays 6; left stays 1.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Explain the result and find the fault10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A Scratch program sets a value, changes it, then shows it. Why must a Python translation preserve that order?
  1. Python displays assignments before running output.
  2. Text languages create a new variable for every line.
  3. The last written line always determines all earlier values.
  4. Each step uses the value produced by earlier steps.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

Where should you write several instructions that you want to save and rerun as a program?
  1. In the output area after the program has finished.
  2. In the editor’s program area.
  3. At a >>> prompt, keeping only its displayed results.
  4. In the input prompt string of the next program.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What happens in a fresh run?

print(distance)
distance = 14
  1. 14 appears before assignment.
  2. distance appears as plain text.
  3. A NameError occurs on the first line.
  4. Nothing appears and both lines finish.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Why does the second line fail?

print = 9
print("Done")
  1. print now refers to a number, so the call raises a TypeError.
  2. print is a keyword, so line 1 raises a SyntaxError.
  3. print was never assigned, so the call raises a NameError.
  4. "Done" is text, so the call raises a ValueError.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does this program display?

small = 4
large = 9
saved = small
small = large
large = saved + 2
print(small, large)
  1. 9 11
  2. 6 9
  3. 9 4
  4. 9 6
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What type is the value 8.0?
  1. int
  2. str
  3. float
  4. input
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What happens when int("4.8") runs?
  1. It returns the integer 4.
  2. It raises a ValueError.
  3. It returns the integer 5.
  4. It returns the float 4.8.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

The variable pupil already holds a name. What repair lets this line display "Hi" and the name?

print("Hi" pupil)
  1. print("Hi", pupil)
  2. print("Hi pupil")
  3. print("Hi", "pupil")
  4. print(Hi, pupil)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A fresh run gets inputs 8 and 3, displays Difference: 0, then finishes. What best explains the problem?

a = int(input())
b = int(input())
difference = 0
print("Difference:", difference)
difference = a - b
  1. It uses an unknown name, causing a runtime error.
  2. It assigns a value twice, causing a syntax error.
  3. It prints the old value, causing a logic error.
  4. It subtracts integers, causing a conversion error.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A rectangle’s area is stored before its width changes. What single line should be inserted immediately before print(area) to show the new area?

length = 7
width = 3
area = length * width
width = 5
print(area)
  1. area = length * width
  2. width = area / length
  3. area = length + width
  4. length = area / width
Show answerHide answer

Save this lesson to see this answer.

Set 4: Repair and adapt short programs10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does this code display on one line?

print("AB", "CD", sep="/", end="!")
print("EF")
  1. AB/CD!EF
  2. AB CD!EF
  3. AB/CD! EF
  4. AB/CD EF!
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does this program display?

stock = 11
packed = stock - 4
stock = 20
packed += 2
print(stock, packed)
  1. 20 18
  2. 11 9
  3. 20 9
  4. 20 7
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A program shows "City: " and waits without an error message. What should its user do next?
  1. Type a new print() instruction into the editor.
  2. Type the city in the input area and press Enter.
  3. Remove the prompt and run the same code again.
  4. Add quotation marks around the whole program.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A timer splits 257 seconds into complete minutes and remaining seconds. What pair should it display?
  1. 4 minutes and 57 seconds.
  2. 5 minutes and 17 seconds.
  3. 4 minutes and 28 seconds.
  4. 4 minutes and 17 seconds.
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A program should calculate the mean of scores 12, 18, and 21, then double that mean. What expression does that job?
  1. 2 * 12 + 18 + 21 / 3
  2. 2 * (12 + 18 + 21) / 3
  3. (2 * 12 + 18 + 21) / 3
  4. 2 * (12 + 18 + 21 / 3)
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does print("ab" * 2 + "c") display?
  1. ababc
  2. abcabc
  3. abab c
  4. ab2c
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

An average calculator uses average = a + b / 2. Which test has a correct expectation and reveals the missing grouping?
  1. Inputs 0, 0; expected 0.0.
  2. Inputs 6, 14; expected 13.0.
  3. Inputs 0, 14; expected 7.0.
  4. Inputs 6, 14; expected 10.0.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A flowchart asks for a distance, multiplies it by a conversion factor, then displays the converted distance. What job does its middle process rectangle become?
  1. An input call asking for the same distance again.
  2. A print call displaying the original distance.
  3. An assignment storing the multiplication result.
  4. A comment describing the distance’s input type.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program uses POINTS_PER_TASK = 4 and later score = tasks * POINTS_PER_TASK. What change gives 6 points per task without changing the calculation line?
  1. Set POINTS_PER_TASK to 6.
  2. Set POINTS_PER_TASK to 2.
  3. Set tasks to 6 on every run.
  4. Rename score to six_points.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A rectangle is 9 meters long and 2 meters wide. What Python expression calculates its perimeter?
  1. 9 * 2
  2. 2 * (9 + 2)
  3. 2 * 9 + 2
  4. (9 + 2) ** 2
Show answerHide answer

Save this lesson to see this answer.

Set 5: Solve new programming problems10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A learner types 15 - 6 at >>> and sees 9. They put only 15 - 6 in a saved program and see no output. What should the program contain to show the answer?
  1. >>> 15 - 6
  2. # print(15 - 6)
  3. print(15 - 6)
  4. print("15 - 6")
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does this code display?

x = 8
y = x + 3
x = y - 2
y = x + y
print(x, y)
  1. 8 19
  2. 9 18
  3. 11 20
  4. 9 20
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What type does type("9.25") report?
  1. float
  2. str
  3. int
  4. round
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does this program display?

base = -3
result = base ** 2 + 18 / 3 * 2
print(result)
  1. 21.0
  2. 3.0
  3. 12.0
  4. 33.0
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The user types 2.75, then 4. The program should show the price of four items plus a fee of 1. What repair makes it display 12.0?

price = input()
count = int(input())
float(price)
total = price * count
print(total + 1)
  1. Replace float(price) with price = int(price).
  2. Replace total = price * count with total = price + count.
  3. Replace float(price) with price = float(price).
  4. Replace count = int(input()) with count = input().
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What error type occurs when this fresh program runs?

amount = "14"
print(amount / 2)
  1. A TypeError from dividing a string by an integer.
  2. A ValueError from converting decimal text.
  3. A NameError from an unassigned variable.
  4. A SyntaxError from a missing parenthesis.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A fresh run gets inputs 9 and 2, displays Ready, then stops. What is the error type, and why?

count = input()
extra = int(input())
print("Ready")
print(count + extra)
  1. ValueError: the text "9" cannot be converted.
  2. SyntaxError: the whole file has invalid syntax.
  3. NameError: count has no assigned value.
  4. TypeError: the addition mixes text and an integer.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

This program should extend a ribbon by half a meter and show its new length in centimeters. What repair and test correctly check the result?

length = float(input())
centimeters = length * 100
length = length + 0.5
print(centimeters)
  1. Recalculate centimeters before the extension; input 1.5 should give 200.0.
  2. Recalculate centimeters after the extension; input 1.5 should give 200.0.
  3. Recalculate centimeters after the extension; input 1.5 should give 150.0.
  4. Add 0.5 to centimeters after the extension; input 1.5 should give 200.0.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A program needs decimal base and height inputs and must show triangle area. What types should those two inputs have before processing?
  1. Both should be strings.
  2. Both should be integers.
  3. Both should be floats.
  4. One should be a string.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A square has a side of 3 meters. A program is changed so the side becomes 6 meters and the area is recalculated. How does the area change?
  1. From 9 to 18 square meters: twice as large.
  2. From 6 to 12 square meters: twice as large.
  3. From 9 to 12 square meters: three more.
  4. From 9 to 36 square meters: four times as large.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

75 Key Terms, each with its definition

A

Actual output
Actual output is what a program really displays during a run. Comparing it with the expected output helps locate bugs.
If the expected mean is 8.0 but the actual result is 11.5, inspect the calculation and grouping.
Area
An area measures the surface inside a flat shape. Rectangle area multiplies length by width and uses square units.
A rectangle measuring 7 meters by 2 meters has an area of 14 square meters.
Assignment
An assignment evaluates the expression on the right of = and stores its result under the name on the left.
In total = price * count, Python calculates the product before assigning it to total.

B

Block-based language
A block-based language lets you build code by connecting ready-made blocks whose shapes limit how they fit together.
In Scratch, a sequence of connected blocks can store a score and show its current value.
Bug
A bug is a mistake in a program that makes it fail or behave differently from its intended purpose.
A missing parenthesis stops a program, while the wrong formula may give an answer that only looks plausible.

C

Case-sensitive
A language is case-sensitive when capital and lowercase letters make different names or instructions.
Assigning score = 7 does not give a value to the differently capitalized name Score.
Code editor
A code editor is a tool for writing and changing program text. It provides a place to keep instructions together.
A learner types several Python lines in the editor, saves the program, and then runs it.
Comment
A comment is a note in code for people to read. In Python, # begins a comment that continues to the end of the line.
The comment # Calculate total distance explains a section’s purpose without adding screen output.
Concatenation
Concatenation joins strings end to end using + in Python. It inserts no extra space or punctuation.
"Good" + "bye" produces "Goodbye"; a space must be included if the message needs one.
Constant
A constant is a value intended to stay fixed during a program. Capitalized names express this intention in Python.
SECONDS_PER_MINUTE = 60 marks a fixed conversion value, although Python still allows reassignment.

D

Data type
A data type is a kind of value. It helps determine how that value is handled and which operations make sense.
The expressions 4 + 2 and "4" + "2" behave differently because their values have different types.
Debugging
Debugging is finding and fixing bugs by observing behavior, locating a cause, making a change, and checking again.
A learner traces a wrong total, repairs one operator, and reruns the same input to check the fix.
Diagnostic output
Diagnostic output is temporary displayed information used to inspect program values while finding a bug.
Adding print("width is", width) reveals the stored width at a chosen point in execution.

E

Empty string
An empty string is text with no characters, written as "" or ''. It is different from a string containing one space.
Setting end="" adds no characters after the values displayed by that print() call.
Error marker
An error marker points near the place where Python noticed a problem; the underlying cause can be earlier in the code.
When the indicated line looks correct, check whether the previous line left a parenthesis open.
Expected output
Expected output is the result a program should display for a chosen input, worked out independently before testing.
For inputs 7 and 9, an average calculator’s expected result is 8.0.
Expression
An expression is a piece of code that produces a value by using values, names, operators, or function calls.
length * width is an expression whose value can be stored in the variable area.

F

Float
A float is Python’s numeric type for values that can include a fractional part. Many decimals are stored approximately.
The literal 3.0 is a float, even though it has the same mathematical value as integer 3.
Float conversion
Float conversion uses float() to make a float, allowing suitable decimal text to become a numeric value.
float(input("Length: ")) converts the typed length before later arithmetic uses it.
Floor division
Floor division, written //, rounds a quotient down. For positive integers, it counts complete groups.
34 // 6 gives five full groups; six items in each group account for thirty items.
Flowchart
A flowchart shows algorithm steps as shapes linked by arrows. Following the arrows gives the order of the instructions.
An input/output parallelogram can become an input() call, while a process rectangle can become assignment.
Formula
A formula describes a calculation relating quantities. Python code needs explicit operators and any required grouping.
The rectangle-area formula becomes area = length * width, using dimensions already stored.

I

Input
Input is data a program receives while it runs. Python’s input() obtains a typed reply and returns it as a string.
A team-name input lets the same program build a different banner each time someone runs it.
Input, process, output
Input, process, output is a planning pattern that identifies received data, the work done on it, and the result to display.
A ribbon calculator gets a count and length, multiplies them, then shows total meters.
Integer
An integer is a whole number, including zero and negative numbers. Python gives integer values the type name int.
A count of 18 tickets is an integer; the measurement 18.5 needs a different type.
Integer conversion
Integer conversion uses int() to make an integer, such as from whole-number text or by truncating a float.
int("17") gives integer 17, but decimal text such as "17.2" cannot be converted directly.
Interpreter
An interpreter is software that carries out Python code. It executes the instructions of a simple sequence in order.
When the interpreter reaches input(), the program waits for a typed reply and Enter.

K

Keyword
A keyword is a word reserved for a fixed role in Python’s language rules, so it cannot be used as a variable name.
The word class is reserved, but class_name can store a class code such as "8C".

L

Line ending
A line ending is what print() adds after its displayed values. By default, it moves following output to a new line.
Using end="" leaves the next print() output immediately after the previous text.
Logic error
A logic error makes a program produce an unintended result even though its instructions can run without an error message.
An area calculation that adds a rectangle’s sides finishes normally but gives the wrong measurement.

M

Modification
A modification is a change to existing code, such as altering a value, prompt, or operator to change its behavior.
Changing one input prompt in a calculator program improves clarity while leaving its arithmetic unchanged.

N

NameError
A NameError occurs when Python cannot find a name being used, often because of spelling or assignment order.
print(points) fails in a fresh run if the program has not yet assigned a value to points.

O

Operator
An operator is a symbol that tells Python to perform an operation on values, such as addition or multiplication.
The * operator multiplies the numeric values in price * count to calculate a total.
Order of operations
The order of operations sets which arithmetic operations happen first when an expression has several operators.
In 7 + 3 * 2, multiplication comes first, so the final addition gives 13.
Output
Output is information a program gives to its user, such as a message or a displayed calculation result.
A calculator’s output might be Total: 16.0, so the user can tell what the number means.

P

Parameter
A parameter can be a value controlling a modeled situation, kept in a named variable so the calculation can be adapted.
Changing a points-per-task parameter changes every score calculation that refers to that value.
Parentheses
Parentheses are the round symbols ( and ). Around an expression, they group work that must be done together.
(a + b) / 2 groups the whole sum before division, so it calculates the mean of two numbers.
PEMDAS
PEMDAS is a reminder for parentheses, exponents, multiplication/division, and addition/subtraction, in priority order.
The multiplication and division level works left to right; multiplication does not always go first.
Perimeter
A perimeter is the distance around a shape. For a rectangle, it is twice the sum of one length and one width.
2 * (length + width) calculates rectangle perimeter in the same unit as the side lengths.
Power
A power raises a base to an exponent. For a positive whole-number exponent, this multiplies copies of the base.
Python writes the square of five as 5 ** 2, which gives the result 25.
Prediction
A prediction is an expected account of what code will do, made by reading its instructions before running it.
A prediction of two printed values can be checked against the run to find a misunderstood operator.
PRIMM
PRIMM is a learning routine: predict, run, investigate, modify, and make, moving from reading code to creating it.
A learner predicts a sharing result, runs the code, explains its operators, then adapts it.
Print function
The print function is Python’s built-in action for displaying values, with spaces between them and a line ending by default.
print("Round", 3) displays Round 3 on one line, then moves to the next output line.
Priority
An operator’s priority determines when it is applied compared with other operators in the same expression.
The power in 2 * 5 ** 2 has higher priority than multiplication, so the result is 50.
Process
A process is work a program performs on data, such as calculating a total from inputs and storing the result.
The instruction total = bags * price is the processing step in a snack-sale calculator.
Program
A program is a set of instructions written for a computer to carry out. Its steps determine what the computer does.
A greeting program asks for a name, stores the reply, and displays a message that uses it.
Programming language
A programming language is a language with rules for writing instructions that a computer can carry out.
Python and JavaScript express familiar ideas, such as output, using different words and symbols.
Prompt
A prompt is a message telling the user what to enter. It is displayed before a reply and is not part of the returned answer.
The prompt "Height in cm: " asks for a measurement and makes its required unit clear.
Pseudocode
Pseudocode is a readable plan for algorithm steps that does not need to follow a programming language’s exact syntax.
OUTPUT area plans a display step that can become print("Area:", area) in Python.

Q

Quotient
A quotient is the result of division. Python’s / gives a float quotient for integer and float inputs.
15 / 4 gives a quotient of 3.75, while whole-group sharing needs a different result.

R

Remainder
A remainder is what is left after forming whole groups. Python’s % operator finds it in positive-integer sharing.
34 % 6 gives 4, the items left after five full groups of six have been made.
Rounding
Rounding replaces a value with a nearby value at a chosen precision. Python’s round() can set decimal places.
round(7 / 3, 2) gives 2.33, a result rounded to two decimal places.
Runtime error
A runtime error occurs while instructions execute. An unhandled error stops the run at the failing operation.
Dividing by zero after a greeting prints the greeting, then stops before the remaining instructions.

S

Separator
A separator is text placed between values in a print() call. The sep setting can replace its usual single space.
With sep="/", printing the strings "red" and "blue" displays red/blue.
Shell
A shell is an interactive place to enter and run Python immediately. It displays the values of entered expressions.
Typing 4 + 6 at the >>> prompt shows 10 without needing a separate print() call.
Snake case
Snake case is a naming style that joins lowercase words with underscores, making longer names easy to read.
The variable name total_distance follows snake case and tells a reader what its value means.
String
A string is a sequence of characters, such as letters, digits, spaces, or symbols. Python calls its string type str.
"Room 12" is a string containing letters, a space, and digits that stay together as text.
String conversion
String conversion uses str() to make text from a value, allowing a number to be included in concatenation.
"Page " + str(6) builds "Page 6" without trying to join a string directly to an integer.
String repetition
String repetition builds text by repeating a whole string an integer number of times using the * operator.
"la" * 3 produces "lalala", repeating both characters together without spaces.
Syntax error
A syntax error breaks Python’s writing rules. A saved file containing one fails its syntax check before execution.
A missing closing quote can prevent every instruction in the file from running, even the earlier lines.

T

Temporary variable
A temporary variable keeps a value while other names are changed, so that the value remains available for a later step.
In a swap, temp = a preserves the old value of a before a = b replaces it.
Test data
Test data is input chosen to check a program’s behavior, paired with an expected outcome for judging the run.
Testing an average program with unequal scores can expose a grouping bug that two zeros would miss.
Text-based language
A text-based language lets you write program instructions as typed text, using the language’s exact words and symbols.
In Python, print("Open") is a typed instruction that displays the text "Open".
Trace table
A trace table records variable values and output as a program’s instructions are followed in order.
A row after coins = coins + bonus records the new coins value and the unchanged bonus.
Traceback
A traceback reports where a runtime error occurred. Its final line names the error type and describes the problem.
A learner reads TypeError at the end of a traceback, then checks the named calculation line.
Tracing
Tracing means following a program one instruction at a time, tracking its values and output by hand.
Tracing shows why an output line before an update displays an old score instead of the new one.
Truncation
Truncation removes a number’s fractional part. Applying int() to a float truncates toward zero instead of rounding.
int(5.8) gives 5, while round(5.8) gives 6; these operations serve different purposes.
Type conversion
Type conversion, also called casting, makes a value of one type from another when the supplied value is suitable.
float("4.5") converts numeric text into a float that can be used in a length calculation.
TypeError
A TypeError occurs when an operation is unsuitable for the types involved, such as adding a string to an integer.
"Total: " + 9 raises a TypeError; a comma in print() can display these values together.

U

Unit
A unit states what a measurement counts or measures, such as meters or seconds. Plain numeric code does not check units.
Convert centimeters to meters before adding a measured length to another length stored in meters.
Update
An update replaces a variable’s value, often using its current value in a calculation that produces the new one.
points += 3 adds three to the stored points value and keeps the result under the same name.

V

Value
A value is a particular piece of data, such as a number or string, that a program can store and use.
In city = "Oslo", the name is city and the stored string value is "Oslo".
ValueError
A ValueError occurs when an operation receives an unsuitable value, such as text that cannot be converted as requested.
int("several") raises a ValueError because that text does not describe a whole number.
Variable
A variable is a name that refers to a stored value. Later instructions can retrieve or replace that value.
After length = 9, a calculation using length gets the currently stored value 9.

Z

ZeroDivisionError
A ZeroDivisionError occurs when a calculation divides by zero. The divisor may come from input or an earlier calculation.
A sharing program fails if the number of people is zero when it calculates items per person.

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started