Python Basics: Values, Variables, and Expressions
BeginnerLesson 1 of 10 in Python for Beginners: Introduction to Programming
What you will learn
- 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 scriptTell 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 mistakesRecognize 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 commentsWrite comments that help a reader understand a program, and know which text Python ignores and which text it still treats as code or data.
- Run code in the shell and as a script
- 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 apartIdentify 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 numbersWrite int and float literals correctly, including very large and very small numbers, and explain why float results are sometimes slightly off.
- Write text as stringsCreate strings with single, double and triple quotes, put quotes and special characters inside them, and keep text apart from code.
- Tell values and types apart
- 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 variablesCreate variables with assignment statements, explain what the equals sign does in Python, and use variables in later statements.
- Choose valid and meaningful variable namesFollow 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 programChange variables with augmented assignment, swap two values correctly, and follow a program line by line with a trace table to predict its output.
- Assign values to variables
- 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 operatorsCalculate with +, -, *, /, //, % and **, and predict whether each result is an int or a float.
- Apply the order of operationsPredict how Python evaluates an expression with several operators, and use parentheses to make it calculate what you intend.
- Split quantities with floor division and remainderUse // and % to split an amount into whole groups and a leftover, and apply them to time, money and digits.
- Combine text and numbers in expressionsJoin and repeat strings with + and *, and predict what happens when an expression mixes integers, floats and strings.
- Use the arithmetic operators
- 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 typesUse 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 programAsk the user for data with input(), convert it before calculating, and combine input, processing and output into a short working program.
- Convert values between types
Python Variables study guide
1Run 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
| Kind | What happens | Example |
|---|---|---|
| Syntax error | Python cannot read the code; the script does not start. | print("hi" has an unclosed parenthesis. |
| Runtime error | Execution reaches an operation that fails and stops there. | 10 / 0 raises ZeroDivisionError. |
| Logic error | The 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" + 5tries 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.
2Recognize 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
| Type | Kind of data | Examples |
|---|---|---|
int | Integer, or whole number | 42, 0, -7 |
float | Floating-point number | 3.5, 2.0, -0.25 |
str | String, or text | "Ada", 'hello', "42" |
bool | Boolean true/false value | True, 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
TrueandFalse, 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:
| Literal | Value |
|---|---|
1.5e3 | 1500.0 |
2.5e-3 | 0.0025 |
1e3 | 1000.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
eis 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 code | Character in the string |
|---|---|
\n | Newline |
\t | Tab |
\\ | 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.
3Name 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.
| Name | What happens |
|---|---|
total, item_count, price2, _temp | Valid names |
2nd_place | Invalid: starts with a digit |
first name | Invalid: contains a space |
first-name | Read 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_casenames 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 run | price | quantity | total |
|---|---|---|---|
price = 20 | 20 | Not assigned | Not assigned |
quantity = 3 | 20 | 3 | Not assigned |
total = price * quantity | 20 | 3 | 60 |
price = 25 | 25 | 3 | 60 |
total += 5 | 25 | 3 | 65 |
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
+= 1for 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.
4Build 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:
| Operation | Expression | Result |
|---|---|---|
| Addition | 7 + 2 | 9 |
| Subtraction | 7 - 2 | 5 |
| Multiplication | 7 * 2 | 14 |
| Division | 7 / 2 | 3.5 |
| Floor division | 7 // 2 | 3 |
| Remainder | 7 % 2 | 1 |
| Power | 7 ** 2 | 49 |
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%raiseZeroDivisionErrorfor 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:
- Parenthesized expressions.
- Powers,
**. - Unary signs, such as the minus in
-x. - Multiplication and division operations:
*,/,//,%. - 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 ** 2and(-2) ** 2differ. - 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:
| Quantity | Full groups | Leftover |
|---|---|---|
| 347 cents, 100 cents per dollar | 347 // 100 gives 3 dollars | 347 % 100 gives 47 cents |
| 75 eggs, 12 per carton | 75 // 12 gives 6 full cartons | 75 % 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 % breconstructsawhenbis 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 toprint(). - Follow both precedence and operand types when tracing a mixed expression.
5Read 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.
| Expression | Result | Reason |
|---|---|---|
int(-3.5) | -3 | Truncate toward zero |
round(-3.5) | -4 | Nearest integer; tie goes to even |
-7 // 2 | -4 | Floor 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.ValueErrorandTypeErroridentify 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.
sepchanges the space between arguments;endchanges 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
1Run a small program and repair it
13 steps
- 1IntroductionStart 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.
- 2ExampleTry one expression in the shell
At the Python shell's
>>>prompt, enter9 * 3. Python evaluates the expression and displays27automatically.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. - 3ExplanationMake a script show its calculation
A script with only
9 * 3evaluates the product but displays nothing. To show it, write:print(9 * 3) print("Calculation finished")The output is
27, thenCalculation finishedon 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. - 4ChallengePredict what is actually shown
A saved script contains these two lines. What is displayed?
11 + 5 print("Ready to check")---reveal---
Only
Ready to checkappears. 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. - 5ExplanationSeparate 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.
- 6ExampleRead the final error line first
Consider this code:
distance = 21 print(distnace)A traceback ends by identifying
NameErrorand the undefined namedistnace. Read that final message, then inspect the reported line above it. The name assigned earlier isdistance; the two spellings differ. Correct the lookup toprint(distance), which displays21. - 7TipChoose the next useful check
Let the error type narrow your search. For
NameError, check spelling, capitalization, and whether the variable was assigned earlier. ForTypeError, inspect the types used by the operation. ForValueError, 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.
- 8ChallengeDoes the first message survive?
What is printed before this program stops?
itemshas not been assigned.print("Checking") print(items) print("Finished")---reveal---
Checkingis printed. The next line raisesNameError, 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. - 9ExplanationAdd 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 feeThe 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.
- 10ChallengeLocate 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, soPacking labelis ignored. A character's position inside or outside a string changes how Python reads it. - 11TipKeep a comment true after editing
If the processing fee changes from 3 percent to 5 percent, change both
service_rateto0.05and the comment to5% 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. - 12ChallengeCombine 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 #1is printed.Printthen raisesNameErrorbecause Python distinguishes uppercase and lowercase names. The built-in isprint. The valid first output stays visible because the failure occurs during execution. - 13RecapUse 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.
2Read the type from a value's spelling
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionSimilar-looking values can behave differently
- 2ExampleInspect three forms of the same digits
- 3ConnectionChoose data for its purpose
- 4ChallengeDistinguish Boolean text from a Boolean
- 5ExplanationScale a float with exponent notation
- 6Key InsightA comma changes the data
- 7ChallengeWrite a small decimal value
- 8TipInterpret the small extra digits
- 9ExampleChoose outer quotes that fit the message
- 10ExplanationMake a line break part of a string
- 11ChallengePredict quoted and unquoted names
- 12Key InsightA space still counts as data
- 13ChallengeFollow spelling into behavior
- 14RecapCheck the value before the operation
3Follow a value through assignments
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTrack one moment at a time
- 2ExampleEvaluate first, assign second
- 3Key InsightA stored result does not keep a formula
- 4ChallengeTrace a copy before reassignment
- 5ConnectionChoose a readable name
- 6ExampleKeep built-in names available
- 7ChallengeRepair a name without changing its meaning
- 8ExplanationUpdate from an existing value
- 9ExampleWrite down only what changed
- 10ChallengeWatch an update change the type
- 11ExplanationKeep an original before overwriting it
- 12ExplanationRead a simultaneous swap
- 13ChallengeCombine names, copies, and updates
- 14RecapTrace current values, not intentions
4Evaluate expressions one operation at a time
18 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionFollow both order and type
- 2ExplanationMatch the symbol to the operation
- 3ExampleKeep the type beside the quotient
- 4ChallengeSelect a power and its result
- 5ExampleWork the highest-priority operation first
- 6Key InsightEqual priority means left to right
- 7ExplanationPowers group in the other direction
- 8ChallengeRepair a grouped calculation
- 9ExampleSplit a quantity into full groups
- 10ExplanationFloor means down, including below zero
- 11ConnectionUse digits as groups of ten
- 12ChallengeFind both pieces of the time
- 13ExplanationText uses the same symbols differently
- 14ExampleBuild a border before joining it
- 15ChallengeConvert the inner result to text
- 16TipLocate an incompatible operation
- 17ChallengeCombine remainder, power, and text
- 18RecapCheck the intermediate result
5Turn typed data into a checked result
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead, calculate, then explain the result
- 2ExplanationKeep the new value from a conversion
- 3ExampleA float and decimal text convert differently
- 4ChallengeSeparate truncating from rounding
- 5ExplanationPass separate values to print
- 6ExampleChange the separator and the ending
- 7ChallengePredict two print calls together
- 8TipRound a value without promising padded text
- 9ExampleRead a whole-number input
- 10ExampleCalculate two results from the same total
- 11ExampleLabel the final values
- 12ChallengeFind the missing conversion
- 13ConnectionTest the place where the answer changes
- 14ChallengeCombine conversion, division, and output
- 15RecapCheck each stage separately
Python Variables practice questions
Set 1: Work with changing values and typed data10 Practice Questions
Question 1 of 10
What does this display?
print("Bay #7") # Pickup point
Show answerHide answer
"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
"00482" and will not be used in calculations. What type best preserves it?Show answerHide answer
Question 3 of 10
What value does cost have at the end?
units = 6
rate = 4
cost = units * rate
units = 8
Show answerHide answer
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)
Show answerHide answer
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
6e2 have?Show answerHide answer
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
Show answerHide answer
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
print("Go" * 2 + "!") display?Show answerHide answer
"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
int(-8.9)?Show answerHide answer
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="-")
Show answerHide answer
: 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)
Show answerHide answer
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
18 - 6. What appears when it runs?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.
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
type("False") report?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
print("North\nSouth") display?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)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
24 / 6 produce?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
40 - 18 / 3 * 2 + 1 produce?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
print("Zone", 4, sep="-") display?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
amount = 11, then amount + 4. What does the shell display for these two entries?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
Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
print('He said "yes"') display?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
MAX_ATTEMPTS = 5. What do the capital letters communicate?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)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
(-3) ** 2 + 2 ** 3 produce?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
-17 // 5 and -17 % 5, in that order?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
int("12.0")?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))
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")
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
3 + 2.0 produce?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
label = "Desk", what does print("label", label, sep=":") display?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)
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
int(-6.5), round(-6.5), and -13 // 2 produce, in that order?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
9.0 // 4 and 9 // 4 produce, in that order?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
n = 6, n * 3, print(n). What difference appears?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: ")
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
print("Row", 8, "|", end="!") display before the cursor stops?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)
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
-23. Its quotient and remainder on division by 6 must reconstruct it. What are the two results?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
print("Code: " + str(3 * 4)) display?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")
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)
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
print("6" + str(2 + 3) * 2) display?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)
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
fee_rate = 0.04 # 4% service fee to fee_rate = 0.06 # 4% service fee. What should be corrected?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
0.1 + 0.2 display as 0.30000000000000004?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)
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
-2 ** 3 ** 2 + 20 // 3 % 4 produce?Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Accumulator
total = 0 before using updates such as total += cost to collect several amounts.Argument
print("Score:", 9), the label and the integer are separate arguments displayed in that order.Assignment
= with the name on the left.area = width * height, the multiplication is evaluated before its result is stored under area.Associativity
16 / 4 * 2 groups as (16 / 4) * 2, so the result is 8.0, not 2.0.Augmented assignment
score += 6 adds six to the current score and assigns the sum back to the same name.B
Boolean
bool with one of two values, True or False, written with capitals and without quotes.4 < 9 produces the Boolean True, while the quoted text "True" is a string.Boundary value
Bug
Built-in function
print() or input(), whose name can be hidden by assignment.item_total keeps the built-in name int available for conversions.C
Case sensitivity
total, writing print(Total) fails unless that separate capitalized name also exists.Comment
# outside a string and ending with the line; Python ignores it when running the program.Commenting out
# disables that output without deleting the line from the editor.Concatenation
+, keeping their character order and inserting no extra spaces or punctuation."Room " and "12" preserves the space already inside the first string and gives "Room 12".Constant
FEE_RATE tells a reader to treat that rate as fixed while following the program.D
Debugging
Docstring
#.Dynamic typing
entry = 3 followed by entry = "three", although a consistent meaning is clearer.E
Empty string
"" or ''; it differs from a string containing a space." " inserts a space character.Escape sequence
"Up\nDown", the escape creates a line break between the two words when the string is printed.Exponentiation
**; with integer operands and a nonnegative exponent, the result is an integer.4 ** 3 multiplies three copies of four and gives the integer result 64.Expression
print(7 * 6), the expression 7 * 6 is evaluated before its value is displayed on the screen.F
Float
6.0 is a float even though its numerical value equals the integer six exactly.Floor division
-10 // 3 gives -4, because negative 3.333… rounds downward, not toward zero.I
Identifier
seat_count2 is valid, but a name starting with a digit or containing a space is not.Increment
visits = 4, the update visits += 1 records one more visit and makes the count five.Inline comment
rate = 0.07 # 7% tax, the assignment runs and the final words explain the meaning of the rate.Input
input() reads a typed line and returns its characters as a string.45 produces the text "45", which needs conversion before it can be used as an integer.Input–process–output
Integer
int, with no fractional part; Python integers have no fixed-width size limit.item_count = 24 for a count, and write large integer literals with optional underscores.Interactive shell
>>> prompt, entering 14 + 2 makes the shell display 16 without a print call.Interpreter
print(6 * 7), the interpreter evaluates 6 * 7 and supplies the resulting value to the print call.K
Keyword
class as the target of an assignment causes a syntax error before the script can run.L
Line ending
end and defaulting to a newline.end="" leaves no ending characters, so the next print call continues on the same line.Literal
12, 12.0, and "12" are an integer, a float, and a string, respectively.Logic error
M
Mixed-type expression
2 + 0.5 works numerically, while "2" + 0.5 fails without an explicit conversion.O
Operand
hours * rate, the current values of hours and rate are the multiplication operands.Operator
+ for addition or ** for a power.6 * 2 to 6 ** 2 changes the operation from multiplication to exponentiation.Output
Distance: 18 miles gives both a value and the unit needed to interpret that value.P
Parentheses
(10 + 6) / 4, parentheses ensure the whole sum is divided by four to give 4.0.Parity
-5 % 2 is one, showing that negative five is odd under the same remainder rule.Precedence
4 + 3 * 5, multiplication has higher precedence than addition, so the result is nineteen.Program
Prompt
"Whole minutes: " signals that the program expects integer-form text and leaves a typing gap.Q
Quotient
22 // 5, the floored quotient is four, and the corresponding remainder is two.R
Reassignment
level = 2 and then level = 5, reading level gives five instead of the earlier two.Remainder
% that completes a division; with integers and a positive divisor, it is nonnegative and smaller than the divisor.43 % 8 gives 3 items left after five complete groups.Rounding
round() resolves exact halfway values toward the even neighbor.round(6.5) gives six, while round(7.5) gives eight because both selected neighbors are even.Runtime error
S
Scientific notation
e and a power of ten, making very large or very small numerical values compact.8e-3 means eight divided by one thousand and represents the float 0.008.Script
Separator
print(), controlled by the named argument sep and defaulting to one space.print("A", "B", sep="-") uses a hyphen separator and displays A-B on the output line.Simultaneous assignment
x, y = 4, 8, the first name gets four and the second gets eight in a single statement.snake_case
total_seconds follows snake_case and identifies the unit used by a time calculation.Statement
count = 6 assigns a value before the later statement print(count) uses it.String
str, containing text such as letters, digits, spaces, punctuation, and symbols."Bus 09" preserves its letters, space, and leading-zero identifier as one text value.String delimiter
"We're ready" allow the apostrophe to remain inside the string.String repetition
* with a string and an integer count to create the requested number of copies joined directly together."ab" * 3 produces "ababab"; no space is added between the repeated copies.Syntax error
T
Temporary variable
temp = left preserves the old left value before left is overwritten.Trace table
price = 10 changes the price column while an earlier saved total stays unchanged.Traceback
Truncation
int() does to a float, without rounding to the nearest integer.-9.8 with int() gives -9, while flooring the same negative value would give -10.Type
"25" is str, so adding another string joins text instead of adding numeric amounts.Type conversion
int(text) in a variable when later arithmetic needs its converted value instead of the text.type()
type() reports the type of its argument, allowing you to inspect a stored value or the result of an expression.type("12") reveals a string even though the displayed characters look like a number.TypeError
"Count: " + 7 fails because concatenation requires text on both sides of +.U
Unary minus
10 - -2, the second minus makes negative two, so subtracting it gives the value 12.V
Value
25 and "25" look similar when printed but support different operations in a program.ValueError
"ten" is text, but int("ten") fails because that text does not describe an integer.Variable
length = 6, the expression length * 2 reads the current value through the name length.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.