Python Basics: Values, Variables, and Expressions

Write and run your first Python programs. Learn how Python stores whole numbers, decimal numbers and text, how variables name and update values, and how operators and the order of operations turn values into results. Read input from the user, convert it to the right type, print clear output, explain your code with comments, and use error messages to fix mistakes.

BeginnerLesson 1 of 10 in Python for Beginners: Introduction to Programming

What you will learn

  1. Run Python code in the interactive shell and as saved script files, follow how a program runs from top to bottom, read error messages to fix mistakes, and explain code with comments.
    • Run code in the shell and as a script
      Tell the interactive shell apart from a saved program file, run code both ways, and predict what each one shows on the screen.
    • Read error messages and fix common mistakes
      Recognize syntax errors, runtime errors and logic errors, read a traceback from the bottom up, and fix the mistakes beginners make most often.
    • Explain code with comments
      Write comments that help a reader understand a program, and know which text Python ignores and which text it still treats as code or data.
  2. Recognize the basic kinds of values Python works with (whole numbers, decimal numbers, text and true/false values) and write each one correctly in code.
    • Tell values and types apart
      Identify the type of a value, check it with type(), and explain why the type decides what you can do with a value.
    • Write whole numbers and decimal numbers
      Write int and float literals correctly, including very large and very small numbers, and explain why float results are sometimes slightly off.
    • Write text as strings
      Create strings with single, double and triple quotes, put quotes and special characters inside them, and keep text apart from code.
  3. Use assignment to give values names, choose names that are valid and clear, and trace how the values of variables change while a program runs.
    • Assign values to variables
      Create variables with assignment statements, explain what the equals sign does in Python, and use variables in later statements.
    • Choose valid and meaningful variable names
      Follow Python's rules and style conventions for names, avoid keywords and built-in names, and pick names that say what a value means.
    • Update variables and trace a program
      Change variables with augmented assignment, swap two values correctly, and follow a program line by line with a trace table to predict its output.
  4. Build expressions with Python's arithmetic and text operators, predict their results and types, and use the order of operations and parentheses to calculate what you mean.
    • Use the arithmetic operators
      Calculate with +, -, *, /, //, % and **, and predict whether each result is an int or a float.
    • Apply the order of operations
      Predict how Python evaluates an expression with several operators, and use parentheses to make it calculate what you intend.
    • Split quantities with floor division and remainder
      Use // and % to split an amount into whole groups and a leftover, and apply them to time, money and digits.
    • Combine text and numbers in expressions
      Join and repeat strings with + and *, and predict what happens when an expression mixes integers, floats and strings.
  5. Write complete short programs that ask the user for data, convert it to the right type, calculate with it, and print clear results.
    • Convert values between types
      Use int(), float(), str() and round() to change or round a value, predict the result, and recognize the conversions that fail.
    • Display output with print()
      Show text and values with print(), control spacing and line endings with sep and end, and lay out output that is easy to read.
    • Read input and write a complete program
      Ask the user for data with input(), convert it before calculating, and combine input, processing and output into a short working program.

Python Variables study guide

5 chapters

1

Run code and understand the result

A short program is easier to understand when you know where to run it and what to expect on the screen. Start with quick experiments in the Python shell, then save a sequence of instructions so you can run it again. Learn to distinguish a calculation that stays invisible from printed output, read the clues in error messages, and leave useful comments for the next person who reads your code. That person may be you a week later.

1.1 The shell and a saved program

A program is a sequence of instructions. The Python interpreter reads Python code and carries out those instructions. Use Python 3, where a call such as print("Hello") has parentheses.

Try a line in the shell

The interactive shell, or REPL (read–evaluate–print loop), shows >>> when it is ready for Python code. Type a statement after the prompt and press Enter. You do not type the >>> yourself.

>>> 3 + 4
7
>>> "hi"
'hi'

The shell shows an expression's value automatically. It puts quotes around a string to identify it as text. A ... prompt means a statement is unfinished and Python is waiting for more. For example, an opening parenthesis may still need its closing partner. Type exit() at a ready prompt to leave the shell.

The shell is useful for testing one expression. It can keep a command history, but that history is not a saved program. Put instructions you want to run together again in a script.

Save and run a script

A script is a plain-text file of code with the .py extension. Use a code editor such as IDLE, Thonny, or VS Code. IDLE comes with the standard Python distribution. A word processor can change straight quotes into curly quotes; those curly marks cannot delimit Python strings.

Enter these lines in the editor and save the script:

print("Hello, world!")
print("Welcome to Python.")

In IDLE, choose Run → Run Module, or press F5. The output is:

Hello, world!
Welcome to Python.

Python runs these statements from top to bottom. Each print() displays its text and moves to a new line. Reversing the statements reverses the output.

You can also run a saved script from a terminal. Open the folder containing your script, then enter the interpreter command followed by its saved name. On macOS or Linux, the command is usually python3 followed by the script name; Windows commonly uses python or py. The terminal's command starts the interpreter and tells it which script to run. That command belongs at the terminal prompt, not after Python's >>>. An online editor may provide a Run button instead.

Decide what needs printing

A script containing just 3 + 4 calculates a value but displays nothing. Write print(3 + 4) to show 7. Similarly, print("hi") displays the text without its surrounding quotes. The quotes belong to the code; they mark the start and end of the text.

Python is case-sensitive. print and Print are different names, so Print("hi") produces a NameError unless that separate name has been defined. Keep the spelling and capitalization of built-in names exactly as shown.

Leading spaces also have meaning. For these simple sequences of statements, start each statement at the left margin. A stray indentation before print("hi") can cause IndentationError: unexpected indent. Spaces inside the quoted text are different: Python prints those as part of the message.

Key Takeaways

  • The shell displays expression values automatically; a script needs print() to show them.
  • Save reusable instructions as a plain-text Python script.
  • Run terminal commands in the terminal and Python statements in the shell or editor.
  • Statement order, capitalization, and leading spaces can change what happens.

1.2 Use an error message to find the next fix

A mistake in a program is a bug. Finding and fixing it is debugging. First identify what kind of problem you have: code Python cannot read, an operation that fails while running, or a result that is simply wrong.

Three kinds of problem
KindWhat happensExample
Syntax errorPython cannot read the code; the script does not start.print("hi" has an unclosed parenthesis.
Runtime errorExecution reaches an operation that fails and stops there.10 / 0 raises ZeroDivisionError.
Logic errorThe code runs but calculates the wrong result.88 + 92 / 2 is not the average of 88 and 92.

Python checks the syntax of the whole script before running it. A syntax error near the end prevents even the first line from running. A runtime error is different: earlier statements have already run, and their printed output stays visible.

For the average, division happens before addition. Python calculates 92 / 2 as 46.0, then adds 88 to get 134.0. The intended expression is (88 + 92) / 2, which gives 90.0. There is no error message because both expressions are legal. A hand calculation gives you something to compare with the program.

Read a traceback from the bottom

Suppose the code is:

name = "Ada"
print("Hello", nme)

The traceback ends with a message like NameError: name 'nme' is not defined. The last line names the error and explains what failed. Above it, Python shows the location, line number, and code. Compare nme with the name assigned earlier: name. Correcting that spelling makes the output Hello Ada.

The reported location is where Python noticed the problem. If a line looks correct, check the line before it too. An earlier missing quote or parenthesis can leave Python unable to understand what follows. Recent versions often point directly to the unmatched opening parenthesis.

Let the error type guide your search
  • NameError: Python cannot find a name, as with pirnt, Print, or a variable used before assignment. Check spelling, capitalization, and line order.
  • TypeError: the operation does not work with those types. "5" + 5 tries to join text and a number.
  • ValueError: a conversion receives unusable content. int("abc") receives text, but the text does not describe an integer.
  • ZeroDivisionError: a divisor is zero. Inspect the value used after /, //, or %.

For a SyntaxError, match every opening quote and parenthesis with a closing one. print('It's late') closes the string at the apostrophe in "It's"; use print("It's late"). Python 2 code such as print "hi" needs Python 3 parentheses: print("hi"). Retype curly quotation marks as straight ones. For unexpected indentation, remove the stray leading spaces.

Fix one problem, then run again. The first failure may have prevented Python from reaching a second one. Build a program a few lines at a time so each new failure has a small area to inspect.

Key Takeaways

  • A syntax error prevents a script from starting; a runtime error stops it after earlier lines have run.
  • Read the final traceback line for the error type, then inspect the reported code.
  • A program can run successfully and still contain a logic error.
  • Use simple expected results to check calculations.
  • Fix one error and run again before changing more code.

1.3 Comments that explain the purpose

Code tells Python what to do. A comment tells a person why the code does it or what a value means. Python ignores a comment when it runs the program.

Mark the comment clearly

A comment begins with # outside a string and continues to the end of that line. It can stand on its own or follow a statement:

# Convert a temperature from Fahrenheit to Celsius.
fahrenheit = 68
celsius = (fahrenheit - 32) * 5 / 9
print(celsius)  # Show the converted temperature.

The full-line comment explains the program's purpose. The inline comment follows code on the same line. PEP 8, Python's style guide, recommends at least two spaces before an inline # and one space after it. That spacing makes the boundary easy to see.

A hash mark inside quotes is ordinary text:

print("#1 is not a comment")  # This part is a comment.

The output is #1 is not a comment. Python reads the entire quoted string, including its hash mark, as data. It ignores the text after the later # because that mark is outside the quotes.

Explain meaning, not obvious steps

Compare these comments:

count = count + 1  # Add 1 to count.
attempts = attempts + 1  # One more failed login.

The first comment repeats an operation already visible in the code. The second adds a reason for the change. A reader now knows what an attempt counts. A clear name such as attempts also does some of the work that a vague name would leave to comments.

Useful comments explain a unit, a choice, or a purpose that the code alone does not make clear. For example, tax_rate = 0.08 # 8% sales tax connects a decimal rate with its meaning. If you later change that rate, check the comment too. A stale comment can send a reader in the wrong direction even when the code works.

Temporarily stop a line from running

To comment out a statement, put # in front of it:

print("Start")
# print("Checking this step")
print("Finish")

Only Start and Finish appear. Commenting out a line keeps it available while you test the program without it. Remove old disabled code when it no longer helps; otherwise a later reader has to guess whether it is still needed.

For a note spanning several lines, start each line with #:

# Read the temperature in degrees Fahrenheit.
# Keep the calculation in Celsius for the next step.

Triple-quoted text is different. A line such as """Convert a temperature.""" is a string expression, not a comment. Such strings can serve as documentation called docstrings in particular positions. Use # when you mean an ordinary comment. A string that nothing uses can remain invisible in a script, which can make it look like a comment even though Python reads it as a value.

Key Takeaways

  • A # outside a string begins a comment that ends at the end of the line.
  • Explain a purpose, choice, or unit that the code does not already make clear.
  • Commenting out a statement prevents it from running.
  • Update comments when the code changes.
2

Recognize and write different kinds of values

Python treats a count, a measurement, and a piece of text as different kinds of data. Their types affect both how you write them and what an operation can do with them. Learn to recognize a value from its spelling, inspect its type, and choose a useful form for a real task. Then write numbers and strings carefully, including decimal points, quotes, and special characters, so Python reads the same data you intended to give it.

2.1 Values have types

A value is a piece of data, such as 42, 3.5, or "Ada". Every value has a type, which tells Python what kind of data it is. A literal is a value written directly in code. Its spelling matters: 7, 7.0, and "7" have different types.

Four basic types
TypeKind of dataExamples
intInteger, or whole number42, 0, -7
floatFloating-point number3.5, 2.0, -0.25
strString, or text"Ada", 'hello', "42"
boolBoolean true/false valueTrue, False

A decimal point makes 2.0 a float even though its numerical value equals the integer 2. Quotes make "42" text even though the characters look like a number. The type follows the written value, not what a reader might use it for.

Boolean literals have a capital first letter and no quotes. True is a Boolean; "True" is a string. Lowercase true is a name, and using it without defining it gives NameError. A comparison can produce a Boolean: 3 < 5 evaluates to True.

Ask Python for the type

The built-in function type() reports the type of its argument. In the shell, these calls show:

>>> type(7)
<class 'int'>
>>> type(7.0)
<class 'float'>
>>> type("7")
<class 'str'>
>>> type(True)
<class 'bool'>

In a script, use print() to see those results:

print(type(42), type("42"))

This prints <class 'int'> <class 'str'>. The word class is part of Python's report; the names int and str identify the types.

Types change what operators mean

With numbers, + adds. With two strings, it joins text:

print(5 + 3)
print("5" + "3")

The first line prints 8. The second prints 53. The second expression has two text values, so Python joins their characters. It does not inspect the digit characters and decide to add them.

"5" + 5 raises TypeError: one operand is text and the other is an integer. Check types when an operation behaves differently from what you expect. In particular, the appearance of digits on the screen does not establish that the stored value is numeric.

Choose a type for the meaning

Use an integer for a count and a float for a measurement that can include a fraction. Keep an identifier such as a ZIP code as text. The string "02134" preserves the initial zero; that zero is part of the code's identity, not part of a calculation. Phone numbers can also contain punctuation worth preserving.

The shell may show 'Ada', while print("Ada") shows Ada. Both refer to the same text. The shell's quotes identify a string; print() presents the characters for a reader. Neither display changes the stored type.

Key Takeaways

  • A literal's spelling determines its type: 7, 7.0, and "7" differ.
  • type() reports the type of a value.
  • Operators use types: numeric addition and text joining are different operations.
  • Write Boolean literals as True and False, without quotes.
  • Store identifiers such as ZIP codes as strings to preserve their characters.

2.2 Numbers, decimal points, and float precision

Python has separate types for whole numbers and floating-point numbers. Writing them clearly prevents both syntax mistakes and less obvious changes to the data.

Write counts as integers

An integer has no fractional part. Write an int without a decimal point, as in 42, 0, or -7. Python's integers can grow as large as available memory allows, with no fixed-width limit. Integer addition, subtraction, and multiplication are exact. For example, 2 ** 100 gives the exact integer 1267650600228229401496703205376.

Do not use commas to group thousands. Write 1000000 or use underscores for readability: 1_000_000. The underscores do not change the value.

A nonzero decimal integer literal cannot begin with a zero. Writing 02134 is a syntax error. If those digits are an identifier whose first zero matters, write "02134" as text.

Write fractional quantities as floats

A float uses a decimal point or exponent notation. 3.5, 2.0, and -0.25 are floats. Python also accepts .5 and 5., meaning 0.5 and 5.0; writing the extra zero often makes them easier to read. Use floats for measurements such as temperature or distance and for introductory calculations with fractional prices.

Python code uses a decimal point. A comma separates values; it never marks the fractional part. For example:

x = 3.5
print(x)

prints 3.5, while x = 3,5 makes a pair of values, displayed as (3, 5). Likewise, x = 1,000 makes (1, 0), not one thousand. These statements can run, so the absence of an error message does not mean the number was written correctly.

Use scientific notation

The letter e means "times ten to the power of" in a number literal:

LiteralValue
1.5e31500.0
2.5e-30.0025
1e31000.0

An exponent literal is a float even when its value is a whole number. The negative sign after e makes a negative exponent, so 2.5e-3 means 2.5 divided by 1,000.

Expect limited precision

Floats store numbers in binary with limited precision, typically about 15–17 significant decimal digits. Many decimal fractions, including 0.1, have no exact representation in that storage. As a result:

print(0.1 + 0.2)
print(round(0.1 + 0.2, 2))

prints 0.30000000000000004 and then 0.3. The tiny difference comes from the stored approximations. round(..., 2) rounds the result to two decimal places for display; it does not change how floats store values. Keep the original calculation until the end, then round the displayed result.

A sign can also be an operator. Unary minus changes the sign of one value: -7 is negative seven. In 5 - -3, the first minus subtracts and the second makes negative three, so the result is 8. Distinguish this sign from the negative exponent in a literal such as 2.5e-3.

Key Takeaways

  • Write decimal points in code and use underscores, not commas, to group large numbers.
  • Python integers have no fixed-width limit; available memory still limits them.
  • A literal containing a decimal point or e is a float.
  • Many decimal fractions are approximate as floats; round the final displayed result.
  • Unary minus changes one value's sign.

2.3 Quotes and characters inside strings

A string is a sequence of characters: letters, digits, spaces, punctuation, and other symbols. Quotes tell Python where that sequence starts and ends. The characters inside are data, even if they look like Python code.

Choose matching quotes

Single quotes and double quotes make the same type, str. Both 'Ada' and "Ada" contain the same three characters. Start and finish a string with the same kind of quote.

Choose the outer quotes to make an inner quote easy to write:

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

The output is:

It's late
She said "hi"

In print('It's late'), the apostrophe after It closes the string too early. Python then cannot read the rest of the statement. Using double outer quotes keeps the apostrophe inside the text.

Use an escape sequence

A backslash begins an escape sequence. These common sequences each stand for one character:

Written in codeCharacter in the string
\nNewline
\tTab
\\One backslash
\'Single quote
\"Double quote

For example, print("Line 1\nLine 2") prints two lines. The backslash and n in the code together stand for a line break, not a visible letter n. Similarly, print('It\'s late') prints It's late: the escaped quote becomes a character without ending the string.

To print a literal backslash followed by a letter, write the doubled backslash. print("A\\B") displays A\B. The first backslash signals that the next backslash should be a character.

Keep line breaks or no characters

Triple quotes let one string span several physical lines. The line breaks become part of its value:

print("""Line one
Line two""")

This prints Line one and Line two on separate lines. Triple single quotes work too. Triple quotes still create a string; they do not make a # comment.

The empty string, "", has no characters. It differs from " ", which contains one space. That space may be hard to see in output, but it remains part of the data.

Tell text from an expression or name

Compare these statements:

name = "Ada"
print("3 + 4")
print(3 + 4)
print("name")
print(name)

The output is 3 + 4, then 7, then name, then Ada. Quotes make the first and third arguments literal text. Without quotes, Python evaluates a calculation or looks up a variable.

Forgetting quotes around a message such as Hello makes Python search for a name. If Hello has not been defined, print(Hello) raises NameError. Write print("Hello") when you want that word.

Strings can contain characters from many languages and symbols such as "café", "naïve", and "°F". Digits can appear alongside them: "Room 101" is text throughout. A digit character inside quotes does not become an integer.

Key Takeaways

  • Single and double quotes both create strings; the opening and closing kind must match.
  • Choose outer quotes or escapes that keep an inner quote inside the text.
  • Common escapes include \n, \t, and \\.
  • Triple quotes preserve line breaks in a string.
  • An empty string contains no characters; a space is a character.
  • Quoted text is data; unquoted names and calculations are evaluated.
3

Name values and follow their changes

Variables let a program reuse a value and give it a meaning a reader can recognize. An assignment connects a name with the result of an expression; a later assignment can change that connection. Learn how to read those steps in order, choose names that Python accepts, and distinguish a saved result from a formula that would need to run again. Trace tables make these changes visible, including the steps needed to swap two values safely.

3.1 Assignment gives a value a name

A variable is a name that refers to a value in memory. An assignment statement connects a name on the left of = with the value of an expression on the right.

Read the right side first

In age = 30, Python evaluates 30, then makes age refer to that integer. The left side must be a valid place to assign a value. 30 = age is a syntax error: you cannot assign a new value to the literal 30.

The = sign means "assign." It does not ask whether two values are equal. Equality testing uses ==. Reading assignment as a direction of work makes statements such as x = x + 1 understandable: use the old x on the right, calculate the new value, then assign it to x on the left.

Consider a rectangle:

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

After the first line, width refers to 4. After the second, height refers to 2.5. For the third line, Python looks up both current values and evaluates 4 * 2.5, producing 10.0. It assigns that result to area. The last line prints 10.0.

Assignment itself does not print the value. Use the name in a later print() call when you want to display it.

Assign before using a name

Python follows statement order. This code fails on the first line:

print(total)
total = 10

At that point, total has no value. The later assignment cannot supply a value to an earlier statement. Move total = 10 before print(total).

A shell can retain names from earlier experiments. A saved program should provide the assignments it needs in its own execution order, so its result does not depend on remembering what you typed earlier.

Reassign an existing name

Reassignment makes a name refer to a new value:

score = 10
score = 15

Now score is 15; the earlier 10 is no longer reachable through that name. For an update based on the old value:

x = 3
x = x + 1

The second line evaluates 3 + 1, then assigns 4 to x. There is no equation to solve and no contradiction.

A type belongs to the value, not permanently to the variable name. Python allows temp = 3 followed by temp = "three"; after that, type(temp) reports str. Keeping a name's meaning and expected type consistent usually makes a program easier to follow.

A copied value is not a future link
a = 5
b = a
a = 10
print(a, b)

This prints 10 5. At b = a, both names refer to the current integer 5. Reassigning a changes which value a refers to; it leaves b referring to 5. Likewise, storing width * height saves its result, not a formula that updates itself when width changes.

One statement can assign several names. a = b = 0 gives both names the value 0. In x, y = 1, 2, the values match the names by position, making x equal to 1 and y equal to 2.

Key Takeaways

  • Assignment evaluates the right-hand expression before assigning its value to the left-hand name.
  • A variable must have a value before an expression uses it.
  • Reassignment changes the value reached through a name.
  • Assigning one variable to another does not keep their future assignments linked.
  • A value has a type; the same name can later refer to a value of another type.

3.2 Names Python accepts and people understand

A name needs to satisfy Python's grammar and help a person understand the program. These are separate tests: Python can accept a name that still makes the code hard to read.

Follow the naming rules

A variable name can contain letters, digits, and underscores. It cannot start with a digit, contain a space, or use punctuation such as a hyphen.

NameWhat happens
total, item_count, price2, _tempValid names
2nd_placeInvalid: starts with a digit
first nameInvalid: contains a space
first-nameRead as subtraction, not one name

Python accepts letters from other alphabets too. English letters are a common choice for identifiers. Whatever letters you choose, keep the spelling consistent: age, Age, and AGE are three different names. Assigning age = 30 does not define Age.

Keep keywords and built-ins distinct

A keyword is reserved for Python's grammar. You cannot use it as a variable name. The hard keywords are:

False None True and as assert async await break class
continue def del elif else except finally for from
global if import in is lambda nonlocal not or pass
raise return try while with yield

You do not need to memorize the list before writing a program. For now, recognize that a name such as class is unavailable: class = 3 is a syntax error. Editors often show keywords in a special color.

Names of built-in functions, including print, input, int, str, type, sum, and max, are not keywords. Python allows you to assign to them, but that assignment hides the original function:

print = 5
print("hi")

The second line tries to call the integer 5 and raises TypeError. Choose a name describing your data, such as total, so the built-in stays available. Restarting a shell clears accidental replacements made during experiments.

Write names in a consistent style

PEP 8 recommends snake_case for variable names: lowercase words joined by underscores, as in hourly_rate and first_name. The underscore keeps a multiword name together without spaces.

A constant is a value you intend to keep unchanged. By convention, its name uses capital letters:

SALES_TAX_RATE = 0.08

Python does not lock that name. A later assignment can change it; the capitals communicate an intention to the reader.

Include meaning and units

hours_worked = 38 tells you more than h = 38. A name such as distance_miles or temp_f also identifies the unit, reducing the chance of using miles as if they were kilometers or Fahrenheit as if it were Celsius. Short names such as x and y work well for coordinates or a brief formula where their meanings are already clear.

Avoid nearly identical names such as total and totl. A typo may produce a NameError, or it may accidentally use a different existing variable. PEP 8 also discourages the single letters l, O, and I, which can look like digits. A few extra letters can make a calculation much easier to inspect.

Key Takeaways

  • Start a name with a letter or underscore, then use letters, digits, or underscores.
  • Keywords are reserved; built-in names can be reused but should be kept available.
  • Use descriptive snake_case names and include useful units.
  • Capitalized constant names communicate an intention; they do not prevent reassignment.

3.3 Updates, trace tables, and swaps

An update uses a variable's current value to calculate its next one. Following each update in order lets you predict output and find logic errors before running the program.

Start a value before updating it

count = count + 1 adds one to the old count. That change is an increment. A variable collecting a running total is an accumulator; give it a starting value such as total = 0 before adding amounts.

Augmented assignment combines an operation with assignment. For numbers, x += 3 has the same effect as x = x + 3. The available forms include +=, -=, *=, /=, //=, %=, and **=.

score = 10
score -= 3
score **= 2
print(score)

The subtraction changes score to 7. The power then changes it to 49, which is printed. Without the starting assignment, an update would try to use an undefined name and raise NameError.

The chosen operator also affects type. Starting with n = 7, n /= 2 produces the float 3.5. Starting again with n = 7, n //= 2 produces the integer 3. Python has no ++ increment operator: x++ is invalid. Writing ++x applies unary plus twice and does not update x; use x += 1.

Trace one statement at a time

A trace table records variable values after each statement. Write one column per variable and one row per step:

price = 20
quantity = 3
total = price * quantity
price = 25
total += 5
print(total, price)
Statement just runpricequantitytotal
price = 2020Not assignedNot assigned
quantity = 3203Not assigned
total = price * quantity20360
price = 2525360
total += 525365

The output is 65 25. Changing price did not repeat the earlier multiplication. The variable total held the computed value 60; it was not a spreadsheet formula linked to price. Only its own later update changed it to 65.

For a hand trace, evaluate the right side using the row immediately above, then update the assigned name. Leave all other columns unchanged. Compare the prediction with the program's real output.

Preserve both values in a swap

Suppose a = 1 and b = 2. The attempt a = b followed by b = a gives 2 2. The first assignment loses access to the original a through that name, so the second line copies the new value back.

A temporary variable keeps the original value available:

a = 1
b = 2
temp = a
a = b
b = temp
print(a, b)

This prints 2 1. You can also write a, b = b, a. Python evaluates both values on the right before assigning either name on the left, so the original values are both available for the swap. Trace the temporary-variable version when you want to see exactly where each original value is preserved.

Key Takeaways

  • An augmented assignment needs an existing value.
  • Use += 1 for an increment; ++ does not update a Python variable.
  • A trace table records values after each statement.
  • Changing an input variable does not recalculate an earlier saved result.
  • The operator in an update can change the resulting type.
  • A swap needs both original values: preserve one temporarily or use simultaneous assignment.
4

Build calculations with the right operators

An expression combines values into a result. Python uses familiar arithmetic ideas, but you must write multiplication, powers, and division with the right symbols. Learn how operator order controls a calculation, how floor division and remainder split quantities, and how types change the meaning of addition and multiplication. Working through expressions in small steps helps you see whether the result, its type, and its meaning all match your intention.

4.1 Arithmetic symbols and result types

An expression evaluates to one value. It can be a single literal, a variable, or a combination such as 2 + 3. The + is an operator; the values it acts on are its operands.

Choose the operator

Python's arithmetic operators work as follows:

OperationExpressionResult
Addition7 + 29
Subtraction7 - 25
Multiplication7 * 214
Division7 / 23.5
Floor division7 // 23
Remainder7 % 21
Power7 ** 249

Write multiplication explicitly with *. Math notation such as 2x does not work as Python multiplication. Write 2 * x or 2 * (x + 1). With x = 1, 2(x + 1) tries to call the integer 2 as if it were a function and raises TypeError.

The power operator is **, not ^. For example, 7 ** 2 is 49, while 7 ^ 2 is 5 because the caret performs a different operation. A program can therefore run while calculating a result you did not intend.

Predict the type as well as the number

Division with / gives a float for integer operands even when the division is exact: 6 / 2 is 3.0. For an integer whole-group count, use //: 6 // 2 is 3.

With two integer operands, addition, subtraction, multiplication, floor division, and remainder give integer results. Nonnegative integer powers do too: 2 ** 10 gives the exact integer 1024. A negative exponent changes this: 2 ** -1 gives the float 0.5.

In ordinary arithmetic with an integer and a float, the calculation uses floating-point values. 3 + 4.0 gives 7.0; 7.0 // 2 gives 3.0. Floor division describes how the quotient is rounded, not a promise that its type is always int.

A fractional power can calculate a root of a positive number. 4 ** 0.5 gives 2.0, and 2 ** 0.5 gives approximately 1.4142135623730951.

Build a calculation from named values

A car travels 287 miles using 10.25 gallons:

miles = 287
gallons = 10.25
mpg = miles / gallons
print("Miles per gallon:", mpg)

The division calculates 28.0, so the output is Miles per gallon: 28.0. The names identify the quantities, and the printed label identifies the result's unit. Multiplying 28.0 * 10.25 recovers 287 miles, providing a check on the division.

A zero divisor fails for /, //, and %. For example, 10 / 0 raises ZeroDivisionError. Inspect a variable used as the divisor when that error occurs.

Spaces around operators do not change their meaning: 2+3 and 2 + 3 both give 5. Spaces around = and most operators make the parts easier to read. They cannot replace an operator; 2 x still does not mean multiplication.

Key Takeaways

  • Use * for multiplication and ** for powers.
  • / gives a float when dividing integers, even for an exact quotient.
  • // with two integers gives an integer; a float operand gives a float result.
  • A negative integer exponent produces a float result.
  • /, //, and % raise ZeroDivisionError for a zero divisor.

4.2 Order operations and group formulas

Python does not simply calculate an expression from its left edge to its right edge. Precedence sets which operations happen first. Parentheses let you choose a different grouping or make the intended grouping clear.

Apply the levels in order

For the operators introduced here, use this order:

  1. Parenthesized expressions.
  2. Powers, **.
  3. Unary signs, such as the minus in -x.
  4. Multiplication and division operations: *, /, //, %.
  5. Addition and subtraction: +, -.

For 3 + 4 * 2 ** 2, evaluate 2 ** 2 to get 4. The expression becomes 3 + 4 * 4. Multiplication gives 16, and addition gives 19. With (3 + 4) * 2 ** 2, the parenthesized sum is 7; the power is 4; the product is 28.

Operators on the multiplication/division level have equal priority. Work from left to right: 8 / 2 * 4 means (8 / 2) * 4, giving 16.0. Multiplication does not jump ahead of division. Likewise, 100 / 10 / 5 gives 2.0, and 10 - 4 - 3 gives 3.

Handle powers and signs carefully

Repeated powers group from right to left. 2 ** 3 ** 2 means 2 ** (3 ** 2). First 3 ** 2 gives 9; then 2 ** 9 gives 512. Grouping from the left would give 64, a different result.

A leading minus sign is applied after a following power: -2 ** 2 means -(2 ** 2) and gives -4. In (-2) ** 2, parentheses make negative two the base, so the result is 4. A minus after ** can belong to the exponent: 2 ** -1 gives 0.5.

Translate the whole grouping of a formula

An average requires adding both values before dividing by two:

average = (88 + 92) / 2

The sum is 180, then division gives 90.0. Without parentheses, 88 + 92 / 2 divides only 92 and gives 134.0.

A fraction bar also groups everything above and below it. A numerator containing a + b and a denominator containing c + d become (a + b) / (c + d). Leaving out either pair can change which terms are divided.

The same issue appears in a temperature conversion:

celsius = (98.6 - 32) * 5 / 9

The subtraction gives 66.6, multiplication gives 333.0, and division gives 37.0. Without the grouping, 98.6 - 32 * 5 / 9 gives 80.82222222222222.

Use the right grouping marks

Round parentheses group an expression. Square brackets and curly braces have other meanings in Python. For example, [2 + 3] * 4 produces [5, 5, 5, 5], not 20.

Parentheses around an operation that would happen first anyway leave the result unchanged: (2 * 3) + 1 and 2 * 3 + 1 both give 7. Parentheses that change the grouping can change the value: 2 * (3 + 1) gives 8. Add grouping where it makes the calculation's meaning easier to see.

Key Takeaways

  • Evaluate parentheses, powers, unary signs, multiplication/division operations, then addition/subtraction.
  • Work left to right within a level, except that powers group right to left.
  • A leading minus differs from a negative base: -2 ** 2 and (-2) ** 2 differ.
  • Group a whole numerator and denominator when translating a fraction.
  • Use round parentheses for grouping calculations.

4.3 Whole groups and the leftover

Floor division and remainder answer two related questions: how many whole groups fit, and what remains after taking those groups. For nonnegative integer quantities, the pair is useful for time, money, packing, and digits.

Find the quotient and remainder together

17 // 5 gives 3, the number of full groups of five. 17 % 5 gives 2, the amount left over. The two results reconstruct the starting quantity:

print((17 // 5) * 5 + 17 % 5)

The expression gives 17: three groups of five plus two. More generally, for integers and a nonzero divisor, (a // b) * b + a % b equals a. Use that relationship to check both answers.

Split real quantities

For 135 minutes:

hours = 135 // 60
minutes = 135 % 60

There are 2 whole hours and 15 minutes left. The divisor is 60 because one hour contains 60 minutes. Dividing with / gives 2.25, which expresses fractional hours; it does not separately give the minutes left over.

The same structure works with a different group size:

QuantityFull groupsLeftover
347 cents, 100 cents per dollar347 // 100 gives 3 dollars347 % 100 gives 47 cents
75 eggs, 12 per carton75 // 12 gives 6 full cartons75 % 12 gives 3 eggs

The carton count is the number of full cartons. If you need a container for the leftover eggs too, that is a different question from how many full groups fit.

Use place value and parity

For a positive integer, dividing by ten separates its last digit. 1234 % 10 gives 4, and 1234 // 10 gives 123. Recombining 123 * 10 + 4 recovers 1234.

For any integer n, n % 2 is 0 when it is even and 1 when it is odd. This also works for negatives: -7 % 2 is 1. For integers and a positive divisor b, the remainder is in the range from 0 through b - 1.

Understand negative division

Floor division rounds down toward negative infinity, not toward zero. Since negative seven divided by two is negative 3.5, -7 // 2 gives -4. The remainder is then 1, because -4 * 2 + 1 equals -7.

A nonzero remainder has the divisor's sign. With a negative divisor, 7 % -2 gives -1, and 7 // -2 gives -4. These still reconstruct the original: -4 * -2 + -1 is 7.

This differs from converting a quotient with int(): int(-7 / 2) gives -3 because conversion truncates toward zero.

Both operators also accept floats. 7.5 // 2 is 3.0, and 7.5 % 2 is 1.5. They share the precedence level of * and /, so 5 * 3 + 17 % 5 gives 17. The % operator here means remainder, not percent: calculate 8 percent of a price with price * 0.08 or price * 8 / 100.

Key Takeaways

  • // gives a floored quotient; % gives the corresponding remainder.
  • For integers, (a // b) * b + a % b reconstructs a when b is nonzero.
  • Choose a divisor that matches the group size or unit conversion.
  • Floor division rounds negative quotients down, not toward zero.
  • A nonzero remainder has the divisor's sign.
  • Remainder is different from a percentage.

4.4 Join text, repeat text, and check types

An operator's symbol is only part of its meaning. Python also uses the types of its operands. The + and * operators work with strings, but they perform text operations there.

Join strings with plus

Concatenation joins one string to the end of another:

print("ab" + "cd")
print("Hello" + "Ada")
print("Hello " + "Ada")

These lines print abcd, HelloAda, and Hello Ada. Concatenation adds no space by itself. The space in the third result comes from the final character of "Hello ".

Digit characters follow the same rule: "5" + "3" gives the string "53". Without quotes, 5 + 3 gives the integer 8. Choose numeric values when you mean arithmetic and strings when you mean text.

Repeat a string with multiplication

A string multiplied by an integer repeats its characters. "3" * 2 gives "33", while 3 * 2 gives 6. The repetition count can go on either side: 3 * "ab" gives "ababab". Repeating zero times gives the empty string, so "ab" * 0 is "".

A repetition count must be an integer. "ab" * 2.5 raises TypeError, as does "ab" * "cd". There is no fractional number of copies in this operation.

Combine operations in order

Multiplication has higher precedence than addition for these expressions too:

print("-" * 4 + "Menu" + "-" * 4)

First, each repetition creates "----". Then the additions join the three strings, producing ----Menu----. The order of the joins preserves the order of their characters.

For a calculation that becomes part of a string:

print("7" + str(3 * 2))

The inner arithmetic gives the integer 6. str(6) creates the string "6". Finally, concatenation produces "76". It does not produce 13, because the final + has two strings as operands.

Resolve incompatible types deliberately

"Age: " + 30 raises TypeError. Convert the integer before concatenating:

print("Age: " + str(30))

This produces Age: 30. Alternatively, print("Age:", 30) displays the two values with a space between them. That is the behavior of print() with separate arguments, not text addition.

Integers and floats can mix in ordinary arithmetic: 2 * 3.0 gives the float 6.0. Python does not similarly turn a numeric string into a number during +. If you need to calculate with "30", convert it to a numeric type first.

Subtraction does not work on these string operands. "10" - 3 raises TypeError, even though the characters 10 could describe a number. To predict a mixed expression, identify each operand's type, evaluate the higher-priority operations, and check the types again at the next operation. A conversion can change which rule the next operator follows.

Key Takeaways

  • String + joins characters without adding spaces.
  • String * repeats text an integer number of times.
  • For text joining, convert a number with str() or pass it separately to print().
  • Follow both precedence and operand types when tracing a mixed expression.
5

Read data, convert it, and display useful output

A complete program needs a way to receive data and report a result. Input arrives as text, so decide whether the program needs to keep that text or convert it into a number. Carry out the calculation with values of the right types, then show the result with a clear label and useful spacing. Conversions, rounding, and the options of print() let a short program turn typed answers into output that someone can understand and check.

5.1 Conversions create new values

Type conversion, also called casting, creates a value of a different type. The functions int(), float(), and str() let you choose the form needed by the next operation.

Keep the converted result
x = "42"
int(x)
print(type(x))

This still prints <class 'str'>. The conversion created an integer, but no assignment kept it. Write x = int(x) to make x refer to that integer, or assign it to a different name when you want to keep both forms.

Choose a numeric conversion

int() accepts a whole-number string, including an optional sign and surrounding spaces. int("42"), int("-12"), and int(" 42 ") produce 42, -12, and 42.

A decimal point in a string prevents direct integer conversion. int("3.5") and int("4.0") raise ValueError; so do int("abc") and int(""). The fact that 4.0 is mathematically whole does not make "4.0" an integer-form string.

float() accepts decimal text and exponent notation. float("3.5") gives 3.5, float("3") gives 3.0, and float("1e3") gives 1000.0. It also converts integers: float(7) gives 7.0. A decimal comma fails: float("3,5") raises ValueError.

Truncate or round on purpose

Converting a float to int drops its fractional part toward zero. int(3.99) gives 3, and int(-3.99) gives -3. It does not choose the nearest integer. To convert decimal text and then truncate, use int(float("3.5")), which gives 3.

round() chooses a nearest value. round(3.7) gives the integer 4; round(3.14159, 2) gives the float 3.14. The second argument sets the decimal places.

At an exact halfway point, Python chooses the even neighbor: round(2.5) gives 2, while round(3.5) gives 4. Decimal fractions stored as floats may not be exact halfway values. round(2.675, 2) gives 2.67 because of its binary representation.

ExpressionResultReason
int(-3.5)-3Truncate toward zero
round(-3.5)-4Nearest integer; tie goes to even
-7 // 2-4Floor the quotient downward

These operations answer different questions. Pick the operation that matches the intended result, especially when negative values are possible.

Convert to text for joining

str(42) produces "42", and str(3.0) produces "3.0". After conversion, + joins their characters:

print("7" + "3")
print(int("7") + int("3"))
print(str(7) + str(3))
print(float("7") + 3)

The outputs are 73, 10, 73, and 10.0. The conversions decide whether the final + receives text or numbers.

A ValueError points to unsuitable content for a conversion, such as int("abc"). A TypeError points to an operation incompatible with its operands, such as "5" + 5. Use that difference to decide whether to inspect the input text or change the operation.

Key Takeaways

  • A conversion returns a new value; assign it if you need to keep it.
  • int() truncates floats toward zero and requires whole-number text for direct string conversion.
  • float() accepts decimal-point and exponent text.
  • round() uses the nearest value and resolves exact ties toward even.
  • str() supplies text for concatenation.
  • ValueError and TypeError identify different kinds of failure.

5.2 Control what print() displays

print() displays values for a person to read. Its arguments are the values or expressions inside its parentheses. Commas separate the arguments; Python evaluates them before displaying their results.

Display values with useful labels
print("Total:", 5)
print(3 + 4)
print("3 + 4")

The lines show Total: 5, 7, and 3 + 4. A label tells the reader what a value means. An unquoted calculation is evaluated; a quoted expression is displayed as text.

By default, print() puts one space between arguments and finishes with a newline. It converts each value for display, so print("Total:", 5) can mix text and an integer without an explicit str().

Compare print("Total:" + str(5)), which prints Total:5. Here the + builds one string before print() receives it. Concatenation supplies no automatic space, and there is only one argument to display.

Set the separator

The named argument sep sets the text placed between arguments:

print("a", "b", sep="-")
print(1, 2, 3, sep=", ")
print("A", 12, sep="")

The output is:

a-b
1, 2, 3
A12

Use the name sep. Writing print("a", "b", "-") supplies a third value, so the result is a b -. An empty separator joins the displayed arguments directly; it does not remove spaces already inside their strings.

Set the ending

The named argument end changes what follows the last value. It is a newline by default. An empty ending keeps the next output on the same line:

print("a", end="")
print("b")

This shows ab on one line. You can include punctuation and a newline together:

print("Hello,", "Ada", end="!\n")

The output is Hello, Ada! followed by a new line. sep applies between arguments within one call; end applies after that call's final argument. They control different locations.

Add line breaks and choose displayed precision

Calling print() with no arguments prints an empty line. A \n inside a string creates a line break within that string, as in print("Line 1\nLine 2"). Repeated text can form a separator: print("=" * 20) displays twenty equals signs.

Python displays a float in a short form that represents its stored value. print(1 / 3) shows 0.3333333333333333. To display a rounded value, calculate it first inside the call: print(round(1 / 3, 2)) shows 0.33.

Rounding does not promise a fixed number of visible decimal places. round(2.50, 2) displays as 2.5, because the float does not store trailing zeros as a display instruction. Use the output exactly as Python produces it when checking a program.

Key Takeaways

  • print() evaluates its arguments and displays strings without their surrounding quotes.
  • The defaults are one space between arguments and a newline at the end.
  • sep changes the space between arguments; end changes what follows the final argument.
  • print() with no arguments adds an empty line.
  • Rounding changes a value's precision, not a fixed count of printed decimal places.

5.3 Build and test an input–process–output program

input() displays a prompt, waits for someone to type and press Enter, then returns the typed text as a string without the Enter. A complete short program reads the needed data, processes it, and displays a result.

Read text and convert numbers
name = input("What is your name? ")
print("Hello", name)

The space at the end of the prompt separates the typed answer from the question. The variable stores text exactly as text, even when the user types digits. Typing 30 into input() produces "30", not the integer 30.

Choose a conversion before arithmetic:

age = int(input("Age in whole years: "))
print("Next year:", age + 1)

The inner input() runs first. If the user types 30, it returns "30"; int() converts that to 30; the assignment keeps the integer. The addition then produces 31.

Use float(input(...)) when fractional values are allowed. A prompt should say what kind of answer is expected. Entering 2.5 or thirty for an int() conversion raises ValueError. Entering 98,6 for a float() conversion also fails; the decimal separator must be a point.

Missing conversion does not always raise an error. If two input calls receive 5 and 3, their unconverted values add as strings and produce 53. Both operands have a type that supports +, but it is the wrong operation for adding quantities.

Work through a complete calculation

The input–process–output pattern keeps the main stages easy to inspect:

# Convert a temperature from Fahrenheit to Celsius.
fahrenheit = float(input("Temperature in °F: "))
celsius = (fahrenheit - 32) * 5 / 9
print(fahrenheit, "°F is", round(celsius, 1), "°C")

With input 98.6, the program reads the float 98.6. It subtracts 32 to get 66.6, multiplies by 5 to get 333.0, and divides by 9 to get 37.0. The displayed line is 98.6 °F is 37.0 °C. Input 50 becomes 50.0, so the line is 50.0 °F is 10.0 °C.

Here is a program with integer data:

total_minutes = int(input("Enter a whole number of minutes: "))
hours = total_minutes // 60
minutes = total_minutes % 60
print("Hours:", hours, "Minutes:", minutes)

Input 135 produces Hours: 2 Minutes: 15. The labels work for zero, one, and larger results without changing the wording. The two processing lines use the same original total; assigning hours does not remove anything from total_minutes.

Test ordinary and boundary values

Choose inputs with answers you can calculate by hand. For the temperature program, 32 should produce 0.0 °C and 212 should produce 100.0 °C. For minutes, test 0, 59, and 60: these check the starting value and the change from no full hour to one full hour.

Also test a typical value such as 135. Compare the exact labels, spacing, numerical results, and types with your prediction. If the code runs but the result is wrong, trace the stored values and the order of operations. If a conversion fails, inspect the typed text and the type your prompt requests.

Key Takeaways

  • input() returns text, including when a user types digits.
  • Convert input before doing numeric calculations.
  • Use clear prompts and label the output.
  • Separate reading data, calculating, and displaying the result.
  • Test ordinary values and boundaries against hand-calculated answers.

Python Variables examples

5 Walkthroughs

1

Run a small program and repair it

13 steps
Move between the shell and a saved script, read a failure, and explain a line with a comment.
  1. 1
    IntroductionStart with a visible prediction

    A program can calculate a value without showing it. Before running code, predict two things: what Python will do and what a person will see.

    We will first compare a shell experiment with a saved script. Then we will inspect errors and comments. Keep the distinction between code execution and visible output in mind: a line can run successfully while producing no text on the screen.

  2. 2
    ExampleTry one expression in the shell

    At the Python shell's >>> prompt, enter 9 * 3. Python evaluates the expression and displays 27 automatically.

    The prompt is supplied by the shell; you type only the expression. A prompt of ... means Python is waiting for more of the same statement. The shell is convenient for a quick check like this, while a saved script keeps a sequence ready to run again.

  3. 3
    ExplanationMake a script show its calculation

    A script with only 9 * 3 evaluates the product but displays nothing. To show it, write:

    print(9 * 3)
    print("Calculation finished")
    

    The output is 27, then Calculation finished on the next line. The interpreter follows the statement order. Run the script through the editor's Run command or a terminal command; do not type that terminal command at the Python prompt.

  4. 4
    ChallengePredict what is actually shown

    A saved script contains these two lines. What is displayed?

    11 + 5
    print("Ready to check")
    

    ---reveal---

    Only Ready to check appears. The first line calculates 16 but does not print it. If you entered that first expression directly in the interactive shell, the shell would display its value automatically. The difference comes from where the expression is run.

  5. 5
    ExplanationSeparate a stopped run from a wrong answer

    A syntax error means Python cannot read the script, so execution never starts. A runtime error happens after execution has started and stops it at the failing operation.

    A logic error can run without a message. For example, a wrong grouping in a formula still produces a legal calculation. Compare its result with a hand calculation instead of waiting for Python to identify the mistake.

  6. 6
    ExampleRead the final error line first

    Consider this code:

    distance = 21
    print(distnace)
    

    A traceback ends by identifying NameError and the undefined name distnace. Read that final message, then inspect the reported line above it. The name assigned earlier is distance; the two spellings differ. Correct the lookup to print(distance), which displays 21.

  7. 7
    TipChoose the next useful check

    Let the error type narrow your search. For NameError, check spelling, capitalization, and whether the variable was assigned earlier. For TypeError, inspect the types used by the operation. For ValueError, inspect the text given to a conversion.

    If the reported line seems correct, check the preceding line for an unclosed quote or parenthesis. Fix one error and run again to find the next reachable problem.

  8. 8
    ChallengeDoes the first message survive?

    What is printed before this program stops? items has not been assigned.

    print("Checking")
    print(items)
    print("Finished")
    

    ---reveal---

    Checking is printed. The next line raises NameError, leaving the final line unexecuted. This is a runtime failure: Python could read the script, but could not look up a value during execution. Earlier output remains visible.

  9. 9
    ExplanationAdd the meaning a reader needs

    A comment starts with # outside a string and continues to the line's end. It can explain the reason for a value:

    service_rate = 0.03  # 3% processing fee
    

    The comment tells a reader what the rate represents. Python ignores it when running the assignment. Leave at least two spaces before an inline comment marker and a space after it. A clear name and a useful comment work together.

  10. 10
    ChallengeLocate the comment boundary

    What does this line print, and which words are ignored by Python?

    print("Order #16")  # Packing label
    

    ---reveal---

    It prints Order #16. The hash mark inside the quotes belongs to the string. The second hash mark starts the comment, so Packing label is ignored. A character's position inside or outside a string changes how Python reads it.

  11. 11
    TipKeep a comment true after editing

    If the processing fee changes from 3 percent to 5 percent, change both service_rate to 0.05 and the comment to 5% processing fee.

    Python will not warn you about a stale comment because comments are not executed. A reader can still be misled by it. For temporary testing, # can disable a statement; remove old disabled lines when they no longer help you understand the program.

  12. 12
    ChallengeCombine output, comments, and a failure

    What appears when this saved script runs? Assume no names were defined earlier.

    print("Status #1")  # Show the status.
    Print("Done")
    

    ---reveal---

    The comment is ignored, and Status #1 is printed. Print then raises NameError because Python distinguishes uppercase and lowercase names. The built-in is print. The valid first output stays visible because the failure occurs during execution.

  13. 13
    RecapUse the output as evidence

    The shell displays expression values, while a script needs an explicit output call. A runtime failure leaves earlier output visible; a syntax error prevents the script from starting.

    For your next short program, write an expected output before running it. If the prediction fails, use the error type or a trace of the values to choose the next check. Keep comments focused on meaning that the code does not already explain.

2

Read the type from a value's spelling

14 steps
Compare literals, inspect types, and build strings with the characters you intend.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionSimilar-looking values can behave differently
  2. 2
    ExampleInspect three forms of the same digits
  3. 3
    ConnectionChoose data for its purpose
  4. 4
    ChallengeDistinguish Boolean text from a Boolean
  5. 5
    ExplanationScale a float with exponent notation
  6. 6
    Key InsightA comma changes the data
  7. 7
    ChallengeWrite a small decimal value
  8. 8
    TipInterpret the small extra digits
  9. 9
    ExampleChoose outer quotes that fit the message
  10. 10
    ExplanationMake a line break part of a string
  11. 11
    ChallengePredict quoted and unquoted names
  12. 12
    Key InsightA space still counts as data
  13. 13
    ChallengeFollow spelling into behavior
  14. 14
    RecapCheck the value before the operation
3

Follow a value through assignments

14 steps
Read assignments, improve names, and trace updates and swaps without losing an old value.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionTrack one moment at a time
  2. 2
    ExampleEvaluate first, assign second
  3. 3
    Key InsightA stored result does not keep a formula
  4. 4
    ChallengeTrace a copy before reassignment
  5. 5
    ConnectionChoose a readable name
  6. 6
    ExampleKeep built-in names available
  7. 7
    ChallengeRepair a name without changing its meaning
  8. 8
    ExplanationUpdate from an existing value
  9. 9
    ExampleWrite down only what changed
  10. 10
    ChallengeWatch an update change the type
  11. 11
    ExplanationKeep an original before overwriting it
  12. 12
    ExplanationRead a simultaneous swap
  13. 13
    ChallengeCombine names, copies, and updates
  14. 14
    RecapTrace current values, not intentions
4

Evaluate expressions one operation at a time

18 steps
Choose arithmetic and string operations, apply grouping, and split quantities into full groups and leftovers.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionFollow both order and type
  2. 2
    ExplanationMatch the symbol to the operation
  3. 3
    ExampleKeep the type beside the quotient
  4. 4
    ChallengeSelect a power and its result
  5. 5
    ExampleWork the highest-priority operation first
  6. 6
    Key InsightEqual priority means left to right
  7. 7
    ExplanationPowers group in the other direction
  8. 8
    ChallengeRepair a grouped calculation
  9. 9
    ExampleSplit a quantity into full groups
  10. 10
    ExplanationFloor means down, including below zero
  11. 11
    ConnectionUse digits as groups of ten
  12. 12
    ChallengeFind both pieces of the time
  13. 13
    ExplanationText uses the same symbols differently
  14. 14
    ExampleBuild a border before joining it
  15. 15
    ChallengeConvert the inner result to text
  16. 16
    TipLocate an incompatible operation
  17. 17
    ChallengeCombine remainder, power, and text
  18. 18
    RecapCheck the intermediate result
5

Turn typed data into a checked result

15 steps
Choose conversions, control output, and build a program that separates reading, calculation, and display.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead, calculate, then explain the result
  2. 2
    ExplanationKeep the new value from a conversion
  3. 3
    ExampleA float and decimal text convert differently
  4. 4
    ChallengeSeparate truncating from rounding
  5. 5
    ExplanationPass separate values to print
  6. 6
    ExampleChange the separator and the ending
  7. 7
    ChallengePredict two print calls together
  8. 8
    TipRound a value without promising padded text
  9. 9
    ExampleRead a whole-number input
  10. 10
    ExampleCalculate two results from the same total
  11. 11
    ExampleLabel the final values
  12. 12
    ChallengeFind the missing conversion
  13. 13
    ConnectionTest the place where the answer changes
  14. 14
    ChallengeCombine conversion, division, and output
  15. 15
    RecapCheck each stage separately

Python Variables practice questions

50 Practice Questions in 5 sets

Set 1: Work with changing values and typed data10 Practice Questions

Question 1 of 10

What does this display?

print("Bay #7")  # Pickup point
  1. Bay
  2. Bay #7
  3. Bay #7 Pickup point
  4. Bay Pickup point
Show answerHide answer
Answer: B
The hash mark inside "Bay #7" is part of the string, so it appears in the output. The later hash mark is outside the quotes and starts a comment, which Python ignores. Treating the first hash mark as a comment would cut off text that is still inside a string.

Question 2 of 10

A badge ID is "00482" and will not be used in calculations. What type best preserves it?
  1. An integer
  2. A float
  3. A Boolean
  4. A string
Show answerHide answer
Answer: D
A string preserves all five digit characters, including the leading zeros. Converting the badge ID to an integer would keep the numerical quantity 482 but lose those initial zeros. The identifier describes a label, so retaining its exact characters matters more than supporting arithmetic.

Question 3 of 10

What value does cost have at the end?

units = 6
rate = 4
cost = units * rate
units = 8
  1. 24
  2. 32
  3. 8
  4. 6
Show answerHide answer
Answer: A
cost receives the result of 6 * 4, which is 24. Changing units afterward does not execute the multiplication again, so cost stays unchanged. The value 32 would require another assignment such as cost = units * rate after the new quantity is assigned.

Question 4 of 10

What does this print?

points = 12
points -= 5
points *= 3
print(points)
  1. 7
  2. 31
  3. 21
  4. 36
Show answerHide answer
Answer: C
The first update changes points from 12 to 7. The next update uses that current value and multiplies it by 3, giving 21. A result of 31 would multiply the original 12 by 3 before subtracting 5; that reverses the order of the two separate updates.

Question 5 of 10

What value and type does the literal 6e2 have?
  1. 600, an integer
  2. 6.2, a float
  3. 600.0, a float
  4. 62, an integer
Show answerHide answer
Answer: C
e2 means multiply by ten to the power of two, so the value is 600.0. An exponent in a numeric literal makes the literal a float even when its value is whole. Reading the e as a decimal point would give 6.2, but exponent notation changes the scale by a power of ten.

Question 6 of 10

A tray holds 8 rolls. A baker has 53 rolls. How many full trays and leftover rolls are there?
  1. 6 full trays and 5 rolls
  2. 6 full trays and 6 rolls
  3. 7 full trays and 3 rolls
  4. 5 full trays and 6 rolls
Show answerHide answer
Answer: A
53 // 8 gives 6 full trays, and 53 % 8 gives 5 leftover rolls. The check 6 * 8 + 5 recovers all 53 rolls. Seven trays would include a partly filled tray; it is not the number of full trays requested, and seven full trays would need 56 rolls.

Question 7 of 10

What does print("Go" * 2 + "!") display?
  1. Go Go!
  2. Go!Go!
  3. Go2!
  4. GoGo!
Show answerHide answer
Answer: D
Multiplication repeats the string "Go" twice to form "GoGo"; the final addition joins "!", producing GoGo!. Repetition does not insert a space between copies. The exclamation mark is added after the repeated part, so it occurs once rather than after each copy.

Question 8 of 10

What is the result of int(-8.9)?
  1. -9
  2. -8
  3. 8
  4. -8.0
Show answerHide answer
Answer: B
int() removes the fractional part toward zero, so int(-8.9) produces the integer -8. It does not round to the nearest integer or floor the value. The tempting result -9 would follow rounding this number to the nearest integer, not integer conversion.

Question 9 of 10

What appears on the first output line?

print("P", "Q", sep=":", end="|")
print("R", "S", sep="-")
  1. P:Q| R-S
  2. P:Q:R-S
  3. P-Q|R:S
  4. P:Q|R-S
Show answerHide answer
Answer: D
The first call joins its arguments with : and ends with |, leaving the cursor on the same line. The second call writes R-S immediately afterward and then a newline. No extra space appears between calls: sep only separates arguments within its own call.

Question 10 of 10

A user types 7 at the first prompt and 4 at the second. What does this program print?

first = input("First: ")
second = input("Second: ")
print(int(first + second) + 2)
  1. 76
  2. 13
  3. 742
  4. 11
Show answerHide answer
Answer: A
Both inputs are strings, so first + second forms "74" before any conversion. int("74") gives 74, and adding 2 gives 76. The result 13 would require converting each input before adding them; converting their joined text is a different operation.
Set 2: Read short programs and predict their results10 Practice Questions

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

Question 1 of 10

A saved script contains only 18 - 6. What appears when it runs?
  1. The number 12 appears.
  2. The expression 18 - 6 appears.
  3. Nothing is displayed.
  4. A syntax error appears.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A script contains this code. What output appears before it stops?

print("Ready")
print(missing_total)
print("Done")

missing_total has not been assigned.

  1. Only Ready
  2. Ready and Done
  3. No output at all
  4. Only Done
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

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

Save this lesson to see this answer.

Question 4 of 10

What Python expression calculates five to the third power?
  1. 5 ^ 3
  2. 5 ** 3
  3. 5 * 3
  4. 5 + 3
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does print("North\nSouth") display?
  1. North\nSouth on one line
  2. North and South on separate lines
  3. North South on one line
  4. NorthnSouth on one line
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does this print?

stock = 14
saved = stock
stock = 9
print(stock, saved)
  1. 9 9
  2. 14 9
  3. 14 14
  4. 9 14
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What is a valid snake_case variable name for a count of available seats?
  1. available_seats
  2. available-seats
  3. 2available_seats
  4. available seats
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What value and type does 24 / 6 produce?
  1. 4, an integer
  2. 0, an integer
  3. 4.0, a float
  4. 0.0, a float
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What value does 40 - 18 / 3 * 2 + 1 produce?
  1. 29.0
  2. 38.0
  3. 15.666666666666666
  4. 28.0
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What does print("Zone", 4, sep="-") display?
  1. Zone 4
  2. Zone4-
  3. Zone 4 -
  4. Zone-4
Show answerHide answer

Save this lesson to see this answer.

Set 3: Trace expressions and diagnose errors10 Practice Questions

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

Question 1 of 10

In a fresh Python shell, you enter amount = 11, then amount + 4. What does the shell display for these two entries?
  1. 11 for assignment, then 15
  2. Nothing for either entry
  3. 11 for assignment, then amount + 4
  4. Nothing for assignment, then 15
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A script contains this code. What output appears before the error message?

print("Loading")
value = 6
print("Value:", value
  1. Only Loading appears.
  2. No output appears.
  3. Loading and Value: 6 appear.
  4. Only Value: 6 appears.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What is a correct Python literal for the integer two million five hundred thousand?
  1. 2,500,000
  2. 2.500.000
  3. 2_500_000
  4. 2_500_000.0
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does print('He said "yes"') display?
  1. He said "yes"
  2. He said yes
  3. 'He said "yes"'
  4. He said 'yes'
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A programmer writes MAX_ATTEMPTS = 5. What do the capital letters communicate?
  1. Python will reject any later assignment.
  2. The variable can hold only integers.
  3. The name is a reserved Python keyword.
  4. The value is intended to stay unchanged.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What does this print?

a = 4
b = 9
a, b = b, a
a += b
print(a, b)
  1. 18 9
  2. 13 4
  3. 13 9
  4. 9 13
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What value does (-3) ** 2 + 2 ** 3 produce?
  1. 17
  2. -1
  3. 25
  4. 15
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What are the values of -17 // 5 and -17 % 5, in that order?
  1. -3 and -2
  2. -4 and -3
  3. -4 and 3
  4. -3 and 2
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What happens when Python evaluates int("12.0")?
  1. It returns the integer 12.
  2. It raises ValueError.
  3. It returns the float 12.0.
  4. It raises TypeError.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A user types 84.5. The program should convert Fahrenheit to Celsius. What replacement for the calculation line fixes its result?

fahrenheit = float(input("Temperature in °F: "))
celsius = fahrenheit - 32 * 5 / 9
print(round(celsius, 1))
  1. celsius = fahrenheit - (32 * 5 / 9)
  2. celsius = (fahrenheit - 32 * 5) / 9
  3. celsius = (fahrenheit - 32) * 5 / 9
  4. celsius = fahrenheit - 32 * (5 / 9)
Show answerHide answer

Save this lesson to see this answer.

Set 4: Choose the operation that matches the task10 Practice Questions

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

Question 1 of 10

A script contains the lines below. What message appears?

# print("Check")
print("Open #2")
  1. Open #2
  2. Check and Open #2
  3. Open
  4. Check and Open
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What value and type does 3 + 2.0 produce?
  1. 5, an integer
  2. "32.0", a string
  3. 5.0, a float
  4. "5.0", a string
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

After label = "Desk", what does print("label", label, sep=":") display?
  1. Desk:Desk
  2. label:Desk
  3. label:label
  4. "label":"Desk"
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does this print?

base = 8
double = base * 2
copy = double
base = 10
double = base * 2
print(copy, double)
  1. 20 20
  2. 16 16
  3. 8 20
  4. 16 20
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What values do int(-6.5), round(-6.5), and -13 // 2 produce, in that order?
  1. -6, -6, -7
  2. -7, -6, -7
  3. -6, -7, -6
  4. -7, -7, -6
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What values do 9.0 // 4 and 9 // 4 produce, in that order?
  1. 2 and 2
  2. 2.25 and 2
  3. 2.0 and 2
  4. 2.0 and 2.0
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

The same valid text is run as a fresh script and then entered one statement at a time in a fresh shell: n = 6, n * 3, print(n). What difference appears?
  1. Both show 18 and then 6; the settings make no difference.
  2. The script shows 18; the shell shows 6 and then 18.
  3. The script shows 6; the shell shows 6, 18, then 6.
  4. The script shows 6; the shell shows 18 and then 6.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Why does the last line fail?

input = "Leah"
name = input("Name: ")
  1. The word input is a reserved keyword.
  2. The name input now refers to a string.
  3. A prompt cannot contain a colon.
  4. A numeric conversion is missing around the call.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What does print("Row", 8, "|", end="!") display before the cursor stops?
  1. Row|8!
  2. Row8|!
  3. Row 8 |!
  4. Row 8 !|
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A minutes-to-hours program gives the expected result for input 145. A user next enters 119. What does it print, and what change makes hours count full hours?

total_minutes = int(input("Whole minutes: "))
hours = round(total_minutes / 60)
minutes = total_minutes % 60
print(hours, minutes)
  1. 2 59; use hours = total_minutes // 60.
  2. 1 59; use hours = total_minutes // 60.
  3. 2 59; use hours = int(total_minutes) / 60.
  4. 1 59; use hours = total_minutes % 60.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine tracing, conversions, and program checks10 Practice Questions

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

Question 1 of 10

A signed adjustment is -23. Its quotient and remainder on division by 6 must reconstruct it. What are the two results?
  1. Quotient -3, remainder -5
  2. Quotient -4, remainder -1
  3. Quotient -4, remainder 1
  4. Quotient -3, remainder 5
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does print("Code: " + str(3 * 4)) display?
  1. Code: 12
  2. Code: 34
  3. Code: 121212
  4. Code: 3 * 4
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does this print?

reading = "18"
float(reading)
print(reading + "2")
  1. 20.0
  2. 182
  3. 18.02
  4. 20
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A machine charges 3 dollars for each complete 15-minute block and 1 dollar for each leftover minute. What should replace the calculation line to compute the charge for a whole-number input?

minutes = int(input("Minutes: "))
charge = 0
print("Charge in dollars:", charge)
  1. charge = (minutes / 15) * 3 + minutes % 15
  2. charge = (minutes // 15) * 3 + minutes // 15
  3. charge = minutes // (15 * 3) + minutes % 15
  4. charge = (minutes // 15) * 3 + minutes % 15
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

What does print("6" + str(2 + 3) * 2) display?
  1. 6565
  2. 610
  3. 655
  4. 16
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A user enters 4. What appears, apart from the input prompt and error message?

count = input("Count: ")
print("Received")
next_count = count + 1
print(next_count)
  1. Received, then 5 is printed.
  2. Received, then 41 is printed.
  3. Nothing; no statement can run.
  4. Received, then execution stops.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A comment is meant to explain a rate. The code changes from fee_rate = 0.04 # 4% service fee to fee_rate = 0.06 # 4% service fee. What should be corrected?
  1. Change the comment to identify a 6% fee.
  2. Keep the comment because Python ignores it.
  3. Put the comment inside quotes to update it.
  4. Remove the decimal point from the rate.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Why can 0.1 + 0.2 display as 0.30000000000000004?
  1. The plus operator joins the decimal digits as text.
  2. The stored binary floats approximate the decimal fractions.
  3. The interpreter rounds every sum upward by one digit.
  4. The decimal point separates two independent values.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What does this print?

rate = 6
hours = 4
pay = rate * hours
rate += 2
pay += rate
hours /= 2
print(pay, hours)
  1. 40 2.0
  2. 32 2
  3. 24 2.0
  4. 32 2.0
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

What value does -2 ** 3 ** 2 + 20 // 3 % 4 produce?
  1. -62
  2. -510
  3. -506
  4. 514
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

71 Key Terms, each with its definition

A

Accumulator
An accumulator is a variable that collects a running total, starting from an initial value and changing as amounts are added.
Initialize total = 0 before using updates such as total += cost to collect several amounts.
Argument
An argument is a value or expression supplied inside a function call's parentheses, allowing the function to operate on that data.
In print("Score:", 9), the label and the integer are separate arguments displayed in that order.
Assignment
Assignment evaluates an expression and makes a target name refer to the resulting value, using = with the name on the left.
In area = width * height, the multiplication is evaluated before its result is stored under area.
Associativity
Associativity determines how equal-priority operations are grouped; most group left to right, while powers group right to left.
The expression 16 / 4 * 2 groups as (16 / 4) * 2, so the result is 8.0, not 2.0.
Augmented assignment
Augmented assignment combines an operation with reassignment, using an existing value to calculate and store its replacement.
For numbers, score += 6 adds six to the current score and assigns the sum back to the same name.

B

Boolean
A Boolean is a value of type bool with one of two values, True or False, written with capitals and without quotes.
The comparison 4 < 9 produces the Boolean True, while the quoted text "True" is a string.
Boundary value
A boundary value is an input at or near a point where a result changes form, useful for checking a program against expected behavior.
For splitting seconds into minutes, testing 59, 60, and 61 checks the first full-minute boundary.
Bug
A bug is a mistake in a program that prevents the intended behavior, whether it causes an error message or an incorrect result.
A missing pair of parentheses in an average calculation can be a bug even when the code runs.
Built-in function
A built-in function is a callable operation available without an import, such as print() or input(), whose name can be hidden by assignment.
Using a data name such as item_total keeps the built-in name int available for conversions.

C

Case sensitivity
Case sensitivity means uppercase and lowercase letters distinguish names, so changing capitalization can refer to a different name.
After assigning total, writing print(Total) fails unless that separate capitalized name also exists.
Comment
A comment is a note beginning with # outside a string and ending with the line; Python ignores it when running the program.
A note explaining that a rate includes a service fee helps a reader understand why it was chosen.
Commenting out
Commenting out means putting a comment marker before a statement so it does not run, while keeping the statement's text available.
Prefixing a temporary print call with # disables that output without deleting the line from the editor.
Concatenation
Concatenation joins strings end to end with +, keeping their character order and inserting no extra spaces or punctuation.
Joining "Room " and "12" preserves the space already inside the first string and gives "Room 12".
Constant
A constant is a value intended to stay unchanged, conventionally given a capital-letter name even though Python permits reassignment.
The name FEE_RATE tells a reader to treat that rate as fixed while following the program.

D

Debugging
Debugging is the process of finding and fixing mistakes in code by inspecting messages, checking values, and comparing expected results.
Reading the last traceback line helps you decide which spelling, value, or operation to check next.
Docstring
A docstring is a string used as documentation in a designated position in Python code; it is different from a comment marked with #.
A triple-quoted string at the start of a script can describe the program without being a comment.
Dynamic typing
Dynamic typing allows a name to refer to values of different types over time, because the type belongs to each value rather than the name.
Python permits entry = 3 followed by entry = "three", although a consistent meaning is clearer.

E

Empty string
The empty string is a string containing no characters at all, written as "" or ''; it differs from a string containing a space.
Repeating a string zero times produces empty text, while adding " " inserts a space character.
Escape sequence
An escape sequence begins with a backslash and represents a character, such as a newline or a quote that should stay inside a string.
In "Up\nDown", the escape creates a line break between the two words when the string is printed.
Exponentiation
Exponentiation raises a base to a power using **; with integer operands and a nonnegative exponent, the result is an integer.
The expression 4 ** 3 multiplies three copies of four and gives the integer result 64.
Expression
An expression is Python code that evaluates to one value, from a single literal or name to a combination of several operations.
In print(7 * 6), the expression 7 * 6 is evaluated before its value is displayed on the screen.

F

Float
A float is a floating-point number with limited precision, used for quantities that may contain fractions, such as measurements.
The literal 6.0 is a float even though its numerical value equals the integer six exactly.
Floor division
Floor division divides two numeric values and rounds the quotient downward, including toward more negative values for a negative quotient.
The expression -10 // 3 gives -4, because negative 3.333… rounds downward, not toward zero.

I

Identifier
An identifier is a name used in code, such as a variable name, that must follow Python's character rules and avoid reserved keywords.
The identifier seat_count2 is valid, but a name starting with a digit or containing a space is not.
Increment
An increment is an increase in a variable's value, commonly by one, performed with an assignment that uses its existing value.
After visits = 4, the update visits += 1 records one more visit and makes the count five.
Inline comment
An inline comment is a comment placed after executable code on the same line, normally separated from the code by at least two spaces.
In rate = 0.07 # 7% tax, the assignment runs and the final words explain the meaning of the rate.
Input
Input is data supplied to a program; the built-in input() reads a typed line and returns its characters as a string.
Entering 45 produces the text "45", which needs conversion before it can be used as an integer.
Input–process–output
Input–process–output is a program structure that reads and converts data, calculates with the values, and displays meaningful results.
A travel program can read miles and gallons, calculate miles per gallon, then print the result with its unit.
Integer
An integer is a whole-number value of type int, with no fractional part; Python integers have no fixed-width size limit.
Use item_count = 24 for a count, and write large integer literals with optional underscores.
Interactive shell
The interactive shell is a place to enter Python statements one at a time and immediately see expression results. It is also called the REPL.
At the >>> prompt, entering 14 + 2 makes the shell display 16 without a print call.
Interpreter
An interpreter is a program that reads Python code and carries out its instructions, using the values and operations the code specifies.
In print(6 * 7), the interpreter evaluates 6 * 7 and supplies the resulting value to the print call.

K

Keyword
A keyword is a word reserved for Python's grammar, so it cannot be used as an ordinary variable name in an assignment.
Using class as the target of an assignment causes a syntax error before the script can run.

L

Line ending
A line ending is the text printed after the final argument of a print call, controlled by end and defaulting to a newline.
Using end="" leaves no ending characters, so the next print call continues on the same line.
Literal
A literal is a value written directly in source code, with spelling such as quotes or a decimal point determining its type.
The literals 12, 12.0, and "12" are an integer, a float, and a string, respectively.
Logic error
A logic error is a mistake that lets code run but gives a result that does not match the calculation or behavior the programmer intended.
A total that omits a fee can be wrong without producing any exception or warning from Python.

M

Mixed-type expression
A mixed-type expression combines values of different types, so each operation must be checked for a compatible operand combination.
The calculation 2 + 0.5 works numerically, while "2" + 0.5 fails without an explicit conversion.

O

Operand
An operand is a value or expression on which an operator acts, and its type helps determine what that operation can do.
In hours * rate, the current values of hours and rate are the multiplication operands.
Operator
An operator is a symbol or symbol combination that performs an operation on operands, such as + for addition or ** for a power.
Changing 6 * 2 to 6 ** 2 changes the operation from multiplication to exponentiation.
Output
Output is information a program displays, such as a calculated number and its label, so a person can read the result.
The line Distance: 18 miles gives both a value and the unit needed to interpret that value.

P

Parentheses
Parentheses are round grouping marks that make an enclosed expression act as one part of a larger calculation or enclose function arguments.
In (10 + 6) / 4, parentheses ensure the whole sum is divided by four to give 4.0.
Parity
Parity describes whether an integer is even or odd, which can be identified by its remainder on division by two.
The result of -5 % 2 is one, showing that negative five is odd under the same remainder rule.
Precedence
Precedence is the priority order that decides which operators are applied first when an expression contains more than one kind.
In 4 + 3 * 5, multiplication has higher precedence than addition, so the result is nineteen.
Program
A program is a sequence of instructions that tells a computer what to do, such as calculate a value and display the result.
A short program can calculate the cost of several items and then print the total with a label.
Prompt
A prompt is a message asking the user to enter data, ideally identifying the expected kind of value and any measurement unit.
The prompt "Whole minutes: " signals that the program expects integer-form text and leaves a typing gap.

Q

Quotient
A quotient is the result of division; floor division selects the greatest whole number no larger than the exact quotient.
For 22 // 5, the floored quotient is four, and the corresponding remainder is two.

R

Reassignment
Reassignment gives an existing name a new value, replacing the value reachable through that name without updating other names.
After level = 2 and then level = 5, reading level gives five instead of the earlier two.
Remainder
A remainder is the value from % that completes a division; with integers and a positive divisor, it is nonnegative and smaller than the divisor.
With 43 items in groups of 8, 43 % 8 gives 3 items left after five complete groups.
Rounding
Rounding selects a nearest value at a chosen precision; Python's round() resolves exact halfway values toward the even neighbor.
The call round(6.5) gives six, while round(7.5) gives eight because both selected neighbors are even.
Runtime error
A runtime error is a failure during execution that stops the program at the failing operation after earlier statements have run.
If a later line divides by zero, text printed by an earlier line remains visible on the screen.

S

Scientific notation
Scientific notation writes a float using e and a power of ten, making very large or very small numerical values compact.
The literal 8e-3 means eight divided by one thousand and represents the float 0.008.
Script
A script is a plain-text file of Python statements that can be saved, edited, and run together in their written order.
Saving instructions as a script lets you rerun the same calculation after changing an input value.
Separator
A separator is the text inserted between displayed arguments by print(), controlled by the named argument sep and defaulting to one space.
The call print("A", "B", sep="-") uses a hyphen separator and displays A-B on the output line.
Simultaneous assignment
Simultaneous assignment evaluates all right-side expressions before assigning their values to the left-side names by position.
In x, y = 4, 8, the first name gets four and the second gets eight in a single statement.
snake_case
Snake_case is a naming style that joins lowercase words with underscores, making multiword variable names valid and readable.
The name total_seconds follows snake_case and identifies the unit used by a time calculation.
Statement
A statement is an instruction in Python code, such as an assignment or a print call, that runs as part of a program.
In a simple script, count = 6 assigns a value before the later statement print(count) uses it.
String
A string is a sequence of characters of type str, containing text such as letters, digits, spaces, punctuation, and symbols.
The value "Bus 09" preserves its letters, space, and leading-zero identifier as one text value.
String delimiter
A string delimiter is an opening or closing quote mark that identifies a string's boundary without becoming part of its text.
Double outer quotes in "We're ready" allow the apostrophe to remain inside the string.
String repetition
String repetition uses * with a string and an integer count to create the requested number of copies joined directly together.
The expression "ab" * 3 produces "ababab"; no space is added between the repeated copies.
Syntax error
A syntax error is a violation of Python's grammar that prevents a saved script from starting, such as a missing closing parenthesis.
An unclosed quote near the end of a script can prevent even the first print statement from running.

T

Temporary variable
A temporary variable holds a value needed during a short sequence of steps, such as preserving an original value while two others are swapped.
In a sequential swap, temp = left preserves the old left value before left is overwritten.
Trace table
A trace table records each variable's value after each statement, making the order and effects of execution visible for hand checking.
A new row after price = 10 changes the price column while an earlier saved total stays unchanged.
Traceback
A traceback is an error report showing where execution failed, followed by the exception type and a message describing the failure.
Read the final error line first, then inspect the reported code and location directly above it.
Truncation
Truncation removes the fractional part of a number toward zero, as int() does to a float, without rounding to the nearest integer.
Converting -9.8 with int() gives -9, while flooring the same negative value would give -10.
Type
A type identifies what kind of value Python has and helps determine which operations it can perform with that value.
The type of "25" is str, so adding another string joins text instead of adding numeric amounts.
Type conversion
Type conversion creates a new value in a requested type, such as an integer from numeric text, without changing the original value itself.
Store int(text) in a variable when later arithmetic needs its converted value instead of the text.
type()
The function type() reports the type of its argument, allowing you to inspect a stored value or the result of an expression.
Printing type("12") reveals a string even though the displayed characters look like a number.
TypeError
A TypeError is an exception raised when an operation or call receives an incompatible type, such as a string joined to an integer.
The expression "Count: " + 7 fails because concatenation requires text on both sides of +.

U

Unary minus
Unary minus is an operator that changes the sign of one value, unlike subtraction, which combines two operands into a difference.
In 10 - -2, the second minus makes negative two, so subtracting it gives the value 12.

V

Value
A value is a piece of data that Python works with, such as a number, some text, or a Boolean result, and every value has a type.
The values 25 and "25" look similar when printed but support different operations in a program.
ValueError
A ValueError is an exception raised when an operation receives a value of an accepted type whose content cannot be used as requested.
The string "ten" is text, but int("ten") fails because that text does not describe an integer.
Variable
A variable is a name that refers to a stored value, allowing a program to use or replace that value in later statements.
After length = 6, the expression length * 2 reads the current value through the name length.

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