- Learn
- Computer Science & IT
- Computing for Ages 11 to 14
- First Programs in Python
First Text Programs in Python
Grade 7, Grade 9Lesson 3 of 10 in Computing for Ages 11 to 14 Course
What you will learn
- 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 codeMatch familiar blocks to typed Python lines, and explain why typed code needs exact syntax.
- Write, save and run a Python programUse 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 printUse print to show strings, numbers and several values on a line, and predict exactly what appears on the screen.
- Compare block code with text code
- 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 assignmentUse the assignment operator to store values in variables, and use those values in later lines.
- Choose valid and clear variable namesApply Python's naming rules, avoid reserved words, and pick names that explain what a value means.
- Update variables and trace a programChange a variable's value, work out what it holds after each line, and record this in a trace table.
- Ask the user for inputUse input with a clear prompt, store the answer in a variable, and use it in the program's output.
- Create variables with assignment
- 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 apartIdentify the data type of a value, choose a suitable type for data, and explain why 5 and "5" are different.
- Calculate with arithmetic operatorsUse Python's arithmetic operators, including integer division and remainder, and predict the type of each result.
- Follow the order of operationsWork out expressions in the order Python uses, and add parentheses so that a calculation means what you intend.
- Join and repeat stringsBuild messages by joining and repeating strings, and choose between commas and plus signs in print.
- Convert between strings and numbersUse 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.
- Tell integers, floats and strings apart
- 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 errorsUse 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 apartSort errors into three kinds by when and how they appear, and recognize the common runtime errors.
- Debug and test a programFollow a step-by-step debugging routine, and choose test data with expected results to check that a program works.
- Read error messages and fix syntax errors
- 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 outputBreak a problem into its inputs, processing and outputs, and turn a plan into Python one line at a time.
- Read, predict and change existing codePredict 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 codeWrite programs that calculate with formulas, test them against hand calculations, and use code to explore how changing a value changes the result.
- Plan a program with input, process and output
First Programs in Python study guide
1Your 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 block | Python instruction |
|---|---|
say [Hello!] | print("Hello!") |
set [score] to 0 | score = 0 |
change [score] by 1 | score = score + 1 |
ask [Name?] and wait | name = 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
.pyending. - 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. sepchanges the separator;endchanges the line ending.- Use matching straight quotes around text.
- An empty
print()adds a blank output line.
2Variables 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 name | Invalid name | Problem |
|---|---|---|
high_score | high score | A space splits the name. |
player2 | 2nd_score | A digit comes first. |
total_cost | total-cost | A 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)
| Line | coins | bonus | New output |
|---|---|---|---|
| 1 | 4 | — | — |
| 2 | 4 | 3 | — |
| 3 | 7 | 3 | — |
| 4 | 7 | 6 | — |
| 5 | 5 | 6 | — |
| 6 | 5 | 6 | 5 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, ais 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.
3Working 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.
| Value | Type | Meaning |
|---|---|---|
5 | int | A whole number |
5.0 | float | A number with a decimal point |
"5" | str | A 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, andstrrepresent 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
| Operator | Job | Example | Result |
|---|---|---|---|
+ | Add | 17 + 5 | 22 |
- | Subtract | 17 - 5 | 12 |
* | Multiply | 17 * 5 | 85 |
/ | Divide | 17 / 5 | 3.4 |
// | Floor division | 17 // 5 | 3 |
% | Find the remainder | 17 % 5 | 2 |
** | Raise to a power | 2 ** 3 | 8 |
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:
- Parentheses, starting with the innermost group.
- Powers, written with
**. - Multiplication and division:
*,/,//, and%. - 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:
3 ** 2gives9.2 * 9gives18.10 + 18gives28.
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 therefore becomes (a + b) / 2. Implied multiplication also needs rewriting: 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 ** 2and(-2) ** 2have 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
| Function | Job | Example |
|---|---|---|
int() | Make a whole number | int("12") gives 12. |
float() | Make a decimal number | float("2.5") gives 2.5. |
str() | Make text | str(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 orfloat()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.
4Finding 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 code | What 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 = 5 | Use one name, such as high_score. |
5 = score | Put 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 kind | What happens | Example |
|---|---|---|
| Syntax | The saved file does not execute. | A missing closing parenthesis |
| Runtime | Execution stops at a problem line. | Division by zero |
| Logic | Execution 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:
| Input | Reason | Expected | Actual |
|---|---|---|---|
8, 10 | Typical scores | 9.0 | 9.0 |
0, 0 | Zero values | 0.0 | 0.0 |
-4, 4 | Opposite values | 0.0 | 0.0 |
ten, 4 | Invalid numeric text | ValueError | ValueError |
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.
5From 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 :
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 . 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
1Type, run, and read a program
12 steps
- 1IntroductionThe 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
printdisplays. Begin by thinking about what each instruction does, then check how Python writes it. - 2ExampleTranslate 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
3without displaying it. The next two lines showGame startand3. In the final line, the unquoted name tells Python to look up the stored value. - 3ExplanationCheck the writing rules
Syntax means the rules for writing code. Python needs matching quotes and parentheses. Capitalization matters too:
printandPrintare 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.
- 4ChallengeTranslate a new pair of blocks
Two blocks first set
roundsto4, then show the value ofrounds. 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. - 5TipKeep a reusable program
Write reusable instructions in the editor and save them with the
.pyending. 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.
- 6ExplanationUnderstand the shell
At the shell's
>>>prompt, an expression such as3 + 4displays7immediately. An assignment such asscore = 5stores 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. - 7ChallengePredict the saved output
What appears when this saved program runs?
# Calculate a sum 3 + 4 print("Finished")---reveal---
Only
Finishedappears. 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 withprint(3 + 4). - 8ExampleChoose text or a calculation
Quotes decide whether characters stay as text:
print("3 + 4") print(3 + 4)The output is
3 + 4and then7. 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. - 9ExplanationControl output spacing
print("Score:", 10)showsScore: 10. Commas normally add spaces between values.sepreplaces that separator.endreplaces the line ending, soend=""lets the next output continue immediately. - 10TipPut 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.
- 11ChallengeRead the whole program
Predict both output lines:
# Count planets planets = 8 print("Planets:", planets) print("planets")---reveal---
The output is
Planets: 8, thenplanets. 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. - 12RecapWhat 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.
2Follow names and changing values
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack what each name holds
- 2ExampleEvaluate before storing
- 3ChallengeFind the needed order
- 4ExplanationNames help people
- 5TipKeep Python’s names available
- 6ChallengeRepair the name consistently
- 7ExampleUpdate from the old value
- 8Key InsightStore an answer, not a live formula
- 9ChallengeTrace several updates
- 10ExampleKeep a value before replacing it
- 11ExampleAsk and keep the reply
- 12ChallengeKeep two replies available
- 13ChallengeCombine names and input
- 14RecapRead values at the moment of use
3Choose types and calculate correctly
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow data through a calculation
- 2ExplanationSeparate three kinds of value
- 3ChallengeChoose types for a project
- 4ExplanationChoose the operation you need
- 5ExampleSplit minutes into two parts
- 6ChallengeWork out groups and leftovers
- 7TipRead decimal results sensibly
- 8ExampleApply the order of operations
- 9ChallengeGroup the total before sharing
- 10Key InsightRead equal priorities and powers
- 11ExampleBuild one exact message
- 12ChallengeRepeat and join text
- 13TipDisplay a number beside text
- 14ExampleConvert from the inside outward
- 15Key InsightKeep the conversion result
- 16ChallengeRepair numeric input
- 17ChallengeFollow a complete price calculation
- 18RecapCheck the type, operator, and grouping
4Use evidence to fix a bug
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionMake the next change for a reason
- 2ExplanationRead the first useful clues
- 3ChallengeRepair one missing symbol
- 4ExampleFind where execution stops
- 5TipUse the error type
- 6ChallengeCompare a working line with its purpose
- 7ExampleFind the first wrong value
- 8ExampleChange and retest
- 9ChallengeChoose a test that reveals the fault
- 10Key InsightKeep expected and actual results separate
- 11ChallengeCheck a complete repair
- 12RecapKeep the cause and check connected
5Build a useful calculator
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart with the result someone needs
- 2ExamplePlan a snack-sale total
- 3ConnectionTranslate the plan’s steps
- 4ChallengePlan a new total
- 5ExamplePredict before editing
- 6TipChange a named setting
- 7ChallengeExplain a modification
- 8ExampleTranslate a temperature formula
- 9ExamplePreserve subtraction before scaling
- 10ChallengeCheck another conversion
- 11Key InsightGive units their own check
- 12ChallengeCalculate two rectangle results
- 13TipLeave a useful explanation
- 14RecapBuild and check in small parts
First Programs in Python practice questions
Set 1: Read and run your first programs10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
What does this saved program display?
# Enter the library
print("Welcome")
Show answerHide answer
# 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
print("Board:", 7) display?Show answerHide answer
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
pet = "otter", what does print("pet") display?Show answerHide answer
"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
Show answerHide answer
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: ")
Show answerHide answer
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
Show answerHide answer
45 // 7. The remainder 3 counts the unused chairs, so it is not the number of complete rows.Question 8 of 10
29 % 6 tell them?Show answerHide answer
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)
Show answerHide answer
Question 10 of 10
Show answerHide answer
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
print("6 * 4") display?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)
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)
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
float("6.25") produce?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
9 + 4 * 2 ** 2 produce?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
team = "Lynx", what expression builds exactly "Go Lynx!"?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)
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")
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
area = length + width. What test best exposes this bug?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)
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
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
What happens in a fresh run?
print(distance)
distance = 14
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Why does the second line fail?
print = 9
print("Done")
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)
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
8.0?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
int("4.8") runs?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)
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
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)
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")
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)
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
12, 18, and 21, then double that mean. What expression does that job?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
print("ab" * 2 + "c") display?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
average = a + b / 2. Which test has a correct expectation and reveals the missing grouping?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
POINTS_PER_TASK = 4 and later score = tasks * POINTS_PER_TASK. What change gives 6 points per task without changing the calculation line?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
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?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)
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
type("9.25") report?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)
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)
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)
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)
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)
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Actual output
8.0 but the actual result is 11.5, inspect the calculation and grouping.Area
Assignment
= and stores its result under the name on the left.total = price * count, Python calculates the product before assigning it to total.B
Block-based language
Bug
C
Case-sensitive
score = 7 does not give a value to the differently capitalized name Score.Code editor
Comment
# begins a comment that continues to the end of the line.# Calculate total distance explains a section’s purpose without adding screen output.Concatenation
+ in Python. It inserts no extra space or punctuation."Good" + "bye" produces "Goodbye"; a space must be included if the message needs one.Constant
SECONDS_PER_MINUTE = 60 marks a fixed conversion value, although Python still allows reassignment.D
Data type
4 + 2 and "4" + "2" behave differently because their values have different types.Debugging
Diagnostic output
print("width is", width) reveals the stored width at a chosen point in execution.E
Empty string
"" or ''. It is different from a string containing one space.end="" adds no characters after the values displayed by that print() call.Error marker
Expected output
7 and 9, an average calculator’s expected result is 8.0.Expression
length * width is an expression whose value can be stored in the variable area.F
Float
3.0 is a float, even though it has the same mathematical value as integer 3.Float conversion
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
//, 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
input() call, while a process rectangle can become assignment.Formula
area = length * width, using dimensions already stored.I
Input
input() obtains a typed reply and returns it as a string.Input, process, output
Integer
int.18 tickets is an integer; the measurement 18.5 needs a different type.Integer conversion
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
input(), the program waits for a typed reply and Enter.K
Keyword
class is reserved, but class_name can store a class code such as "8C".L
Line ending
print() adds after its displayed values. By default, it moves following output to a new line.end="" leaves the next print() output immediately after the previous text.Logic error
M
Modification
N
NameError
print(points) fails in a fresh run if the program has not yet assigned a value to points.O
Operator
* operator multiplies the numeric values in price * count to calculate a total.Order of operations
7 + 3 * 2, multiplication comes first, so the final addition gives 13.Output
Total: 16.0, so the user can tell what the number means.P
Parameter
Parentheses
( 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
Perimeter
2 * (length + width) calculates rectangle perimeter in the same unit as the side lengths.Power
5 ** 2, which gives the result 25.Prediction
PRIMM
Print function
print("Round", 3) displays Round 3 on one line, then moves to the next output line.Priority
2 * 5 ** 2 has higher priority than multiplication, so the result is 50.Process
total = bags * price is the processing step in a snack-sale calculator.Program
Programming language
Prompt
"Height in cm: " asks for a measurement and makes its required unit clear.Pseudocode
OUTPUT area plans a display step that can become print("Area:", area) in Python.Q
Quotient
/ 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
% operator finds it in positive-integer sharing.34 % 6 gives 4, the items left after five full groups of six have been made.Rounding
round() can set decimal places.round(7 / 3, 2) gives 2.33, a result rounded to two decimal places.Runtime error
S
Separator
print() call. The sep setting can replace its usual single space.sep="/", printing the strings "red" and "blue" displays red/blue.Shell
4 + 6 at the >>> prompt shows 10 without needing a separate print() call.Snake case
total_distance follows snake case and tells a reader what its value means.String
str."Room 12" is a string containing letters, a space, and digits that stay together as text.String conversion
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
* operator."la" * 3 produces "lalala", repeating both characters together without spaces.Syntax error
T
Temporary variable
temp = a preserves the old value of a before a = b replaces it.Test data
Text-based language
print("Open") is a typed instruction that displays the text "Open".Trace table
coins = coins + bonus records the new coins value and the unchanged bonus.Traceback
TypeError at the end of a traceback, then checks the named calculation line.Tracing
Truncation
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
float("4.5") converts numeric text into a float that can be used in a length calculation.TypeError
"Total: " + 9 raises a TypeError; a comma in print() can display these values together.U
Unit
Update
points += 3 adds three to the stored points value and keeps the result under the same name.V
Value
city = "Oslo", the name is city and the stored string value is "Oslo".ValueError
int("several") raises a ValueError because that text does not describe a whole number.Variable
length = 9, a calculation using length gets the currently stored value 9.Z
ZeroDivisionError
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.