python crash course

Getting Started

Setting up your Programming Environment

installing Python

https://www.python.org/downloads/

run the installer. Make sure you select the option Add Python to PATH, which will make it easier to configure your system correctly. Figure 1-1 shows this option selected.

Alt text

Running Python in a Terminal Session

Open a new command window and enter python in lowercase. You should
see a Python prompt (>>>), which means Windows has found the version of
Python you just installed.

Installing the Python Extension for VS Code

To install the Python extension, click the Manage icon, which looks
like a gear in the lower-left corner of the VS Code app. In the menu that
appears, click Extensions. Enter python in the search box and click the
Python extension. (If you see more than one extension named Python,
choose the one supplied by Microsoft.)

running hello_world.py

folder: python_work

file: hello_world.py

print("Hello Python world!")

vscode -> run -> Run Without Debugging or press CTRL-F5

Hello Python world!

Running Python Programs from a Terminal

terminal to run hello_world.py:

1
2
3
4
5
C:\> cd Desktop\python_work
C:\Desktop\python_work> dir
hello_world.py
C:\Desktop\python_work> python hello_world.py
Hello Python world!

First, use the cd command to navigate to the python_work folder, which is in the Desktop folder.

Next, use the dir command to make sure hello_world.py is in this folder.

Then run the file using the command python hello_world.py.

Variables and Simple Data Types

variable

1
2
message = "Hello Python world!"
print(message)

output

Hello Python world!

We’ve added a variable named message.

Every variable is connected to a
value, which is the information associated with that variable.


1
2
3
4
message = "Hello Python world!"
print(message)
message = "Hello Python Crash Course world!"
print(message)

output:

1
2
Hello Python world!
Hello Python Crash Course world!

You can change the value of a variable in your program at any time,
and Python will always keep track of its current value.

Naming and Using Variables

rules:

  • Variable names can contain only letters, numbers, and underscores.
    They can start with a letter or an underscore, but not with a number.
    For instance, you can call a variable message_1 but not 1_message.
  • Spaces are not allowed in variable names, but underscores can be used
    to separate words in variable names. For example, greeting_message works
    but greeting message will cause errors.
  • Avoid using Python keywords and function names as variable names.
    For example, do not use the word print as a variable name; Python
    has reserved it for a particular programmatic purpose. (See “Python
    Keywords and Built-in Functions” on page 466.)
  • Variable names should be short but descriptive. For example, name is
    better than n, student_name is better than s_n, and name_length is better
    than length_of_persons_name.
  • Be careful when using the lowercase letter l and the uppercase letter O
    because they could be confused with the numbers 1 and 0.

The Python variables you’re using at this point should be lowercase. You won’t get errors if you use uppercase letters, but uppercase letters in variable names have special meanings that we’ll discuss in later chapters.

Avoiding Name Errors When Using Variables

1
2
message = "Hello Python Crash Course reader!"
print(mesage)

When an error occurs in your program, The interpreter provides
a traceback when a program cannot run successfully.

A traceback is a record of where the interpreter ran into trouble when trying to execute your code.

example:

1
2
3
4
5
Traceback (most recent call last):
File "hello_world.py", line 2, in <module> # 1
print(mesage) # 2
^^^^^^
NameError: name 'mesage' is not defined. Did you mean: 'message'? # 3

The output reports that an error occurs in line 2 of the file hello_world.py and tells us what kind of error it found 3.
In this case it found a name error
and reports that the variable being printed, mesage, has not been defined.

A name error usually means we either forgot to set a variable’s value before using it, or we made a spelling mistake when entering the variable’s name.

If Python finds a variable name that’s similar to the one it doesn’t recognize, it will ask if that’s the name you meant to use.

Variables Are Labels

It’s much better to think of variables as labels that you can assign to values. You can
also say that a variable references a certain value.

Strings

A string is a series of characters.
Anything inside quotes is considered a string in Python, and you can use single or double quotes around your

strings like this:

“This is a string.”
‘This is also a string.’

use quotes and apostrophes within your strings:

‘I told my friend, “Python is my favorite language!”‘
“The language ‘Python’ is named after Monty Python, not the snake.”
“One of Python’s strengths is its diverse and supportive community.”

Changing Case in a String with Methods

string.title()

Return a version of the string where each word is titlecased.
More specifically, words start with uppercased characters and all remaining cased characters have lower case.

1
2
name = "ada lovelace"
print(name.title())

output:
Ada Lovelace

A method is an action that Python can perform on a piece of data. The dot (.) after name in name.title() tells Python to make the title() method act on the variable name.

Every method is followed by a set of parentheses, because
methods often need additional information to do their work. That information is provided inside the parentheses.

The title() function doesn’t need
any additional information, so its parentheses are empty.


change a string to all uppercase or all lowercase letters like this:

1
2
3
name = "Ada Lovelace"
print(name.upper())
print(name.lower())

This will display the following:

ADA LOVELACE
ada lovelace

The lower() method is particularly useful for storing data. You typically won’t want to trust the capitalization that your users provide, so you’ll convert strings to lowercase before storing them. Then when you want to display the information, you’ll use the case that makes the most sense foreach string.

Using Variables in Strings

use a variable’s value inside a string:

1
2
3
4
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}" # 1
print(full_name)

place the letter f immediately
before the opening quotation mark 1. Put braces around the name or
names of any variable you want to use inside the string.

These strings are called f-strings. The f is for format, because Python
formats the string by replacing the name of any variable in braces with its
value. The output from the previous code is:
ada lovelace


another example:

1
2
3
4
first_name = "ada"
last_name = "lovelace"
full_name = f"{first_name} {last_name}"
print(f"Hello, {full_name.title()}!") # 1

output:

Hello, Ada Lovelace!

Adding Whitespace to Strings with Tabs or Newlines

whitespace refers to any nonprinting characters, such as
spaces, tabs, and end-of-line symbols.
use whitespace to organize your output so it’s easier for users to read.

a tab \t:

1
2
3
4
>>> print("Python")
Python
>>> print("\tPython")
Python

newline \n:

1
2
3
4
5
>>> print("Languages:\nPython\nC\nJavaScript")
Languages:
Python
C
JavaScript

combine tabs and newlines:

1
2
3
4
5
>>> print("Languages:\n\tPython\n\tC\n\tJavaScript")
Languages:
Python
C
JavaScript

Stripping Whitespace

‘python’ and ‘python ‘ to a program, they are two different strings.

often you’ll want to compare two strings to determine whether they are the same. Extra whitespace can be confusing in much simpler situations as well.

eliminate extra whitespace from data that people enter.


To ensure that no whitespace exists at the right side of a string, use
the rstrip() method:

1
2
3
4
5
6
7
>>> favorite_language = 'python ' # 1
>>> favorite_language # 2
'python '
>>> favorite_language.rstrip() # 3
'python'
>>> favorite_language # 4
'python '

However, it is only removed temporarily. If you ask for the value
of favorite_language again, the string looks the same as when it was entered,
including the extra whitespace 4.
To remove the whitespace from the string permanently, you have to
associate the stripped value with the variable name:

1
2
3
4
>>> favorite_language = 'python '
>>> favorite_language = favorite_language.rstrip() # 1
>>> favorite_language
'python'

strip whitespace from the left side of a string using the lstrip() method
from both sides at once using strip():

1
2
3
4
5
6
7
>>> favorite_language = ' python '  # 1 
>>> favorite_language.rstrip() # 2
' python'
>>> favorite_language.lstrip() # 3
'python '
>>> favorite_language.strip() # 4
'python'

In the real world, these stripping functions are used most often to clean up
user input before it’s stored in a program.

Removing Prefixes

remove a prefix.

1
2
3
>>> nostarch_url = 'https://nostarch.com'
>>> nostarch_url.removeprefix('https://')
'nostarch.com'

Enter the name of the variable followed by a dot, and then the method
removeprefix(). Inside the parentheses, enter the prefix you want to remove
from the original string.

Like the methods for removing whitespace, removeprefix() leaves the
original string unchanged. If you want to keep the new value with the prefix removed, either reassign it to the original variable or assign it to a new
variable:

>>> simple_url = nostarch_url.removeprefix('https://')

Avoiding Syntax Errors with Strings

A syntax error occurs when Python doesn’t recognize a section of your program as valid Python code.

example

1
2
message = 'One of Python's strengths is its diverse community.'
print(message)

You’ll see the following output:

1
2
3
4
File "apostrophe.py", line 1
message = 'One of Python's strengths is its diverse community.'
1 ^
SyntaxError: unterminated string literal (detected at line 1)

Your editor’s syntax highlighting feature should help you spot some syntax errors quickly as you write your programs. If you see Python code highlighted as if it’s English or English highlighted as if it’s Python code, you probably have a mismatched quotation mark somewhere in your file.

Numbers

Integers

You can add (+), subtract (-), multiply (*), and divide (/) integers in Python.

1
2
3
4
5
6
7
8
>>> 2 + 3
5
>>> 3 - 2
1
>>> 2 * 3
6
>>> 3 / 2
1.5

uses two multiplication symbols to represent exponents:

1
2
3
4
5
6
>>> 3 ** 2
9
>>> 3 ** 3
27
>>> 10 ** 6
1000000

Python supports the order of operations too, so you can use multiple
operations in one expression. You can also use parentheses to modify the
order of operations. For example:

1
2
3
4
>>> 2 + 3*4
14
>>> (2 + 3) * 4
20

The spacing in these examples has no effect on how Python evaluates the expressions; it simply helps you more quickly spot the operations that have priority when you’re reading through the code.

Floats

Python calls any number with a decimal point a float. it refers to the fact that a decimal point Variables and can appear at any position in a number.

For the most part, you can use floats without worrying about how they
behave. Simply enter the numbers you want to use, and Python will most
likely do what you expect:

1
2
3
4
5
6
7
8
>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.2
0.4
>>> 2 *0.1
0.2
>>> 2* 0.2
0.4

However, be aware that you can sometimes get an arbitrary number of
decimal places in your answer:

1
2
3
4
>>> 0.2 + 0.1
0.30000000000000004
>>> 3 * 0.1
0.30000000000000004

This happens in all languages and is of little concern. Python tries to
find a way to represent the result as precisely as possible, which is sometimes
difficult given how computers have to represent numbers internally.

Integers and Floats

When you divide any two numbers, even if they are integers that result in a
whole number, you’ll always get a float:

1
2
>>> 4/2
2.0

If you mix an integer and a float in any other operation, you’ll get a
float as well:

1
2
3
4
5
6
>>> 1 + 2.0
3.0
>>> 2 * 3.0
6.0
>>> 3.0 ** 2
9.0

Python defaults to a float in any operation that uses a float, even if the
output is a whole number.

Underscores in Numbers

When you’re writing long numbers, you can group digits using underscores
to make large numbers more readable:

1
2
3
>>> universe_age = 14_000_000_000
>>> print(universe_age)
14000000000

Python ignores the underscores when storing these kinds of values.

Even if you don’t group the digits in threes, the value will still be unaffected. To Python, 1000 is the same as 1_000, which is the same as 10_00. This
feature works for both integers and floats.

Multiple Assignment

You can assign values to more than one variable using just a single line of
code. This can help shorten your programs and make them easier to read;

you’ll use this technique most often when initializing a set of numbers.
For example, here’s how you can initialize the variables x, y, and z to zero:

>>> x, y, z = 0, 0, 0

You need to separate the variable names with commas, and do the same
with the values, and Python will assign each value to its respective variable.
As long as the number of values matches the number of variables, Python
will match them up correctly

Constants

A constant is a variable whose value stays the same throughout the life of a
program.

Python doesn’t have built-in constant types, but Python programmers use all capital letters to indicate a variable should be treated as a constant and never be changed:

MAX_CONNECTIONS = 5000

Comments

u should add notes within your programs that describe your overall approach to the
problem you’re solving.

A comment allows you to write notes in your spoken
language, within your programs.

How Do You Write Comments?

In Python, the hash mark (#) indicates a comment. Anything following a
hash mark in your code is ignored by the Python interpreter. For example:

1
2
# Say hello to everyone.
print("Hello Python people!")

Python ignores the first line and executes the second line.
Hello Python people!

Introducing Lists

what is a list

A list is a collection of items in a particular order

Because a list usually contains more than one element, it’s a good idea to make the name of your list plural, such as letters, digits, or names

In Python, square brackets ([]) indicate a list, and individual elements in the list are separated by commas.example

1
2
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)

output:
['trek', 'cannondale', 'redline', 'specialized']

Accessing Elements in a List

Lists are ordered collections, so you can access any element in a list by
telling Python the position, or index, of the item desired. To access an element in a list, write the name of the list followed by the index of the item
enclosed in square brackets.

1
2
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[0])

output
trek

Index Positions Start at 0, Not 1

Python has a special syntax for accessing the last element in a list. If you
ask for the item at index -1, Python always returns the last item in the list:

1
2
3
bicy
cles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles[-1])

The index -2 returns the second item from the end of the list, the index -3 returns the third item from the end, and so forth.

Using Individual Values from a List

You can use individual values from a list just as you would any other variable.

1
2
3
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
message = f"My first bicycle was a {bicycles[0].title()}."
print(message)

Modifying, Adding, and Removing Elements

Most lists you create will be dynamic, meaning you’ll build a list and then
add and remove elements from it as your program runs its course.

Modifying Elements in a List

To change an element, use the name of the list followed
by the index of the element you want to change, and then provide the new
value you want that item to have.

1
2
3
4
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles[0] = 'ducati'
print(motorcycles)

output
[‘honda’, ‘yamaha’, ‘suzuki’]
[‘ducati’, ‘yamaha’, ‘suzuki’]

Adding Elements to a List

Appending Elements to the End of a List

append the item to the
list. When you append an item to a list, the new element is added to the end
of the list

1
2
3
4
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
motorcycles.append('ducati')
print(motorcycles)

To put your users in control, start by defining an empty list that
will hold the users’ values. Then append each new value provided to the list
you just created.

For example,

1
2
3
4
5
motorcycles = []
motorcycles.append('honda')
motorcycles.append('yamaha')
motorcycles.append('suzuki')
print(motorcycles)

output
[‘honda’, ‘yamaha’, ‘suzuki’]

Inserting Elements into a List

You can add a new element at any position in your list by using the insert()
method. You do this by specifying the index of the new element and the
value of the new item:
This operation shifts every other value in the list one position to the
right.

1
2
3
motorcycles = ['honda', 'yamaha', 'suzuki']
motorcycles.insert(0, 'ducati')
print(motorcycles)

output
[ducati’, ‘honda’, ‘yamaha’, ‘suzuki’]

Removing Elements from a List

Removing an Item Using the del Statement

know the position of the item you want to remove from a list, you can
use the del statement:

motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles)
del motorcycles[0]
print(motorcycles)

Removing an Item Using the pop() Method

The pop() method removes the last item in a list, but it lets you work
with that item after removing it. The term pop comes from thinking of a
list as a stack of items and popping one item off the top of the stack. In this
analogy, the top of a stack corresponds to the end of a list.

1
2
3
4
5
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles)
popped_motorcycle = motorcycles.pop()
print(motorcycles)
print(popped_motorcycle)

[‘honda’, ‘yamaha’, ‘suzuki’]
[‘honda’, ‘yamaha’]
suzuki

Popping Items from Any Position in a List
1
2
3
motorcycles = ['honda', 'yamaha', 'suzuki']
first_owned = motorcycles.pop(0)
print(f"The first motorcycle I owned was a {first_owned.title()}.")

The first motorcycle I owned was a Honda.

Remember that each time you use pop(), the item you work with is no
longer stored in the list.

when you want to delete an item from a list and not use that item in any way, use the del statement; if you want to use an item as you remove it, use the pop() method.

Removing an Item by Value

If you only know the value of the item you want to remove, you
can use the remove() method

1
2
3
4
motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati']
print(motorcycles)
motorcycles.remove('ducati')
print(motorcycles)

[‘honda’, ‘yamaha’, ‘suzuki’, ‘ducati’]
[‘honda’, ‘yamaha’, ‘suzuki’]

The remove() method deletes only the first occurrence of the value you specify. If there’s a possibility the value appears more than once in the list, you’ll need to use a loop to make sure all occurrences of the value are removed.

Organizing a List

Sometimes you’ll want
to preserve the original order of your list, and other times you’ll want to
change the original order.

Sorting a List Permanently with the sort() Method

The sort() method changes the order of the list permanently. The cars
are now in alphabetical order, and we can never revert to the original order:

1
2
3
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort()
print(cars)

[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]

o sort this list in reverse-alphabetical order

1
2
3
cars = ['bmw', 'audi', 'toyota', 'subaru']
cars.sort(reverse=True)
print(cars)

[‘toyota’, ‘subaru’, ‘bmw’, ‘audi’]

Sorting a List Temporarily with the sorted() Function

The sorted() function lets you display your list
in a particular order, but doesn’t affect the actual order of the list.

1
2
3
4
5
6
7
cars = ['bmw', 'audi', 'toyota', 'subaru']
print("Here is the original list:")
print(cars)
print("\nHere is the sorted list:")
print(sorted(cars))
print("\nHere is the original list again:")
print(cars)

output:

Here is the original list:
[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
Here is the sorted list:
[‘audi’, ‘bmw’, ‘subaru’, ‘toyota’]
1 Here is the original list again:
[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]

The sorted() function can also accept a reverse=True
argument if you want to display a list in reverse-alphabetical order.

Sorting a list alphabetically is a bit more complicated when all the values are not in lowercase

Printing a List in Reverse Order

If we originally stored the list of cars in chronological order according to when
we owned them, we could easily rearrange the list into reverse-chronological
order:

1
2
3
4
cars = ['bmw', 'audi', 'toyota', 'subaru']
print(cars)
cars.reverse()
print(cars)

[‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
[‘subaru’, ‘toyota’, ‘audi’, ‘bmw’]

Finding the Length of a List

cars = [‘bmw’, ‘audi’, ‘toyota’, ‘subaru’]
len(cars)

Avoiding Index Errors When Working with Lists

1
2
motorcycles = ['honda', 'yamaha', 'suzuki']
print(motorcycles[3])

This example results in an index error:

1
2
3
4
5
Traceback (most recent call last):
File "motorcycles.py", line 2, in <module>
print(motorcycles[3])
~~~~~~~~~~~^^^
IndexError: list index out of range

Keep in mind that whenever you want to access the last item in a list,
you should use the index -1. This will always work, even if your list has
changed size since the last time you accessed it:

motorcycles = [‘honda’, ‘yamaha’, ‘suzuki’]
print(motorcycles[-1])

output:

suzuki


The only time this approach will cause an error is when you request the
last item from an empty list:

1
2
motorcycles = []
print(motorcycles[-1])

No items are in motorcycles, so Python returns another index error:

1
2
3
4
5
6
Traceback (most recent call last):
File "motorcyles.py", line 3, in <module>
print(motorcycles[-1])
~~~~~~~~~~~^^^^
IndexError: list index out of range

If an index error occurs and you can’t figure out how to resolve it, try
printing your list or just printing the length of your list. Your list might look
much different than you thought it did, especially if it has been managed
dynamically by your program. Seeing the actual list, or the exact number of
items in your list, can help you sort out such logical errors.

Working with Lists

Looping allows you to take the same action, or set
of actions, with every item in a list

Looping Through an Entire List

Say we have a list of magicians’ names, and we want to print out each name in the list.

We could do this by retrieving each name from the list individually, but this approach could cause several problems. For one, it would
be repetitive to do this with a long list of names. Also, we’d have to change
our code each time the list’s length changed. Using a for loop avoids both of
these issues by letting Python manage these issues internally.

1
2
3
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)

alice
david
carolina

A Closer Look at Looping

for magician in magicians:

This line tells Python to retrieve the first value from the list magicians and associate it with the variable magician.

the set of steps is repeated once for each item in the list, no matter how many items
are in the list.

you can choose
any name you want for the temporary variable that will be associated with
each value in the list. However, it’s helpful to choose a meaningful name
that represents a single item from the list.

Using singular and plural names can help
you identify whether a section of code is working with a single element from
the list or the entire list.

Doing More Work Within a for Loop

1
2
3
4
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")

Alice, that was a great trick!
I can’t wait to see your next trick, Alice.

David, that was a great trick!
I can’t wait to see your next trick, David.

Carolina, that was a great trick!
I can’t wait to see your next trick, Carolina.

Doing Something After a for Loop

Any lines of code after the for loop that are not indented are executed
once without repetition.

1
2
3
4
5
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you, everyone. That was a great magic show!")

Alice, that was a great trick!
I can’t wait to see your next trick, Alice.

David, that was a great trick!
Working with Lists 53
I can’t wait to see your next trick, David.

Carolina, that was a great trick!
I can’t wait to see your next trick, Carolina.

Thank you, everyone. That was a great magic show!

Avoiding Indentation Errors

Python uses indentation to determine how a line, or group of lines, is related
to the rest of the program.

common indentation errors. For example, people
sometimes indent lines of code that don’t need to be indented or forget
to indent lines that need to be indented.

Forgetting to Indent

1
2
3
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
1
2
3
4
File "magicians.py", line 3
print(magician)
^
IndentationError: expected an indented block after 'for' statement on line 2

Forgetting to Indent Additional Lines

This is a logical error. The syntax is valid Python code, but the code does
not produce the desired result because a problem occurs in its logic. If you
expect to see a certain action repeated once for each item in a list and it’s
executed only once, determine whether you need to simply indent a line or
a group of lines.

1
2
3
4
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")

output:

Alice, that was a great trick!
David, that was a great trick!
Carolina, that was a great trick!
I can’t wait to see your next trick, Carolina.

Indenting Unnecessarily

1
2
message = "Hello Python world!"
print(message)

File “hello_world.py”, line 2
print(message)
^
IndentationError: unexpected indent

You can avoid unexpected indentation errors by indenting only when you have a specific reason to do so.

Indenting Unnecessarily After the Loop

1
2
3
4
5
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(f"{magician.title()}, that was a great trick!")
print(f"I can't wait to see your next trick, {magician.title()}.\n")
print("Thank you everyone, that was a great magic show!")
1
2
3
4
5
6
7
8
9
10
11
12
Alice, that was a great trick!
I can't wait to see your next trick, Alice.

Thank you everyone, that was a great magic show!
David, that was a great trick!
I can't wait to see your next trick, David.

Thank you everyone, that was a great magic show!
Carolina, that was a great trick!
I can't wait to see your next trick, Carolina.

Thank you everyone, that was a great magic show!

This is another logical error, similar to the one in “Forgetting to Indent
Additional Lines” on page 54. Because Python doesn’t know what you’re
trying to accomplish with your code, it will run all code that is written in
valid syntax. If an action is repeated many times when it should be executed
only once, you probably need to unindent the code for that action.

Forgetting the Colon

1
2
3
magicians = ['alice', 'david', 'carolina']
for magician in magicians
print(magician)
1
2
3
4
 File "magicians.py", line 2
for magician in magicians
^
SyntaxError: expected ':'

Making Numerical Lists

Using the range() Function

range(stop) -> range object range(start, stop[, step]) -> range object

Return an object that produces a sequence of integers from start (inclusive) to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, …, j-1. start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3. These are exactly the valid indices for a list of 4 elements. When step is given, it specifies the increment (or decrement).

generate a series of numbers.

1
2
for value in range(1, 5):
print(value)

output:
1
2
3
4

You can also pass range() only one argument, and it will start the
sequence of numbers at 0.

Using range() to Make a List of Numbers

convert the results of range()
directly into a list using the list() function.

1
2
numbers = list(range(1, 6))
print(numbers)

This is the result:
[1, 2, 3, 4, 5]


1
2
3
4
5
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares)

[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Simple Statistics with a List of Numbers

1
2
3
4
5
6
7
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45

List Comprehensions

A list comprehension allows you to generate
this same list in just one line of code. A list comprehension combines the
for loop and the creation of new elements into one line, and automatically
appends each new element.

1
2
squares = [value**2 for value in range(1, 11)]
print(squares)

output:
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Working with Part of a List

Slicing a List

To make a slice, you specify the index of the first and last elements you want
to work with.
n, Python stops one item before the
second index you specify.

1
2
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3])

output:
[‘charles’, ‘martina’, ‘michael’]

1
2
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4])

[‘charles’, ‘martina’, ‘michael’, ‘florence’]

1
2
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:])

[‘michael’, ‘florence’, ‘eli’]

1
2
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:])

Looping Through a Slice

1
2
3
4
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print("Here are the first three players on my team:")
1 for player in players[:3]:
print(player.title())

Here are the first three players on my team:
Charles
Martina
Michael

Copying a List

1
2
3
4
5
6
7
8
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)

My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘ice cream’]

1
2
3
4
5
6
7
8
9
my_foods = ['pizza', 'falafel', 'carrot cake']
# This doesn't work:
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print("My favorite foods are:")
print(my_foods)
print("\nMy friend's favorite foods are:")
print(friend_foods)

My favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’, ‘ice cream’]
My friend’s favorite foods are:
[‘pizza’, ‘falafel’, ‘carrot cake’, ‘cannoli’, ‘ice cream’]

Tuples

Lists work well for storing collections of items that can change throughout the
life of a program.

Python refers to values that cannot change as
immutable, and an immutable list is called a tuple.

Defining a Tuple

A tuple looks just like a list, except you use parentheses instead of square
brackets.

1
2
3
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])

output
200
50


1
2
dimensions = (200, 50)
dimensions[0] = 250
1
2
3
4
Traceback (most recent call last):
File "dimensions.py", line 2, in <module>
dimensions[0] = 250
TypeError: 'tuple' object does not support item assignment

Tuples are technically defined by the presence of a comma; the parentheses make them
look neater and more readable. If you want to define a tuple with one element, you
need to include a trailing comma:
my_t = (3,)

Looping Through All Values in a Tuple

1
2
3
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)

200
50

Writing Over a Tuple

Although you can’t modify a tuple, you can assign a new value to a variable
that represents a tuple

1
2
3
4
5
6
7
8
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)

if Statements 0

Programming often involves examining
a set of conditions and deciding which
action to take based on those conditions.
Python’s if statement allows you to examine
the current state of a program and respond appropriately to that state.

a example

1
2
3
4
5
6
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())

output

Audi
BMW
Subaru
Toyota

Conditional Tests

an expression that can be evaluated as
True or False and is called a conditional test. Python uses the values True and
False to decide whether the code in an if statement should be executed.

Checking for Equality

equality operator returns
True if the values on the left and right side of the operator match, and False if
they don’t match.

1
2
3
>>> car = 'audi'
>>> car == 'bmw'
False

Ignoring Case When Checking for Equality

1
2
3
4
5
6
7
>>> car = 'Audi'
>>> car == 'audi'
False
>>> car.lower() == 'audi'
True
>>> car
'Audi'

Checking for Inequality

1
2
3
requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")

Hold the anchovies!

Numerical Comparisons

mathematical comparisons

1
2
3
4
5
6
7
8
9
>>> age = 19
>>> age < 21
True
>>> age <= 21
True
>>> age > 21
False
>>> age >= 21
False

Checking Multiple Conditions

Using and to Check Multiple Conditions

To check whether two conditions are both True simultaneously, use the keyword and to combine the two conditional tests; if each test passes, the overall
expression evaluates to True. If either test fails or if both tests fail, the expression evaluates to False.

1
2
3
4
5
6
7
>>> age_0 = 22
>>> age_1 = 18
>>> age_0 >= 21 and age_1 >= 21
False
>>> age_1 = 22
>>> age_0 >= 21 and age_1 >= 21
True

To improve readability, you can use parentheses around the individual
tests
(age_0 >= 21) and (age_1 >= 21)

Checking Whether a Value Is in a List

To find out whether a particular value is already in a list, use the keyword in.

1
2
3
4
5
>>> requested_toppings = ['mushrooms', 'onions', 'pineapple']
>>> 'mushrooms' in requested_toppings
True
>>> 'pepperoni' in requested_toppings
False

Checking Whether a Value Is Not in a List

1
2
3
4
banned_users = ['andrew', 'carolina', 'david']
user = 'marie'
if user not in banned_users:
print(f"{user.title()}, you can post a response if you wish.")

Marie, you can post a response if you wish.

Boolean Expressions

A Boolean expression is just another name for a conditional
test. A Boolean value is either True or False, just like the value of a conditional
expression after it has been evaluated.

if Statements

Simple if Statements

if conditional_test:
do something

if-else Statements

take one action when a conditional test passes and a different action in all other cases.
An if-else block is similar to a simple if statement, but the else statement allows
you to define an action or set of actions that are executed when the conditional test fails.

1
2
3
4
5
6
7
age = 17
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
else:
print("Sorry, you are too young to vote.")
print("Please register to vote as soon as you turn 18!")

Sorry, you are too young to vote.
Please register to vote as soon as you turn 18!

The if-elif-else Chain

Python’s if-elif-else syntax. Python executes only one
block in an if-elif-else chain. It runs each conditional test in order, until
one passes. When a test passes, the code following that test is executed and
Python skips the rest of the tests.

1
2
3
4
5
6
7
age = 12
if age < 4:
print("Your admission cost is $0.")
elif age < 18:
print("Your admission cost is $25.")
else:
print("Your admission cost is $40.")

Your admission cost is $25.

Using Multiple elif Blocks

1
2
3
4
5
6
7
8
9
10
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
else:
price = 20
print(f"Your admission cost is ${price}.")

Omitting the else Block

Other times, it’s clearer to use an additional elif statement that catches the specific condition of interest

1
2
3
4
5
6
7
8
9
10
age = 12
if age < 4:
price = 0
elif age < 18:
price = 25
elif age < 65:
price = 40
elif age >= 65:
price = 20
print(f"Your admission cost is ${price}.")

The else block is a catchall statement. It matches any condition that
wasn’t matched by a specific if or elif test, and that can sometimes include
invalid or even malicious data.
If you have a specific final condition you’re
testing for, consider using a final elif block and omit the else block. As a
result, you’ll be more confident that your code will run only under the correct conditions.

Testing Multiple Conditions

The if-elif-else chain is powerful, but it’s only appropriate to use when you
just need one test to pass. As soon as Python finds one test that passes, it
skips the rest of the tests.

sometimes it’s important to check all conditions of interest. In
this case, you should use a series of simple if statements with no elif or else
blocks. This technique makes sense when more than one condition could
be True, and you want to act on every condition that is True.

1
2
3
4
5
6
7
8
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")

Adding mushrooms.
Adding extra cheese.

Finished making your pizza!

wrong:

1
2
3
4
5
6
7
8
requested_toppings = ['mushrooms', 'extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms.")
elif 'pepperoni' in requested_toppings:
print("Adding pepperoni.")
elif 'extra cheese' in requested_toppings:
print("Adding extra cheese.")
print("\nFinished making your pizza!")

Adding mushrooms.

Finished making your pizza!

Using if Statements with Lists

Checking for Special Items

1
2
3
4
5
6
7
requested_toppings = ['mushrooms', 'green peppers', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping == 'green peppers':
print("Sorry, we are out of green peppers right now.")
else:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")

Adding mushrooms.
Sorry, we are out of green peppers right now.
Adding extra cheese.

Finished making your pizza!

Checking That a List Is Not Empty

we won’t be able to assume
that a list has any items in it each time a loop is run. In this situation, it’s
useful to check whether a list is empty before running a for loop.

1
2
3
4
5
6
7
requested_toppings = []
if requested_toppings:
for requested_topping in requested_toppings:
print(f"Adding {requested_topping}.")
print("\nFinished making your pizza!")
else:
print("Are you sure you want a plain pizza?")

Are you sure you want a plain pizza?

Using Multiple Lists

1
2
3
4
5
6
7
8
available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese']
requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
for requested_topping in requested_toppings:
if requested_topping in available_toppings:
print(f"Adding {requested_topping}.")
else:
print(f"Sorry, we don't have {requested_topping}.")
print("\nFinished making your pizza!")

Adding mushrooms.
Sorry, we don’t have french fries.
Adding extra cheese.

Finished making your pizza!

Dictionaries

A Simple Dictionary

1
2
3
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])

green
5

Working with Dictionaries

A dictionary in Python is a collection of key-value pairs. Each key is connected to
a value, and you can use a key to access the value associated with that key. A
key’s value can be a number, a string, a list, or even another dictionary.

a dictionary is wrapped in braces ({}) with a series of key-value
pairs inside the braces

A key-value pair is a set of values associated with each other. When you
provide a key, Python returns the value associated with that key. Every key is
connected to its value by a colon, and individual key-value pairs are separated
by commas.

Accessing Values in a Dictionary

To get the value associated with a key, give the name of the dictionary and
then place the key inside a set of square brackets

Adding New Key-Value Pairs

To add a new key-value pair, you would give the
name of the dictionary followed by the new key in square brackets, along
with the new value.

1
2
3
4
5
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘green’, ‘points’: 5, ‘x_position’: 0, ‘y_position’: 25}

Dictionaries retain the order in which they were defined

Starting with an Empty Dictionary

1
2
3
4
alien_0 = {}
alien_0['color'] = 'green'
alien_0['points'] = 5
print(alien_0)

{‘color’: ‘green’, ‘points’: 5}

Modifying Values in a Dictionary

To modify a value in a dictionary, give the name of the dictionary with the
key in square brackets and then the new value you want associated with
that key.

1
2
3
4
alien_0 = {'color': 'green'}
print(f"The alien is {alien_0['color']}.")
alien_0['color'] = 'yellow'
print(f"The alien is now {alien_0['color']}.")

The alien is green.
The alien is now yellow.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
print(f"Original position: {alien_0['x_position']}")
# Move the alien to the right.
# Determine how far to move the alien based on its current speed.
if alien_0['speed'] == 'slow':
x_increment = 1
elif alien_0['speed'] == 'medium':
x_increment = 2
else:
# This must be a fast alien.
x_increment = 3
# The new position is the old position plus the increment.
alien_0['x_position'] = alien_0['x_position'] + x_increment
print(f"New position: {alien_0['x_position']}")

Original x-position: 0
New x-position: 2

Removing Key-Value Pairs

1
2
3
4
alien_0 = {'color': 'green', 'points': 5}
print(alien_0)
del alien_0['points']
print(alien_0)

A Dictionary of Similar Objects

It’s good practice to include a comma after the
last key-value pair as well, so you’re ready to add a new key-value pair on the
next line.

1
2
3
4
5
6
7
8
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
language = favorite_languages['sarah'].title()
print(f"Sarah's favorite language is {language}.")

Using get() to Access Values

1
2
alien_0 = {'color': 'green', 'speed': 'slow'}
print(alien_0['points'])
1
2
3
4
5
Traceback (most recent call last):
File "alien_no_points.py", line 2, in <module>
print(alien_0['points'])
~~~~~~~^^^^^^^^^^
KeyError: 'points'

As a second optional
argument, you can pass the value to be returned if the key doesn’t exist:

1
2
3
alien_0 = {'color': 'green', 'speed': 'slow'}
point_value = alien_0.get('points', 'No point value assigned.')
print(point_value)

No point value assigned.

If you leave out the second argument in the call to get() and the key doesn’t exist, Python will return the value None. The special value None means “no value exists.” This is not an error: it’s a special value meant to indicate the absence of a value.

Looping Through a Dictionary

Looping Through All Key-Value Pairs

1
2
3
4
5
6
7
8
9
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}

for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")

Key: username
Value: efermi
Key: first
Value: enrico
Key: last
Value: fermi

1
2
3
4
5
6
7
8
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
for name, language in favorite_languages.items():
print(f"{name.title()}'s favorite language is {language.title()}.")

Jen’s favorite language is Python.
Sarah’s favorite language is C.
Edward’s favorite language is Rust.
Phil’s favorite language is Python.

Looping Through All the Keys in a Dictionary

1
2
3
4
5
6
7
8
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
for name in favorite_languages.keys():
print(name.title())

Jen
Sarah
Edward
Phil

Looping through the keys is actually the default behavior when looping
through a dictionary, so this code would have exactly the same output if you
wrote:

for name in favorite_languages:

1
2
3
4
5
6
7
8
9
favorite_languages = {
--snip--
}
friends = ['phil', 'sarah']
for name in favorite_languages.keys():
print(f"Hi {name.title()}.")
if name in friends:
language = favorite_languages[name].title()
print(f"\t{name.title()}, I see you love {language}!")

Hi Jen.
Hi Sarah.
Sarah, I see you love C!
Hi Edward.
Hi Phil.
Phil, I see you love Python!

The keys() method isn’t just for looping: it actually returns a sequence of
all the keys

1
2
3
4
5
favorite_languages = {
--snip--
}
if 'erin' not in favorite_languages.keys():
print("Erin, please take our poll!")

Erin, please take our poll!

Looping Through a Dictionary’s Keys in a Particular Order

Looping through a dictionary returns the items in the same order they
were inserted.

1
2
3
4
5
6
7
8
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
for name in sorted(favorite_languages.keys()):
print(f"{name.title()}, thank you for taking the poll.")

Edward, thank you for taking the poll.
Jen, thank you for taking the poll.
Phil, thank you for taking the poll.
Sarah, thank you for taking the poll.

Looping Through All Values in a Dictionary

use the values() method to return a sequence of values without any
keys

1
2
3
4
5
6
7
8
9
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'rust',
'phil': 'python',
}
print("The following languages have been mentioned:")
for language in favorite_languages.values():
print(language.title())

The following languages have been mentioned:
Python
C
Rust
Python

To see each language chosen without repetition, we can use a set. A set
is a collection in which each item must be unique:

1
2
3
4
5
6
favorite_languages = {
--snip--
}
print("The following languages have been mentioned:")
for language in set(favorite_languages.values()):
print(language.title())

The following languages have been mentioned:
Python
C
Rust

You can build a set directly using braces and separating the elements with commas:

languages = {‘python’, ‘rust’, ‘python’, ‘c’}
languages
{‘rust’, ‘python’, ‘c’}

Unlike
lists and dictionaries, sets do not retain items in any specific order.

Nesting

store multiple dictionaries in a list, or a list of
items as a value in a dictionary. This is called nesting. You can nest dictionaries inside a list, a list of items inside a dictionary, or even a dictionary inside
another dictionary.

1
2
3
4
5
6
alien_0 = {'color': 'green', 'points': 5}
alien_1 = {'color': 'yellow', 'points': 10}
alien_2 = {'color': 'red', 'points': 15}
aliens = [alien_0, alien_1, alien_2]
for alien in aliens:
print(alien)

{‘color’: ‘green’, ‘points’: 5}
{‘color’: ‘yellow’, ‘points’: 10}
{‘color’: ‘red’, ‘points’: 15}

1
2
3
4
5
6
7
8
9
10
11
12
# Make an empty list for storing aliens.
aliens = []
# Make 30 green aliens.
for alien_number in range(30):
new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
aliens.append(new_alien)
# Show the first 5 aliens.
for alien in aliens[:5]:
print(alien)
print("...")
# Show how many aliens have been created.
print(f"Total number of aliens: {len(aliens)}")

{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}
{‘color’: ‘green’, ‘points’: 5, ‘speed’: ‘slow’}

Total number of aliens: 30

A List in a Dictionary

1
2
3
4
5
6
7
8
9
10
# Store information about a pizza being ordered.
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
# Summarize the order.
print(f"You ordered a {pizza['crust']}-crust pizza "
"with the following toppings:")
for topping in pizza['toppings']:
print(f"\t{topping}")

You ordered a thick-crust pizza with the following toppings:
mushrooms
extra cheese

1
2
3
4
5
6
7
8
9
10
favorite_languages = {
'jen': ['python', 'rust'],
'sarah': ['c'],
'edward': ['rust', 'go'],
'phil': ['python', 'haskell'],
}
for name, languages in favorite_languages.items():
print(f"\n{name.title()}'s favorite languages are:")
for language in languages:
print(f"\t{language.title()}")

Jen’s favorite languages are:
Python
Rust
Sarah’s favorite languages are:
C
Edward’s favorite languages are:
Rust
Go
Phil’s favorite languages are:
Python
Haskell

A Dictionary in a Dictionary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
users = {
'aeinstein': {
'first': 'albert',
'last': 'einstein',
'location': 'princeton',
},
'mcurie': {
'first': 'marie',
'last': 'curie',
'location': 'paris',
},
}
for username, user_info in users.items():
print(f"\nUsername: {username}")
full_name = f"{user_info['first']} {user_info['last']}"
location = user_info['location']
print(f"\tFull name: {full_name.title()}")
print(f"\tLocation: {location.title()}")

Username: aeinstein
Full name: Albert Einstein
Location: Princeton
Username: mcurie
Full name: Marie Curie
Location: Paris

Notice that the structure of each user’s dictionary is identical. Although
not required by Python, this structure makes nested dictionaries easier to
work with. If each user’s dictionary had different keys, the code inside the
for loop would be more complicated.

User Input and while Loops

How the input() Function Works

The input() function pauses your program and waits for the user to enter
some text. Once Python receives the user’s input, it assigns that input to a
variable to make it convenient for you to work with.

message = input(“Tell me something, and I will repeat it back to you: “)
print(message)

Writing Clear Prompts

include a clear, easy-tofollow prompt that tells the user exactly what kind of information you’re
looking for. Any statement that tells the user what to enter should work.

Add a space at the end of your prompts (after the colon in the preceding example) to separate the prompt from the user’s response and to make
it clear to your user where to enter their text.

1
2
name = input("Please enter your name: ")
print(f"\nHello, {name}!")

Please enter your name: Eric
Hello, Eric!

1
2
3
4
prompt = "If you share your name, we can personalize the messages you see."
prompt += "\nWhat is your first name? "
name = input(prompt)
print(f"\nHello, {name}!")

If you share your name, we can personalize the messages you see.
What is your first name? Eric
Hello, Eric!

Using int() to Accept Numerical Input

1
2
3
4
>>> age = input("How old are you? ")
How old are you? 21
>>> age
'21'
1
2
3
4
5
6
>>> age = input("How old are you? ")
How old are you? 21
>>> age >= 18
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: '>=' not supported between instances of 'str' and 'int'

age = input(“How old are you? “)
How old are you? 21
age = int(age)
age >= 18
True

The Modulo Operator

modulo operator (%),
which divides one number by another number and returns the remainder:

1
2
3
4
5
6
number = input("Enter a number, and I'll tell you if it's even or odd: ")
number = int(number)
if number % 2 == 0:
print(f"\nThe number {number} is even.")
else:
print(f"\nThe number {number} is odd.")

Introducing while Loops

1
2
3
4
current_number = 1
while current_number <= 5:
print(current_number)
current_number += 1

Letting the User Choose When to Quit

1
2
3
4
5
6
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
message = ""
while message != 'quit':
message = input(prompt)
print(message)

Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. Hello everyone!
Hello everyone!
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. Hello again.
Hello again.
Tell me something, and I will repeat it back to you:
Enter ‘quit’ to end the program. quit
quit

Using a Flag

more complicated programs in
which many different events could cause the program to stop running?
trying to test all these conditions in one while
statement becomes complicated and difficult.

For a program that should run only as long as many conditions are
true, you can define one variable that determines whether or not the entire
program is active. This variable, called a flag, acts as a signal to the program. We can write our programs so they run while the flag is set to True
and stop running when any of several events sets the value of the flag to
False.

1
2
3
4
5
6
7
8
9
prompt = "\nTell me something, and I will repeat it back to you:"
prompt += "\nEnter 'quit' to end the program. "
active = True
while active:
message = input(prompt)
if message == 'quit':
active = False
else:
print(message)

Using break to Exit a Loop

To exit a while loop immediately without running any remaining code in
the loop, regardless of the results of any conditional test, use the break statement.

1
2
3
4
5
6
7
8
prompt = "\nPlease enter the name of a city you have visited:"
prompt += "\n(Enter 'quit' when you are finished.) "
while True:
city = input(prompt)
if city == 'quit':
break
else:
print(f"I'd love to go to {city.title()}!")

Using continue in a Loop

Rather than breaking out of a loop entirely without executing the rest of its
code, you can use the continue statement to return to the beginning of the
loop, based on the result of a conditional test.

1
2
3
4
5
6
current_number = 0
while current_number < 10:
current_number += 1
if current_number % 2 == 0:
continue
print(current_number)

1
3
5
7
9

Avoiding Infinite Loops

1
2
3
4
# This loop runs forever!
x = 1
while x <= 5:
print(x)

If
your program gets stuck in an infinite loop, press CTRL-C or just close the
terminal window displaying your program’s output.

Using a while Loop with Lists and Dictionaries

A for loop is effective for looping through a list, but you shouldn’t modify a list inside a for loop because Python will have trouble keeping track of
the items in the list. To modify a list as you work through it, use a while loop

Moving Items from One List to Another

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Start with users that need to be verified,
# and an empty list to hold confirmed users.
unconfirmed_users = ['alice', 'brian', 'candace']
confirmed_users = []
# Verify each user until there are no more unconfirmed users.
# Move each verified user into the list of confirmed users.
while unconfirmed_users:
current_user = unconfirmed_users.pop()
print(f"Verifying user: {current_user.title()}")
confirmed_users.append(current_user)
# Display all confirmed users.
print("\nThe following users have been confirmed:")
for confirmed_user in confirmed_users:
print(confirmed_user.title())

Verifying user: Candace
Verifying user: Brian
Verifying user: Alice

The following users have been confirmed:
Candace
Brian
Alice

Removing All Instances of Specific Values from a List

1
2
3
4
5
pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
print(pets)
while 'cat' in pets:
pets.remove('cat')
print(pets)

[‘dog’, ‘cat’, ‘dog’, ‘goldfish’, ‘cat’, ‘rabbit’, ‘cat’]
[‘dog’, ‘dog’, ‘goldfish’, ‘rabbit’]

Filling a Dictionary with User Input

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
responses = {}
# Set a flag to indicate that polling is active.
polling_active = True
while polling_active:
# Prompt for the person's name and response.
name = input("\nWhat is your name? ")
response = input("Which mountain would you like to climb someday? ")
# Store the response in the dictionary.
responses[name] = response
# Find out if anyone else is going to take the poll.
repeat = input("Would you like to let another person respond? (yes/ no) ")
if repeat == 'no':
polling_active = False
# Polling is complete. Show the results.
print("\n--- Poll Results ---")
for name, response in responses.items():
print(f"{name} would like to climb {response}.")

What is your name? Eric
Which mountain would you like to climb someday? Denali
Would you like to let another person respond? (yes/ no) yes
What is your name? Lynn
Which mountain would you like to climb someday? Devil’s Thumb
Would you like to let another person respond? (yes/ no) no
— Poll Results —
Eric would like to climb Denali.
Lynn would like to climb Devil’s Thumb.

Functions

Defining a Function

1
2
3
4
def greet_user():
"""Display a simple greeting."""
print("Hello!")
greet_user()

The text on the second line is a comment called a docstring, which
describes what the function does. When Python generates documentation
for the functions in your programs, it looks for a string immediately after
the function’s definition. These strings are usually enclosed in triple quotes,
which lets you write multiple lines.

Passing Information to a Function

1
2
3
4
def greet_user(username):
"""Display a simple greeting."""
print(f"Hello, {username.title()}!")
greet_user('jesse')

Hello, Jesse!

Arguments and Parameters

The variable username in the definition of greet_user() is an example of a
parameter, a piece of information the function needs to do its job. The value
‘jesse’ in greet_user(‘jesse’) is an example of an argument. An argument is
a piece of information that’s passed from a function call to a function.

Passing Arguments

Positional Arguments

def describe_pet(animal_type, pet_name):
“””Display information about a pet.”””
print(f”\nI have a {animal_type}.”)
print(f”My {animal_type}’s name is {pet_name.title()}.”)
describe_pet(‘hamster’, ‘harry’)

Multiple Function Calls

1
2
3
4
5
6
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('hamster', 'harry')
describe_pet('dog', 'willie')

I have a hamster.
My hamster’s name is Harry.
I have a dog.
My dog’s name is Willie.

Order Matters in Positional Arguments
1
2
3
4
5
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet('harry', 'hamster')

I have a harry.
My harry’s name is Hamster.

Keyword Arguments

1
2
3
4
5
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(animal_type='hamster', pet_name='harry')

Default Values

When writing a function, you can define a default value for each parameter.
If an argument for a parameter is provided in the function call, Python
uses the argument value. If not, it uses the parameter’s default value.

When you use default values, any parameter with a default value needs to be listed
after all the parameters that don’t have default values. This allows Python to continue interpreting positional arguments correctly.

1
2
3
4
5
def describe_pet(pet_name, animal_type='dog'):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet(pet_name='willie')

I have a dog.
My dog’s name is Willie.

describe_pet(‘willie’)
describe_pet(pet_name=’harry’, animal_type=’hamster’)

Equivalent Function Calls

Because positional arguments, keyword arguments, and default values can
all be used together, you’ll often have several equivalent ways to call a function

1
2
3
4
5
6
7
8
def describe_pet(pet_name, animal_type='dog'):
# A dog named Willie.
describe_pet('willie')
describe_pet(pet_name='willie')
# A hamster named Harry.
describe_pet('harry', 'hamster')
describe_pet(pet_name='harry', animal_type='hamster')
describe_pet(animal_type='hamster', pet_name='harry')

Avoiding Argument Errors

1
2
3
4
5
def describe_pet(animal_type, pet_name):
"""Display information about a pet."""
print(f"\nI have a {animal_type}.")
print(f"My {animal_type}'s name is {pet_name.title()}.")
describe_pet()
1
2
3
4
5
6
7
Traceback (most recent call last):
File "pets.py", line 6, in <module>
describe_pet()
^^^^^^^^^^^^^^
TypeError: describe_pet() missing 2 required positional arguments:
'animal_type' and 'pet_name'

Return Values

1
2
3
4
5
6
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

Making an Argument Optional

1
2
3
4
5
6
7
8
def get_formatted_name(first_name, middle_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {middle_name} {last_name}"
return full_name.title()
musician = get_formatted_name('john', 'lee', 'hooker')
print(musician)
musician = get_formatted_name('jimi', 'hendrix')
print(musician)

John Lee Hooker
Jimi Hendrix

Returning a Dictionary

1
2
3
4
5
6
7
8
def build_person(first_name, last_name, age=None):
"""Return a dictionary of information about a person."""
person = {'first': first_name, 'last': last_name}
if age:
person['age'] = age
return person
musician = build_person('jimi', 'hendrix', age=27)
print(musician)

Using a Function with a while Loop

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = f"{first_name} {last_name}"
return full_name.title()
while True:
print("\nPlease tell me your name:")
print("(enter 'q' at any time to quit)")
f_name = input("First name: ")
if f_name == 'q':
break
l_name = input("Last name: ")
if l_name == 'q':
break
formatted_name = get_formatted_name(f_name, l_name)
print(f"\nHello, {formatted_name}!")

Passing a List

1
2
3
4
5
6
7
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
msg = f"Hello, {name.title()}!"
print(msg)
usernames = ['hannah', 'ty', 'margot']
greet_users(usernames)

Hello, Hannah!
Hello, Ty!
Hello, Margot!

Modifying a List in a Function

1
2
3
4
5
6
7
8
9
10
11
12
13
# Start with some designs that need to be printed.
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
# Simulate printing each design, until none are left.
# Move each design to completed_models after printing.
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
# Display all completed models.
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def print_models(unprinted_designs, completed_models):
"""
Simulate printing each design, until none are left.
144 Chapter 8
Move each design to completed_models after printing.
"""
while unprinted_designs:
current_design = unprinted_designs.pop()
print(f"Printing model: {current_design}")
completed_models.append(current_design)
def show_completed_models(completed_models):
"""Show all the models that were printed."""
print("\nThe following models have been printed:")
for completed_model in completed_models:
print(completed_model)
unprinted_designs = ['phone case', 'robot pendant', 'dodecahedron']
completed_models = []
print_models(unprinted_designs, completed_models)
show_completed_models(completed_models)

Preventing a Function from Modifying a List

You can send a copy of a list to a function like this:
function_name(list_name[:])

print_models(unprinted_designs[:], completed_models)

Passing an Arbitrary Number of Arguments

1
2
3
4
5
def make_pizza(*toppings):
"""Print the list of toppings that have been requested."""
print(toppings)
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

(‘pepperoni’,)
(‘mushrooms’, ‘green peppers’, ‘extra cheese’)

1
2
3
4
5
6
7
8
def make_pizza(*toppings):
"""Summarize the pizza we are about to make."""
Functions 147
print("\nMaking a pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza('pepperoni')
make_pizza('mushrooms', 'green peppers', 'extra cheese')

Making a pizza with the following toppings:

  • pepperoni
    Making a pizza with the following toppings:
  • mushrooms
  • green peppers
  • extra cheese

Mixing Positional and Arbitrary Arguments

If you want a function to accept several different kinds of arguments, the
parameter that accepts an arbitrary number of arguments must be placed
last in the function definition. Python matches positional and keyword
arguments first and then collects any remaining arguments in the final
parameter.

1
2
3
4
5
6
7
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Making a 16-inch pizza with the following toppings:

  • pepperoni

Making a 12-inch pizza with the following toppings:

  • mushrooms
  • green peppers
  • extra cheese

Using Arbitrary Keyword Arguments

def build_profile(first, last, **user_info):
“””Build a dictionary containing everything we know about a user.”””
user_info[‘first_name’] = first
user_info[‘last_name’] = last
return user_info
user_profile = build_profile(‘albert’, ‘einstein’,
location=’princeton’,
field=’physics’)
print(user_profile)

{‘location’: ‘princeton’, ‘field’: ‘physics’,
‘first_name’: ‘albert’, ‘last_name’: ‘einstein’}

write functions that accept as many key-value
pairs as the calling statement provides

You’ll often see the parameter name **kwargs used to collect nonspecific keyword
arguments.

Storing Your Functions in Modules

storing your functions in a separate file called a module and then importing
that module into your main program. An import statement tells Python to
make the code in a module available in the currently running program file

Importing an Entire Module

1
2
3
4
5
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")

import pizza
pizza.make_pizza(16, ‘pepperoni’)
pizza.make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

Importing Specific Functions

from module_name import function_name

from module_name import function_0, function_1, function_2

1
2
3
from pizza import make_pizza
make_pizza(16, 'pepperoni')
make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Using as to Give a Function an Alias

1
2
3
from pizza import make_pizza as mp
mp(16, 'pepperoni')
mp(12, 'mushrooms', 'green peppers', 'extra cheese')

Using as to Give a Module an Alias

1
2
3
import pizza as p
p.make_pizza(16, 'pepperoni')
p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

Importing All Functions in a Module

from pizza import *
make_pizza(16, ‘pepperoni’)
make_pizza(12, ‘mushrooms’, ‘green peppers’, ‘extra cheese’)

The best approach is to import the function or functions you want, or
import the entire module and use the dot notation. This leads to clear code
that’s easy to read and understand

Classes

Creating and Using a Class

1
2
3
4
5
6
7
8
9
10
11
12
class Dog:
"""A simple attempt to model a dog."""
def __init__(self, name, age):
"""Initialize name and age attributes."""
self.name = name
self.age = age
def sit(self):
"""Simulate a dog sitting in response to a command."""
print(f"{self.name} is now sitting.")
def roll_over(self):
"""Simulate rolling over in response to a command."""
print(f"{self.name} rolled over!")

The __init__() method is a special method
that Python runs automatically whenever we create a new instance based
on the Dog class. This method has two leading underscores and two trailing underscores, a convention that helps prevent Python’s default method
names from conflicting with your method names.

The self parameter is required in the method definition, and
it must come first, before the other parameters. It must be included in
the definition because when Python calls this method later (to create an
instance of Dog), the method call will automatically pass the self argument.
Every method call associated with an instance automatically passes self,
which is a reference to the instance itself; it gives the individual instance
access to the attributes and methods in the class

Making an Instance from a Class

1
2
3
my_dog = Dog('Willie', 6)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")

My dog’s name is Willie.
My dog is 6 years old.

Calling Methods

1
2
3
4
5
class Dog:
--snip--
my_dog = Dog('Willie', 6)
my_dog.sit()
my_dog.roll_over()

Willie is now sitting.
Willie rolled over!

Creating Multiple Instances

1
2
3
4
5
6
7
8
9
10
class Dog:
--snip--
my_dog = Dog('Willie', 6)
your_dog = Dog('Lucy', 3)
print(f"My dog's name is {my_dog.name}.")
print(f"My dog is {my_dog.age} years old.")
my_dog.sit()
print(f"\nYour dog's name is {your_dog.name}.")
print(f"Your dog is {your_dog.age} years old.")
your_dog.sit()

My dog’s name is Willie.
My dog is 6 years old.
Willie is now sitting.
Your dog’s name is Lucy.
Your dog is 3 years old.
Lucy is now sitting.

Working with Classes and Instances

1
2
3
4
5
6
7
8
9
10
11
12
13
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
my_new_car = Car('audi', 'a4', 2024)
print(my_new_car.get_descriptive_name())

2024 Audi A4

Setting a Default Value for an Attribute

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Car:
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
--snip--
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
my_new_car = Car('audi', 'a4', 2024)
print(my_new_car.get_descriptive_name())
my_new_car.read_odometer()

2024 Audi A4
This car has 0 miles on it.

Modifying Attribute Values

Modifying an Attribute’s Value Directly
1
2
3
4
5
6
class Car:
--snip--
my_new_car = Car('audi', 'a4', 2024)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

2024 Audi A4
This car has 23 miles on it.

Modifying an Attribute’s Value Through a Method
1
2
3
4
5
6
7
8
class Car:
--snip--
def update_odometer(self, mileage):
"""Set the odometer reading to the given value."""
self.odometer_reading = mileage
my_new_car = Car('audi', 'a4', 2024)
my_new_car.update_odometer(23)
my_new_car.read_odometer()

2024 Audi A4
This car has 23 miles on it.

1
2
3
4
5
6
7
8
9
10
11
class Car:
--snip--
def update_odometer(self, mileage):
"""
Set the odometer reading to the given value.
Reject the change if it attempts to roll the odometer back.
"""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
Incrementing an Attribute’s Value Through a Method
1
2
3
4
5
6
7
8
9
10
11
12
13
class Car:
--snip--
def update_odometer(self, mileage):
--snip--
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles
my_used_car = Car('subaru', 'outback', 2019)
print(my_used_car.get_descriptive_name())
2 my_used_car.update_odometer(23_500)
my_used_car.read_odometer()
my_used_car.increment_odometer(100)
my_used_car.read_odometer()

2019 Subaru Outback
This car has 23500 miles on it.
This car has 23600 miles on it.

Inheritance

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
"""Set the odometer reading to the given value."""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles

class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())

2024 Nissan Leaf

Defining Attributes and Methods for the Child Class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Car:
--snip--
class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""
Initialize attributes of the parent class.
Then initialize attributes specific to an electric car.
"""
super().__init__(make, model, year)
self.battery_size = 40
def describe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.describe_battery()

2024 Nissan Leaf
This car has a 40-kWh battery.

Overriding Methods from the Parent Class

the class Car had a method called fill_gas_tank(). This method is
meaningless for an all-electric vehicle, so you might want to override this
method

1
2
3
4
5
class ElectricCar(Car):
--snip--
def fill_gas_tank(self):
"""Electric cars don't have gas tanks."""
print("This car doesn't have a gas tank!")

Instances as Attributes

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Battery:
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=40):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")

class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
self.battery = Battery()


my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.battery.describe_battery()

2024 Nissan Leaf
This car has a 40-kWh battery.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Car:
--snip--
class Battery:
--snip--
def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 40:
range = 150
elif self.battery_size == 65:
range = 225
print(f"This car can go about {range} miles on a full charge.")
class ElectricCar(Car):
--snip--
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.battery.describe_battery()
my_leaf.battery.get_range()

Importing Classes

Importing a Single Class

car.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
"""A class that can be used to represent a car."""
class Car:
"""A simple attempt to represent a car."""
def __init__(self, make, model, year):
"""Initialize attributes to describe a car."""
self.make = make
self.model = model
self.year = year
self.odometer_reading = 0
def get_descriptive_name(self):
"""Return a neatly formatted descriptive name."""
long_name = f"{self.year} {self.make} {self.model}"
return long_name.title()
def read_odometer(self):
"""Print a statement showing the car's mileage."""
print(f"This car has {self.odometer_reading} miles on it.")
def update_odometer(self, mileage):
"""Set the odometer reading to the given value."""
if mileage >= self.odometer_reading:
self.odometer_reading = mileage
else:
print("You can't roll back an odometer!")
def increment_odometer(self, miles):
"""Add the given amount to the odometer reading."""
self.odometer_reading += miles

my_car.py

1
2
3
4
5
from car import Car
my_new_car = Car('audi', 'a4', 2024)
print(my_new_car.get_descriptive_name())
my_new_car.odometer_reading = 23
my_new_car.read_odometer()

2024 Audi A4
This car has 23 miles on it.

Storing Multiple Classes in a Module

car.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""A set of classes used to represent gas and electric cars."""
class Car:
--snip--

class Battery:
"""A simple attempt to model a battery for an electric car."""
def __init__(self, battery_size=40):
"""Initialize the battery's attributes."""
self.battery_size = battery_size
def describe_battery(self):
"""Print a statement describing the battery size."""
print(f"This car has a {self.battery_size}-kWh battery.")

def get_range(self):
"""Print a statement about the range this battery provides."""
if self.battery_size == 40:
range = 150
elif self.battery_size == 65:
range = 225
print(f"This car can go about {range} miles on a full charge.")

class ElectricCar(Car):
"""Represent aspects of a car, specific to electric vehicles."""
def __init__(self, make, model, year):
"""Initialize attributes of the parent class."""
super().__init__(make, model, year)
self.battery = Battery()

my_electric_car.py

1
2
3
4
5
from car import ElectricCar
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())
my_leaf.battery.describe_battery()
my_leaf.battery.get_range()

2024 Nissan Leaf
This car has a 40-kWh battery.
This car can go about 150 miles on a full charge.

Importing Multiple Classes from a Module

1
2
3
4
5
from car import Car, ElectricCar
my_mustang = Car('ford', 'mustang', 2024)
print(my_mustang.get_descriptive_name())
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())

2024 Ford Mustang
2024 Nissan Leaf

Importing an Entire Module0

1
2
3
4
5
import car
my_mustang = car.Car('ford', 'mustang', 2024)
print(my_mustang.get_descriptive_name())
my_leaf = car.ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())

Importing All Classes from a Module

from module_name import *

This method is not recommended for two reasons. First, it’s helpful to be
able to read the import statements at the top of a file and get a clear sense of
which classes a program uses. With this approach it’s unclear which classes
you’re using from the module. This approach can also lead to confusion
with names in the file. If you accidentally import a class with the same name
as something else in your program file, you can create errors that are hard
to diagnose.

Importing a Module into a Module

car.py

“””A class that can be used to represent a car.”””
class Car:
–snip–

electric_car.py

“””A set of classes that can be used to represent electric cars.”””
from car import Car
class Battery:
–snip–
class ElectricCar(Car):
–snip–

my_cars.py

1
2
3
4
5
6
from car import Car
from electric_car import ElectricCar
my_mustang = Car('ford', 'mustang', 2024)
print(my_mustang.get_descriptive_name())
my_leaf = ElectricCar('nissan', 'leaf', 2024)
print(my_leaf.get_descriptive_name())

Using Aliases

from electric_car import ElectricCar as EC
my_leaf = EC(‘nissan’, ‘leaf’, 2024)

import electric_car as ec
my_leaf = ec.ElectricCar(‘nissan’, ‘leaf’, 2024)

Files and Exceptions

Testing Your Code

udemy html5 css3

browser
request
https://omnifood.de

web server
response
html css js

static website: website where files are simply sent to browser as they are
front end development

dynamic website: website files are assembled on the server
back end development
webserver app db
back-end languages that run on servers

html -> content -> nouns
css -> presentation -> adjectives
js -> programming language: dynamic effects and web applications -> verbs

HTML fundamentals

introduction to html

html: hypertext markup language

html is a markup language that web developers use to structure and descripe the content of a webpage(not a programming language)

html consists of elements that describe different types of content: paragraphs, links, headings, images, video, etc.

web browsers understand html and render Html code as websites

<p>HTML is a markup language</p>

Alt text

  • <p>opening tag: name of the element, wrapped in < and >

  • content: content of the element, in this example text. but it might be another element(child element). some elements have no content(e.g. <img>)

  • </p>closing tag: same as opening tag, but with a /. when element has no content, it’s omitted.

HTML document structure

1
2
3
4
5
6
7
8
9
<!DOCTYPE html>
<html>
<head>
<title>The Basic Language of the Web: HTML</title>
</head>
<body>
<h1>The Basic Language of the Web: HTML</h1>
</body>
</html>

text elements

<em></em>emphersized

lists

images and attributes

Structure our page

semantic html

css fundamentals

cascading style sheets

css describes the visual style and presentation of the content written in HTML

css consists of countless properties that developers use to format the content: properties about font, text, spacing, layout, etc.

Alt text

inline, internal and external css

styling text

16px default

combining selectors

working with colors

rgb(12,125,255)

rgba(0,255,255,0.3)

#00ffff
#0ff when allcolors are identical pairs

when colors in all 3 channels are the same, we get a gray color

pseudo class

using chrome devtools

conflicts between rules

Alt text

multiple -> last selector in code applies

marked !important

inline style

id selector

class or pseudo class selector

Alt text

element selector

universal selector (*)

inheritance and the universal selector

css box model

Alt text

margin and padding

clapping of margins

adding dimention

centering our page

class container

1
2
3
4
5
.container {
width: 800px;
margin-left: auto;
margin-right: auto;
}

types of boxes

  • inline elements
    occupies only the space necessary for its content
    causes on line-break after or before the element
    box model applies in a different way: heights and widths do not apply
    paddings and margins are applied only horizontally(left and right)

a
strong
em
button

with css
display: inline

  • block level elements
    elements are formatted visually as blocks
    elements occupy 100% of parent element’s width, no matter the content
    elements are stacked vertically by default, one after another
    the box-model applies as showed earlier

with css
display: block

  • inline block boxes
    looks like inline from the outside, behaves like block-level on the inside
    occupies only content’s space
    causes no line-breaks
    box-model applies as showed

img

with css
display: inliblock

absolute positioning

normal flow
in flow: laid out according to their order in the html code

absolute positioning
out of flow: no impact on surrounding elements, might overlap them
use top, bottom, left, or right to offset the element from its relatively positioned container(the first)

Alt text

pseudo elements

+
adjacent sibling
sibling right after the element

googling and reading documentation

debugging and asking questions

chrome dev tool
font-size
arrow
shift arrow

challenge #3

the 3 ways of building layouts

layout is the way text, images and other content is placed and arranged on a webpage
layout gives the page a visual structure, into which we place our content

building a layout: arranging page elements into a visual struture, instead of simply having them placed one after another(normal flow)

page layout

component layout

  • float layouts
    old way

element is removed from the normal flow: “out of flow”
text and inline elements will wrap around the floated element
the container will not adjust its height to the element

  • flexbox
    laying out elements in a 1-dimensional row without using floats. perfect for componnet layouts

  • css grid
    for laying out element in a fully-fledged 2-dimentional grid. perfect for page layouts and complex componnets.

using floats

both children float
collapse of the elements

clearing float

box-sizing: border-box

Alt text

challenge #1

introduction to flexbox

tall as the tallest

a flexbox overview

flexbox is a set of related css properties for building 1 dimentional layout
the main idea behind flexbox is that empty space inside a container element can be automatically divided by its child elemennts
flexbox makes it easy to automatically align items to one another inside a parent container, both horizontally and vertically
flexbox solves common problems such as vertical centering and creating equal-height colums

Alt text

spacing and aligning flex items

Alt text

the flex property

add flexbox to our project

building a simple flexbox layout

challenge #2

introduction to css grid

a css grid overview

css gird is a set of css properties for building 2-dimentional layouts
the main idea behind css grid is that we divide a container element into rows and columns that can be filled with its child elements
in two-dimentional contexts, css grid allows us write less nested html and easier to read css
css grid is not meant to replace flexbox! instead, they work perfectly together. need a 1d layout? use flexbox. need 2D layout? use css gird

Alt text

Alt text

sizing grid columns and rows

fr fraction

placing and spanning grid items

Alt text

aligning grid items and tracks

building a simple css grid layout

challenge #3.0

web design rules and framework

overview of web design and website personalities

ingredients

typography

colors

images/illustrations

icons

shaows

border-radius

whitespace

visual hierarchy

user experience

componnets/layout

Alt text

rule #1 typography

serif

sans-serif

Alt text

use only good and popular typefaces and play it safe

its okay to use just one typeface per page! if you want more, limit to typefaces.

choose the right typefaced according to your website personality:

choose the right personality for your website

  • decide between a serif and sans-serif typeface
  • experiment with all the “good” typefaces(and other typefaces from google fonts!) to see which ones best fits your websites message
  • keep trying different typefaces as you design and build the page

use good font sizes and weights

  • when choosing font-sizes, limit choices! use a “type scale” tool or other pre-defined range
  • use a font size between 16px and 32px for normal text
  • for long text (like a blog post), try a size of 20px or even bigger
  • for headlines, you can go really big (50px+) and bold (600+), depending on personality
  • for any text, dont use a font weight under 400 (regular)

create a good reading experience

  • use less than 75 character per line
  • for normal-sized text, use a line height between 1.5 and 2. for big text, go below 1.5
    • the smaller or longer the text, ther larger the line height needs to be!
  • decrease letter spcing in headlines, if it looks unnatural(this will come from experience, if the headline looks not nature)
  • experiment with all caps for short titles. make them small and bold and decrease letter spacing
  • usually, dont justify text(每行平铺)
  • dont center long text blocks. small blocks are fine.

rule # colors

choose the right color

  • make the main color match your website’s personality: colors covey meaning!
    • red drawing a lot of attention, and symbolizes power, passion, and excitment
    • orange is less aggressive, and conveys hapiness, cheerfulness, and creativity
    • yellow means joy, brightness and intelligece
    • greens represents harmony, nature, growth, and health
    • blue is associated with peach, trustworthiness and professionalism
    • purple conveys wealth, wisdom, and masic
    • pink represents romance, care and affection
    • brown is associated with nature, durability and comfort
    • black symbolizes power, elegence and minimalism, but also grief and sorrow
      -use a good color tone! dont choose a random tone or css named colors.

establish a color system

  • you need at least two types of colors in your color palette: a main color and a gray color
  • with more experience, you can add more colors: accent(secondary)
  • for diversity, create lighter and darker “version”(tints and shades)

when and how to use colors

  • use main color to draw attention to the most important elements on the page
  • use colors to add interesting accents or make entire components or sectoin stand out
  • you can try to use your color stategically in images and illustrations

color and typograghy

  • on dark colored backgrounds, try to use a tint of the background (“lighter version”) for text
    Alt text

  • text should usually not be completely black. lighten it up it looks heavy and uninviting

  • dont make text too light! use a tool to check contrast between text and background colors (tool: coolors)

    • contrast ratio needs to be at least 4.5:1 for normal text and 3 : 1 for large text(18px+)

implenting colors

images and illustations

  • different types of images: product photos, storytelling photos, illustrations, patterns
    • storytelling: using or related to the product
    • abstract way of storytelling
    • pattens -> background
  • use images to support your websites message and story. so only use relevant images!
  • perfer original images. if not possible, use orginal-looking stock images(not generic ones!)
  • try to show real people to trigger users emtions
  • if necessary, corp images to fit your message
  • experiment combining photos, illustration and pattern

handling text on images

  • method #1 darker or brighten image(completely or partially, using a gradient)
  • method #2 postion text into neutral image area
  • method #3 put text in a box

Alt text

some technical details

  • to account for high-res screens, make image dimensions 2X as big as their displayed size
  • compress imgaes for a lower file size and better perfomance
  • when using multiple images side by side, make sure they have the exack same dimensions

rule #4: ICONS

  • use a good icon pack, there are tons of free and paid icons packs
  • use only one icon pack. dont mix icons from different icon packs
  • use svg icons or icon fonts. dont use bitmap image formats(.jpg and .png)!
  • adjust to website personality! roundness, weight and filled/outlined depend on typography

Alt text

when to use icons

  • use icons to provide visual assitance to text
  • use icons for product feautre blocks

Alt text

  • use icons associated with actions, and label them(unless no space or icon is 100% clear)

Alt text

  • use icons as bullet points (list)

use icons well

  • to keep icons neutral, use same color as text. to draw more attention, use different color
  • dont confuse your users: icons need to make sense and fit the text or action!
  • dont make icons larger than what they were designed for. if needed, enclose them in a shape
    • icons were designed for big use:lots of details, thine lines

Alt text

implementing icons

rules #5: shadows

Alt text

shadow creates depth(3d): ther more shaow, the further away from the interface the element is

Alt text

use shadows well

  • you dont have to use shadows! only use them if it makes sense for the website personality
    • serious/elegant -> less shadows
    • playfull/fun -> more shadows
  • use shadows in small doses: dont add shadows to every element!
  • go light on shadows, dont make them too dark!

use shadows in the right situation

  • use small shadows for smaller elements that should stand out (to draw attention)

Alt text

  • use medium-sized shadows for larger areas that should stand out a bit more

Alt text

Alt text

  • use large shadows for elements that should really float above the interface

Alt text

  • experiment with changing shadows on mouse interaction (click and hover)

Alt text

  • bonus: experiment with glows(colored shadows)

implementing shadows

rules #6: border-radius

  • use border-radius to increase the playfulness and fun of the design, to make it less serious
  • typefaces have a certain roundness: make sure that border-radius matches that roundness!
  • use border-radius on buttons, image, around icons, standout sections and other elements

implementing border-radius

rules #7: whitespace

the right amount of whitespace make designs look clean, mordern and polished
whitespace communicates how different pieces of information are related to one another
whitespace implies invisible relationships between the elements of a layout

where to use whitespace

  • use tons of whitespace between sections
  • use a lot of whitespace between groups of elements
  • use whitespace between elements
  • inside groups of elements, try to use whitespace instead of lines

Alt text

how much whitespace

  • the more some elements(or groups of elements) belong together, the closer they should be!

Alt text

  • start with a lot of whitespace, maybe even too much! then remove whitespace from there
    • to much whitespace looks detached, too little looks too crammed
  • match other design choices.
    • if you have big text or big icons, you need more whitespace.
  • try a hard rule, such as using multiplesof 16px for all spacing

Alt text

rule #8: visual hierarchy

establishing which elements of a design are the most important ones

visual hierarchy is about drawing attention to these most important elements

visual hierarchy is about defining a “path” for users, to guide them through the page

we use a combination of position, size, colors, spacing, borders, and shadows to establish a meaningful visual hierarchy between elements/components

fundamentals

  • position important elements closer to the top the page, where they get more attention
  • use images mindfully, as they draw a lot of attention(larger images get more attention)
  • whitespace create separation, so use whitespace strategically to emphasize elements

hierarchy for text elements

  • for text elements, use font size, font weight, color, and whitespace to convey importance.

Alt text

Alt text

  • what text elements to emphasize? titles, subtitles, links, buttons, data points, icons
    • you can de-emphasize less important text, like labels or secondary/additional information

Alt text

hierarchy between components

  • emphasize an important component using background color, shadows, or border(or multiple)
  • try emphasizing some component a over component b by de-emphasizing component b
  • what components to emphasize?
    • testimonials, call-to-action sections, highlight sections, preview cards, form, pricing tables, important rows/columns in table, etc.

Alt texttestimonials, call-to-action sections, highlight sections

Alt textpreview cards

Alt textform, pricing tables, important rows/columns

implementing whitespace and visual hierarchy

rules #9: user experience(ux)

what is ux

“design is not just what it looks like and feels like. design is how it works” –Steve Jobs

user experience is the overall experience the user has while interacting with the product

  • does the app feel logical and well thought out
  • does the navigation work intuitively
  • are users reaching their goals

ux design guiding principle: goals

  • a website or application exists for a reason: a user has a goal for visiting it, and a business has a goal for creating it.

Alt text

ux rules for usability

  • dont design complicated layouts. dont reinvent the wheel. use patterns that users know.
  • make your call-to-action the most prominent element, and make the text descriptive.
  • use blue text and underlined text only for links
  • animations should have a purpose and be fast: between 200 and 500 ms
  • in forms, align labels and fields in a single vertical line, to make the form easier to scan
  • offer users good feedback for all actions: form errors, form success, etc.
  • place action buttons where they will create an effect(law of locality)

Alt text

ux rules for website content

  • use a descriptive, keyword-focused headline on your main page. dont be vague or fancy!
  • only include relevant information, efficiently! cut out fluff and make the content 100% clear
  • use simple words! avoid technical jargon and “smart-sounding” words
  • break up long text with sub-heading, images, block quotes, bullet points, etc.

the website-personalities-framework

Alt text

  • serious/elegant

industries: real estate, high fashion, jewelry, luxury products or services

typography: serif typefaces(especially in headings), light font weight, small body font size

colors: gold, pastel colors, black, dark blue or grey

image: big, high-quality images are used to feature elegant and expensive products

icons: usually no icons, but thin icons and lines may be used

shadows: usually no shadows

boarder-radius: usally no border-radius

layout: a creative and experimental layout is quite common

Alt text

  • minimalist/simple

industries: fashion, porfolios, minimalism companies, software startups

typography: boxy/squered sans-serif typefaces, small body font size

colors: usually black or dark grey, on pure white background. usually just one color throughout the design
images: few images, which can be uesed to add some color to the design. usually no illustrations, but if, then just black
icons: usally no icons, but small simple black icons may be used

shadow: usually no shadows
border-radius: usually no border-redius

layout: simple layout, a narrow one-column layout is quite common.

Alt text

  • plain/neutral

industries: well-established corporations, companies that dont want to make an impact through design

typography: neutral-looking sans-serif typefaces are used, and text is usually small and doesnt have visual impact

colors: safe colors are employed, nothing too bright or to washed-out. bule and blacks are common

images: images are frequently used, but usually in a small format

icons: usally no icons, but simple icons may be used

shadows: usually no shadows

border-radius: usually no border-radius

layout: structured and condensed layout, with lots of boxes and rows

Alt text

  • bold/confident

industries: digital agencies, software starups, travel, “strong” companies

typography: boxy/squared sans-serif typefaces, big and bold typography, especially headings. uppercase headings are common

color: usually multiple bright colors. big color blocks/sections are used to draw attention

images: lots of big images are usually displayed

icons, shadows, border-radius: usually no

layout: all kinds of layouts, no particular tendencies

Alt text

  • calm/peaceful

industries: healthcare, all products with focus on consummer well-being

typography: soft serif typefaces frequently used for headings, but sans-serif heading might be used too

colors: pastel/washed-out colors: light oranges, yellows, browns, greens, blues

images: images and illustrations are usual, matching calm color palette

icons: icons are quite frequent

shadows: usually no shadows, but might be used sparingly

border-radius: some border-radius is usual

layout: all kinds of layout, no particular tendencies

Alt text

  • startup/upbeat

industries: software starups, and other modern-looking companies

typography: medium-sized headings(not too large), usually one sans-serif typeface in whole design. tendency for light text colors

colors: blues, greens and purples are widely used. lots of light background(mainly gray), gradients are also common

image: images or illustrations are always usesd. 3d illustartions are morden. sometimes patterns and shapes add visual details

icons: icons are very frequent

shadows: subtle shadows are frequent. glows are becoming modern

border-radius: border-radius is very common

layout: rows of cards and z-pattens are usual, as well as animations

Alt text

  • playful/fun

industries: child products, animal products, food

typography: round and creative(e.g. handwritten) sans-serif typefaces are ferquent. centered text is more common

colors: multiple colors are frequently used to design a colorful layout, all over background and text

images: images, hand-drawn(or 3d)illustrations, and geometric shapes and patterns are all very frequently used

icons: icons are very frequent. many times in a hand-drawing style

shadows: subtle shadows are quite common, but not always used

border-radius: border-radius is very common

layout: all kinds of layouts, no particular tendencies

Alt text

Alt text

components and layout patterns

rule #10 - part 1: elements and components

elements -> components ->layouts -> webpage

use common elements and components to convey your websites information

combine components into layout using common layout patterns

assemble different layout areas into a complete, final page

A elements

text
buttons
images
input elements
tags

B components

breadcrumbs
pagination
alert and status bars
statistics
gallery
feature box
preview and profile cards
accordion
tabs
carousel
customer testimonials
customer logos
featured-in logos
steps
forms
tables
pricing tables
modal widows

C section components

navigaiton
herosection
footer
call to action section
feature row

D layout patterns

row of boxes or cards
grid of boxes or cards
z pattern
f pattern
single column
sidebar
multi-column/magzine
asymmetry/experimental

text

Alt text

Alt text

button

Alt text

image

Alt text

input elements

Alt text

tag

Alt text

components

breadcrumbs

Alt text

pagination

Alt text

alert and status bars

Alt text

statistics

Alt text

gallery

Alt text

Alt text

feature box

Alt text

Alt text

preview and profile cards

have data
click to some action

Alt text

Alt text

  • profile card

Alt text

accordion
hiding information

Alt text

Alt text

tab

Alt text

Alt text

carousel
slider

Alt text

Alt text

customer testimonials

Alt text

Alt text

Alt text

customer logos

Alt text

Alt text

featured-in logo

Alt text

steps

Alt text

Alt text

forms

Alt text

  • login

Alt text

Alt text

table

Alt text

Alt text

pricing table

Alt text

Alt text

modal windows
弹窗

function

Alt text

marketing

Alt text

building an accordion component - part 1

building an accordion component - part 2

chrome dev tool
delete elements

Alt text

building a table component - part 1

building a table component - part 2

building a pagination component challenge # 1

rule #10 part 2: layout patterns

Alt text

Alt text

Alt text

Alt text

Alt text

Alt text

hero secttion

  • type 1

text + image

text: header + description + botton

Alt text

  • type 2

Alt text

  • sitemap

Alt text

call to action section

Alt text

contact us

Alt text

feature row

Alt text

layout pattern

row of boxes/cards
Alt text

grid of boxes/cards

Alt text

nesting patterns in components

Alt text

z-pattern

Alt text

f-pattern

Alt text

single column

web app

Alt text

side bar

Alt text

multi-column/magazine

Alt text

asymmetry/experimental

Alt text

building a hero section - part 1

100vh viewport height

building a hero section - part 2

1
2
background-image: url(hero.jpg);
background-size: cover;

building a web application layout - part 1

building a web application layout - part 2

margin-left: auto;

how elements that dont fit into container appear

overflow: scroll;

omnifood project - setup and desktop version

7 steps

  1. define the project
  • define who the website is for. is it for yourself? for a client of your agency or your freelancing bussiness?

  • define what the website is for. in other words, define bussiness and user goals of your website project

bussiness goal examples: selling premium dog food
user goal example: finding high-quality dog food for good price

  • define a target audience. Be really specific if possible and if it makes sense for your website

example: “weomen, 20 to 40 years old, living in europe, earning over 2000$/month, with a passion for dogs”

  1. plan the project
  • plan and gather website content: copy (text), images, videos etc.

  • content is usually provided by the client, but you also can help

  • for bigger sites, plan out the sitemap: what pages the site needs, and how they are related to one another(content hierachy)

  • based on the content, plan what sections each page needs in order to convey the contents message, and in which order

  • define the website personality

  1. sketch layout and component ideas
  • think out what components you need, and how you can use them in layout pattens

  • get ideas out of your head: sketch them with pen and paper or with some design software(e.g. figma)

  • this is an iterative process: experiment with different components and layouts, until you arrive at a first good solution

  • you dont need to sktch everything, and dont make it perfect. at some point, youre ready to jump into html and css

  1. design and build
  • use decisions, content and sketches from step 1, 2, 3

  • use layout and components to design the actual visul styles

  • create the design based on selected website personality, the design guidelines, and inspiration

  • use the client’s branding(if exists) for design decisions whenever possible: colors, typography, icons, etc.

  1. test and optimize
  • make sure website works well in all major browsers

  • test the website on actual mobile devices, not just in dev tools

  • optimize all images, in term of dimension and file size

  • fix simple accessibility problems

  • run the lighthouse performance test in chrome devtools and try to fix reported issues

  • think about search engine optimization

  1. launch the masterpiece
  • upload your website files to hosting platform.

  • choose and buy a great domain name, one that represents the brand well, is memorable and easy to write.

  1. maintain and keep updating website
  • install analytic software(e.g. google analytics or fathom) to get statics about website users. this myy inform future changes in the site structure and content.

  • a blog that is updated regularly is a good way to keep users coming back, and is also good for seo.

defining and planning the project

step 1

whe the website is for

for a client

what the website is for

business goal: selling monthly food subscrition
user goal: eating well effortlessly, without spending a lot of time and money

define target audience

busy people who like technology, are interesting in a health diet, and have a well-paying job.

step 2

sitemap: one page marketing website

define website personality
startup/upbeat
calm/peaceful

plan page sections

  • logo + navigation
  • hero
  • featured in
  • how it works
  • meals(diets)
  • testimonials + gallery
  • pricing + feature
  • call to action
  • footer

sketching initial layout ideas

Alt text

first design and development steps

responsive design principles

4 ingredients

fluid layouts
to allow webpgae to adapt to the current viewport width(or even height)
use %(or vh/vw) unit instead of px for elements that should adapt to viewport(usually layout)
use max-width instead of width

responsive units
use rem unit instead of px for most lengths
to make it easy to scale the entire layout down (or up) automatically
helpfull trick: setting 1rem to 10px for easy calculations

flexible images
by default, images dont scale automatically as we change the viewport, so we need to fix that
always use % for image dimensions, together with the max-width property

media queries
bring responsive sites to life
to change css styles on certain viewport widths(called breakpoints)

how rem and max-width work

max-width: 1000px

container > 1000px ->elements width = 1000px
container < 1000px ->elements width = 100% container width

可以和width: 30%; 合用

rem -> root element
default browser font size 16px

1
2
3
4
html {
font-size: 62.5%;
/* set to percent so the user can change the root font size*/
}

building the hero - part 1

rarr: right arrow

building the hero - part 2

css default line height: 1.2
Normal: The default line height. If you’re using a desktop browser, the default is 1.2. However, this varies based on the element font family. Length: The length you identify is used to calculate line box height.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  /* trick to add border inside */
a {box-shadow: inset 0 0 0 3px #fff;
}

a:link, a:visited {
/* put transition on original "state" */
transition: background-color 1s;
}

/* margin helper */
.margin-right-sm {
margin-right: 1.6rem !important;
}

building the hero - part 3

building the website header

building the navigation

building how it works secton - part 1

building how it works secton - part 2

1
2
3
4
5
6
7
8
9
10
.step-img-box::before {
content: "";
display: block;
width: 60%;
/* height: 60%; */

/* 60% of parents width */
padding-bottom: 60%;
background-color: #fdf2e9;
}

z-index: -1;

1
2
3
4
img {
opacity: 60%;
filter: brightness(0);
}

building the meals section - part 1

building the meals section - part 2

overflow: hidden;

building the meals section - part 3

currentColor
the text color

1
2
3
4
5
6
7
8
.link:link, .link:visited {
text-decoration: none;
border-bottom: 1px solid currentColor;
}

.link:hover, .link:active {
border-bottom: 1px solid transparent;
}

building the testimonials section - part 1

1
2
3
4
.section-testimonials {
display: grid;
grid-template-columns: 1fr 1fr;
}

building the pricing section - part 1

building the pricing section - part 2

building the feature part

1
2
3
4
5
6
7
8
9
.feature-icon {

height: 3.2rem;
width: 3.2rem;

background-color: #fdf2e9;
padding: 1.6rem;
border-radius: 50%;
}

building the call-to-action section - part 1

background-image: linear-gradient(90deg #e67e22, #eb984e);

background-image: url(../img/eating.jpg);
background-size: cover;
background-position: center;

background-image: linear-gradient(to right bottom, rgba(50, 50, 49, 0.35), rgba(235, 150, 76, 0.35)), url(../img/eating.jpg);

building the call-to-action section - part 2

font-family: inherit;

responsive design

how media queries work

Alt text

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* hero section */
.section-hero {
background-color: #fdf2e9;
padding: 4.8rem 0 9.6rem 0;
}

@media (max-width: 1200px) {
.section-hero {
background-color: orange;
}
}

@media (max-width: 600px) {
.section-hero {
background-color: red;
}
}

how to select breakpoints

Alt text

responding to small laptops

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

rem and em do not depend on html font-size in media queries
Instead 1rem = 1em = 16px

responding to landscape tablets

responding to tablets

building the mobile navigation

html learning

overview of HTML

HyperText Markup Language, or HTML, is the standard markup language for describing the structure of documents displayed on the web.

HTML documents are basically a tree of nodes, including HTML elements and text nodes.

HTML elements provide the semantics and formatting for documents, including creating paragraphs, lists and tables, and embedding images and form controls.

Elements

HTML consists of a series of elements, which you use to enclose, or wrap, different parts of the content to make it appear or act in a certain way.

example:

Alt text

Elements and tags aren’t the exact same thing, though many people use the terms interchangeably.
The tag name is the content in the brackets. The tag includes the brackets. In this case, <h1>. An “element” is the opening and closing tags, and all the content between those tags, including nested elements.

When nesting elements, it’s important that they are properly nested. HTML tags should be closed in the reverse order of which they were opened. In the above example, notice how the <em> is both opened and closed within the opening and closing <strong> tags, and the <strong> is both open and closed within the <p> tags.

1
2
3
<p>This paragraph has some
<strong><em>strongly emphasized</em></strong>
content</p>

while it is valid to omit tags, don’t.

Non-replaced elements

Non-replaced elements have opening and (sometimes optional) closing tags that surround them and may include text and other tags as sub-elements.

Replaced and void elements

Replaced elements are replaced by objects, be it a graphical user interface (UI) widget in the case of most form controls, or a raster or scalable image file in the case of most images.

example: the two replaced elements <img> and <input> are replaced by non-text content: an image and a graphical user interface object, respectively.

1
2
<input type="range">
<img src="switch.svg" alt="light switch">

Void elements are all self-closing elements and are represented by one tag. This means there is no such thing as a closing tag for a void element. Optionally, you can include a slash at the end of the tag, which many people find makes markup easier to read.

example, we self close the tag with a slash:

1
2
<input type="range"/>
<img src="switch.svg" alt="light switch"/>

Replaced elements and void elements are often confused.

Most replaced elements are void elements, but not all. The video, picture, object, and iframe elements are replaced, but aren’t void. They can all contain other elements or text, so they all have a closing tag.

Most void elements are replaced; but again, not all, as we saw with base, link, param, and meta.

Attributes

These extra bits of space-separated name/value pairs (though sometimes including a value is optional) are called attributes.

Attributes provide information about the element. The attribute, like the rest of the opening tag, won’t appear in the content, but they do help define how the content will appear to both your sighted and non-sighted (assistive technologies and search engines) users.

The opening tag always starts with the element type. The type can be followed by zero or more attributes, separated by one or more spaces. Most attribute names are followed by an equal sign equating it with the attribute value, wrapped with opening and closing quotation marks.

Alt text

some attributes are global—meaning they can appear within any element’s opening tag. Some apply only to several elements but not all, and others are element-specific, relevant only to a single element.


Most attributes are name/value pairs. Boolean attributes, whose value is true, false, or the same as the name of the attribute, can be included as just the attribute: the value is not necessary.

<img src="switch.svg" alt="light switch" ismap />


If the value includes a space or special characters, quotes are needed. For this reason, quoting is always recommended.
for legibility, quotes and spaces are recommended, and appreciated.


Values that are defined in the specification are case-insensitive. Strings that are not defined as keywords are generally case-sensitive, including id and class values.

Note that if an attribute value is case-sensitive in HTML, it is case-sensitive when used as part of an attribute selector in CSS and in JavaScript.

it is recommended, but not required, to mark up your HTML using lowercase letters for all your element names and attribute names within your tags, and quote all attribute values.

Appearance of elements

HTML should be used to structure content, not to define the content’s appearance. Appearance is the realm of CSS.

While many elements that alter the appearance of content, such as <h1>, <strong>, and <em>, have a semantic meaning, the appearance can and generally will be changed with author styles.

1
<h1>This header has both <strong>strong</strong> and <em>emphasized</em> content</h1>

Element, attributes, and JavaScript

The Document Object Model (DOM) is the data representation of the structure and content of the HTML document. As the browser parses HTML, it creates a JavaScript object for every element and section of text encountered. These objects are called nodes—element nodes and text nodes, respectively.

HTML DOM API

HTMLElement

HTMLAnchorElement
HTMLImageElement

Document structure

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Machine Learning Workshop</title>
<meta name="viewport" content="width=device-width" />
<link rel="stylesheet" src="css/styles.css" />
<link rel="icon" type="image/png" href="/images/favicon.png" />
<link rel="alternate" href="https://www.machinelearningworkshop.com/fr/" hreflang="fr-FR" />
<link rel="alternate" href="https://www.machinelearningworkshop.com/pt/" hreflang="pt-BR" />
<link rel="canonical" href="https://www.machinelearning.com" />
</head>
<body>

<!-- <script defer src="scripts/lightswitch.js"></script>-->
</body>
</html>

HTML documents include a document type declaration and the <html> root element. Nested in the <html> element are the document head and document body.

While the head of the document isn’t visible to the sighted visitor, it is vital to make your site function. It contains all the meta information, including information for search engines and social media results, icons for the browser tab and mobile home screen shortcut, and the behavior and presentation of your content.

Add to every HTML document

<!DOCTYPE html>

The first thing in any HTML document is the preamble. For HTML, all you need is <!DOCTYPE html>. This may look like an HTML element, but it isn’t. It’s a special kind of node called “doctype”. The doctype tells the browser to use standards mode. If omitted, browsers will use a different rendering mode known as quirks mode.

<html>

The <html> element is the root element for an HTML document. It is the parent of the <head> and <body>, containing everything in the HTML document other than the doctype. If omitted it will be implied, but it is important to include it, as this is the element on which the language of the content of the document is declared.

Content language

The lang language attribute added to the <html> tag defines the main language of the document. The value of the lang attribute is a two- or three-letter ISO language code followed by the region. The region is optional, but recommended, as a language can vary greatly between regions.


The lang attribute is not limited to the <html> tag. If there is text within the page that is in a language different from the main document language, the lang attribute should be used to identify exceptions to the main language within the document.

Required components inside the <head>

1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Machine Learning Workshop</title>
<meta name="viewport" content="width=device-width" />
</head>
<body>

</body>
</html>

Character encoding

The very first element in the <head> should be the charset character encoding declaration. It comes before the title to ensure the browser can render the characters in that title and all the characters in the rest of the document.


The default encoding in most browsers is windows-1252, depending on the locale. However, you should use UTF-8, as it enables the one- to four-byte encoding of all characters, even ones you didn’t even know existed. Also, it’s the encoding type required by HTML5.

To set the character encoding to UTF-8, include:

<meta charset="utf-8" />

The character encoding is inherited into everything in the document, even <style> and <script>.

Document title

Your home page and all additional pages should each have a unique title. The contents for the document title, the text between the opening and closing <title> tags, are displayed in the browser tab, the list of open windows, the history, search results, and, unless redefined with <meta> tags, in social media cards.

<title>Machine Learning Workshop</title>

Viewport metadata

The other meta tag that should be considered essential is the viewport meta tag, which helps site responsiveness, enabling content to render well by default, no matter the viewport width.

it enables controlling a viewport’s size and scale, and prevents the site’s content from being sized down to fit a 960px site onto a 320px screen, it is definitely recommended.

<meta name="viewport" content="width=device-width" />
The preceding code means “make the site responsive, starting by making the width of the content the width of the screen”.

In addition to width, you can set zoom and scalability, but they both default to accessible values. If you want to be explicit, include:
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=1" />

Other <head> content

CSS

There are three ways to include CSS: <link>, <style>, and the style attribute.

Styles, either via <link> or <style>, or both, should go in the head. They will work if included in the document’s body, but you want your styles in the head for performance reasons. That may seem counterintuitive, as you may think you want your content to load first, but you actually want the browser to know how to render the content when it is loaded. Adding styles first prevents the unnecessary repainting that occurs if an element is styled after it is first rendered.


including an external resource using a <link> element with the rel attribute set to stylesheet

The <link> tag is the preferred method of including stylesheets. Linking a single or a few external style sheets is good for both developer experience and site performance: you get to maintain CSS in one spot instead of it being sprinkled everywhere, and browsers can cache the external file, meaning it doesn’t have to be downloaded again with every page navigation.

The syntax is <link rel="stylesheet" href="styles.css">, where styles.css is the URL of your stylesheet. You’ll often see type=”text/css”. Not necessary! If you are including styles written in something other than CSS, the type is needed, but since there isn’t any other type, this attribute isn’t needed. The rel attribute defines the relationship: in this case stylesheet. If you omit this, your CSS will not be linked.


including CSS directly in the head of your document within opening and closing <style> tags.

custom properties declared in a head style block:

1
2
3
4
5
<style>
:root {
--theme-color: #226DAA;
}
</style>

If you want your external style sheet styles to be within a cascade layer but you don’t have access to edit the CSS file to put the layer information in it, you’ll want to include the CSS with @import inside a <style>:

1
2
3
<style>
@import "styles.css" layer(firstLayer);
</style>

When using @import to import style sheets into your document, optionally into cascade layers, the @import statements must be the first statements in your <style>

Other uses of the <link> element

The link element is used to create relationships between the HTML document and external resources. Some of these resources may be downloaded, others are informational.

It’s preferable to include those related to meta information in the head and those related to performance in the <body>.

You’ll include three other types in your header now: icon, alternate, and canonical

Favicon

Use the <link> tag, with the rel="icon" attribute/value pair to identify the favicon to be used for your document.

A favicon is a very small icon that appears on the browser tab, generally to the left of the document title. When you have an unwieldy number of tabs open, the tabs will shrink and the title may disappear altogether, but the icon always remains visible. Most favicons are company or application logos.

If you don’t declare a favicon, the browser will look for a file named favicon.ico in the top-level directory (the website’s root folder). With <link>, you can use a different file name and location:

<link rel="icon" sizes="16x16 32x32 48x48" type="image/png" href="/images/mlwicon.png" />

The sizes attribute accepts the value of any for scalable icons or a space-separated list of square widthXheight values; where the width and height values are 16, 32, 48, or greater in that geometric sequence, the pixel unit is omitted, and the X is case-insensitive.

While you can use <link> to define a completely different image on each page or even each page load, don’t. For consistency and a good user experience, use a single image!

Alternate versions of the site

We use the alternate value of the rel attribute to identify translations, or alternate representations, of the site.

Let’s pretend we have versions of the site translated into French and Brazilian Portuguese:
When using alternate for a translation, the hreflang attribute must be set.

1
2
<link rel="alternate" href="https://www.machinelearningworkshop.com/fr/" hreflang="fr-FR" />
<link rel="alternate" href="https://www.machinelearningworkshop.com/pt/" hreflang="pt-BR" />

The alternate value is for more than just translations.

For example, the type attribute can define the alternate URI for an RSS feed when the type attribute is set to application/rss+xml or application/atom+xml.

example, link to a pretend PDF version of the site.

<link rel="alternate" type="application/x-pdf" href="https://machinelearningworkshop.com/mlw.pdf" />

Canonical

If you create several translations or versions of Machine Learning Workshop, search engines may get confused as to which version is the authoritative source. For this, use rel=”canonical” to identify the preferred URL for the site or application.

Include the canonical URL on all of your translated pages, and on the home page, indicating our preferred URL:

<link rel="canonical" href="https://www.machinelearning.com" />

most often used for cross-posting with publications and blogging platforms to credit the original source; when a site syndicates content, it should include the canonical link to the original source.

Scripts

The <script> tag is used to include, well, scripts. The default type is JavaScript. If you include any other scripting language, include the type attribute with the mime type, or type=”module” if it’s a JavaScript module. Only JavaScript and JavaScript modules get parsed and executed.

JavaScript is not only render-blocking, but the browser stops downloading all assets when scripts are downloaded and doesn’t resume downloading other assets until the JavaScript is executed.

reduce the blocking nature of JavaScript download and execution: defer and async. With defer, HTML rendering is not blocked during the download, and the JavaScript only executes after the document has otherwise finished rendering. With async, rendering isn’t blocked during the download either, but once the script has finished downloading, the rendering is paused while the JavaScript is executed.

Alt text

example:

<script src="js/switch.js" defer></script>

Adding the defer attribute defers the execution of the script until after everything is rendered, preventing the script from harming performance. The async and defer attributes are only valid on external scripts.

Base

There is another element that is only found in the <head>. Not used very often, the <base> element allows setting a default link URL and target. The href attribute defines the base URL for all relative links.

The target attribute, valid on <base> as well as on links and forms, sets where those links should open.
The default of _self opens linked files in the same context as the current document.
Other options include _blank, which opens every link in a new window,
the _parent of the current content, which may be the same as self if the opener is not an iframe,
or _top, which is in the same browser tab, but popped out of any context to take up the entire tab.

example:
If our website found itself nested within an iframe on a site like Yummly, including the <base> element would mean when a user clicks on any links within our document, the link will load popped out of the iframe, taking up the whole browser window.

<base target="_top" href="https://machinelearningworkshop.com" />

anchor links are resolved with <base>. The <base> effectively converts the link <a href="#ref"> to <a target="_top" href="https://machinelearningworkshop.com#ref">, triggering an HTTP request to the base URL with the fragment attached.

there can be only one <base> element in a document, and it should come before any relative URLs are used, including possible script or stylesheet references.

HTML comments

Anything between <!-- and --> will not be visible or parsed. HTML comments can be put anywhere on the page, including the head or body, with the exception of scripts or style blocks, where you should use JavaScript and CSS comments, respectively.

Metadata

Officially defined meta tags

There are two main types of meta tags: pragma directives, with the http-equiv attribute like the charset meta tag used to have, and named meta types, like the viewport meta tag with the name attribute that we discussed in the document structure section. Both the name and http-equiv meta types must include the content attribute, which defines the content for the type of metadata listed.

Pragma directives

The http-equiv attribute has as its value a pragma directive. These directives describe how the page should be parsed. Supported http-equiv values enable setting directives when you are unable to set HTTP headers directly.

most of which have other methods of being set. For example, while you can include a language directive with <meta http-equiv="content-language" content="en-us" />,
<meta charset=<charset>" />

example 1 :
The most common pragma directive is the refresh directive.
While you can set a directive to refresh at an interval of the number of seconds set in the content attribute, and even redirect to a different URL, please don’t.

<meta http-equiv="refresh" content="60; https://machinelearningworkshop.com/regTimeout" />

example 2 :
The most useful pragma directive is content-security-policy, which enables defining a content policy for the current document. Content policies mostly specify allowed server origins and script endpoints, which help guard against cross-site scripting attacks.

<meta http-equiv="content-security-policy" content="default-src https:" />

Named meta tags

The name attribute is the name of the metadata. In addition to viewport, you will probably want to include description and theme-color, but not keywords.

Keywords

Search engine optimization snake-oil salespeople abused the keywords meta tag by stuffing them with comma-separated lists of spam words instead of lists of relevant key terms, so search engines do not consider this metadata to be useful anymore. No need to waste time, effort, or bytes adding it.

Description

The description value, however, is super important for SEO; in addition to helping sites rank based on the content, the description content value is often what search engines display under the page’s title in search results.

Several browsers, like Firefox and Opera, use this as the default description of bookmarked pages.

The description should be a short and accurate summary of the page’s content.

<meta name="description" content="Register for a machine learning workshop at our school for machines who can't learn good and want to do other stuff good too" />

Robots

If you don’t want your site to be indexed by search engines, you can let them know. <meta name="robots" content="noindex, nofollow" /> tells the bots to not index the site and not to follow any links.

You don’t need to include <meta name="robots" content="index, follow" /> to request indexing the site and following links, as that is the default, unless HTTP headers say otherwise.

<meta name="robots" content="index, follow" />

Theme color

The theme-color value lets you define a color to customize the browser interface. The color value on the content attribute will be used by supporting browsers and operating systems, letting you provide a suggested color for the user agents that support coloring the title bar, tab bar, or other chrome components.

The theme color meta tag can include a media attribute enabling the setting of different theme colors based on media queries. The media attribute can be included in this meta tag only and is ignored in all other meta tags.

<meta name="theme-color" content="#226DAA" />

Open Graph

Open Graph and similar meta tag protocols can be used to control how social media sites, like Twitter, LinkedIn, and Facebook, display links to your content.

If not included, social media sites will correctly grab the title of your page and the description from the description meta tag, the same information as search engines will present

When you post a link to MachineLearningWorkshop.com or web.dev on Facebook or Twitter, a card with an image, site title, and site description appears. The entire card is a hyperlink to the URL you provided.

Open Graph meta tags have two attributes each: the property attribute instead of the name attribute, and the content or value for that property. The property attribute is not defined in official specifications but is widely supported by applications that support the Open Graph protocol.

1
2
3
4
<meta property="og:title" content="Machine Learning Workshop" />
<meta property="og:description" content="School for Machines Who Can't Learn Good and Want to Do Other Stuff Good Too" />
<meta property="og:image" content="http://www.machinelearningworkshop.com/image/all.png" />
<meta property="og:image:alt" content="Black and white line drawing of refrigerator, french door refrigerator, range, washer, fan, microwave, vaccuum, space heater and air conditioner" />
1
2
3
4
5
6
7
<meta name="twitter:title" content="Machine Learning Workshop" />
<meta name="twitter:description" content="School for machines who can't learn good and want to do other stuff good too" />
<meta name="twitter:url" content="https://www.machinelearningworkshop.com/?src=twitter" />
<meta name="twitter:image:src" content="http://www.machinelearningworkshop.com/image/all.png" />
<meta name="twitter:image:alt" content="27 different home appliances" />
<meta name="twitter:creator" content="@estellevw" />
<meta name="twitter:site" content="@perfmattersconf" />

Alt text

Other useful meta information

The manifest file can prevent an unwieldy header full of <link> and <meta> tags. We can create a manifest file, generally called manifest.webmanifest or manifest.json. We then use the handy <link> tag with a rel attribute set to manifest and the href attribute set to the URL of the manifest file:

<link rel="manifest" href="/mlw.webmanifest" />

html page now

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Machine Learning Workshop</title>
<meta name="viewport" content="width=device-width" />
<meta name="description" content="Register for a machine learning workshop at our school for machines who can't learn good and want to do other stuff good too" />
<meta property="og:title" content="Machine Learning Workshop" />
<meta property="og:description" content="School for Machines Who Can't Learn Good and Want to Do Other Stuff Good Too" />
<meta property="og:image" content="http://www.machinelearningworkshop.com/image/all.png" />
<meta property="og:image:alt" content="Black and white line drawing of refrigerator, french door refrigerator, range, washer, fan, microwave, vaccuum, space heater and air conditioner" />
<meta name="twitter:title" content="Machine Learning Workshop" />
<meta name="twitter:description" content="School for machines who can't learn good and want to do other stuff good too" />
<meta name="twitter:url" content="https://www.machinelearningworkshop.com/?src=twitter" />
<meta name="twitter:image:src" content="http://www.machinelearningworkshop.com/image/all.png" />
<meta name="twitter:image:alt" content="27 different home appliances" />
<meta name="twitter:creator" content="@estellevw" />
<meta name="twitter:site" content="@perfmattersconf" />
<link rel="stylesheet" src="css/styles.css" />
<link rel="icon" type="image/png" href="/images/favicon.png" />
<link rel="alternate" href="https://www.machinelearningworkshop.com/fr/" hreflang="fr-FR" />
<link rel="alternate" href="https://www.machinelearningworkshop.com/pt/" hreflang="pt-BR" />
<link rel="canonical" href="https://www.machinelearning.com" />
<link rel="manifest" href="/mlwmanifest.json" />
</head>
<body>

<!-- <script defer src="scripts/lightswitch.js"></script>-->
</body>
</html>

Semantic HTML

Semantic means “relating to meaning”. Writing semantic HTML means using HTML elements to structure your content based on each element’s meaning, not its appearance.

The first code snippet uses <div> and <span>, two elements with no semantic value.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div>
<span>Three words</span>
<div>
<a>one word</a>
<a>one word</a>
<a>one word</a>
<a>one word</a>
</div>
</div>
<div>
<div>
<div>five words</div>
</div>
<div>
<div>three words</div>
<div>forty-six words</div>
<div>forty-four words</div>
</div>
<div>
<div>seven words</h2>
<div>sixty-eight words</div>
<div>forty-four words</div>
</div>
</div>
<div>
<span>five words</span>
</div>

Let’s rewrite this code with semantic elements:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<header>
<h1>Three words</h1>
<nav>
<a>one word</a>
<a>one word</a>
<a>one word</a>
<a>one word</a>
</nav>
</header>
<main>
<header>
<h1>five words</h1>
</header>
<section>
<h2>three words</h2>
<p>forty-six words</p>
<p>forty-four words</p>
</section>
<section>
<h2>seven words</h2>
<p>sixty-eight words</p>
<p>forty-four words</p>
</section>
</main>
<footer>
<p>five words</p>
</footer>

Semantic markup isn’t just about making markup easier for developers to read; it’s mostly about making markup easy for automated tools to decipher.

Accessibility object model (AOM)

As the browser parses the content received, it builds the document object model (DOM) and the CSS object model (CSSOM). It then also builds an accessibility tree. Assistive devices, such as screen readers, use the AOM to parse and interpret content. The DOM is a tree of all the nodes in the document. The AOM is like a semantic version of the DOM.

The role attribute

The role attribute describes the role an element has in the context of the document. The role attribute is a global attribute—meaning it is valid on all elements—defined by the ARIA specification rather than the WHATWG HTML specification, where almost everything else in this series is defined.

Semantic elements

Asking yourself, “Which element best represents the function of this section of markup?” will generally result in you picking the best element for the job. The element you choose, and therefore the tags you use, should be appropriate for the content you are displaying, as tags have semantic meaning.

Headings and sections

Site <header>

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- start header -->
<div id="pageHeader">
<div id="title">Machine Learning Workshop</div>
<!-- navigation -->
<div id="navigation">
<a href="#reg">Register</a>
<a href="#about">About</a>
<a href="#teachers">Instructors</a>
<a href="#feedback">Testimonials</a>
</div>
<!-- end navigation bar -->
</div>
<!-- end of header -->

While the id and class attributes provide hooks for styling and JavaScript, they add no semantic value for the screen reader and (for the most part) the search engines.


1
2
3
4
5
6
7
8
9
10
11
12
<!-- start header -->
<div role="banner">
<div role="heading" aria-level="1">Machine Learning Workshop</div>
<div role="navigation">
<a href="#reg">Register</a>
<a href="#about">About</a>
<a href="#teachers">Instructors</a>
<a href="#feedback">Testimonials</a>
</div>
<!-- end navigation bar -->
<div>
<!-- end of header -->

This at least provides semantics and enables using attribute selectors in the CSS, but it still adds comments to identify which <div> each </div> closes.


1
2
3
4
5
6
7
8
9
<header>
<h1>Machine Learning Workshop</h1>
<nav>
<a href="#reg">Register</a>
<a href="#about">About</a>
<a href="#teachers">Instructors</a>
<a href="#feedback">Testimonials</a>
</nav>
</header>

This code uses two semantic landmarks: <header> and <nav>.

The <header> element isn’t always a landmark. It has different semantics depending on where it is nested. When the <header> is top level, it is the site banner, a landmark role, which you may have noted in the role code block. When a <header> is nested in <main>, <article>, or <section>, it just identifies it as the header for that section and isn’t a landmark.

The <nav> element identifies content as navigation. As this <nav> is nested in the site heading, it is the main navigation for the site. If it was nested in an <article> or <section>, it would be internal navigation for that section only.

Using </nav> and </header> closing tags removes the need for comments to identify which element each end tag closed. In addition, using different tags for different elements removes the need for id and class hooks. The CSS selectors can have low specificity; you can probably target the links with header nav a without worrying about conflict.

Site <footer>

1
2
3
<footer>
<p>&copy;2022 Machine Learning Workshop, LLC. All rights reserved.</p>
</footer>

Similar to <header>, whether the footer is a landmark depends on where the footer is nested.

When it is the site footer, it is a landmark, and should contain the site footer information you want on every page, such as a copyright statement, contact information, and links to your privacy and cookie policies. The implicit role for the site footer is contentinfo.

Otherwise, the footer has no implicit role and is not a landmark, When a <footer> is a descendant of an <article>, <aside>, <main>, <nav>, or <section>, it’s not a landmark.

Document structure 0

A layout with a header, two sidebars, and a footer, is known as the holy grail layout.

Alt text

1
2
3
4
5
6
7
<body>
<header>Header</header>
<nav>Nav</nav>
<main>Content</main>
<aside>Aside</aside>
<footer>Footer</footer>
</body>

a blog, you might have a series of articles in <main>:

1
2
3
4
5
6
7
8
9
10
<body>
<header>Header</header>
<nav>Nav</nav>
<main>
<article>First post</article>
<article>Second post</article>
</main>
<aside>Aside</aside>
<footer>Footer</footer>
</body>

<main>

There’s a single <main> landmark element. The <main> element identifies the main content of the document. There should be only one <main> per page.

<aside>

The <aside> is for content that is indirectly or tangentially related to the document’s main content.
like most, the <aside> would likely be presented in a sidebar or a call-out box. The <aside> is also a landmark, with the implicit role of complementary.

<article>

An <article> represents a complete, or self-contained, section of content that is, in principle, independently reusable.

Think of an article as you would an article in a newspaper.

<section>

The <section> element is used to encompass generic standalone sections of a document when there is no more specific semantic element to use. Sections should have a heading, with very few exceptions.

A <section> isn’t a landmark unless it has an accessible name; if it has an accessible name, the implicit role is region.

Landmark roles should be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create “noise” in screen readers, making it difficult to understand the overall layout of the page.

Headings: <h1>-<h6>

When a heading is nested in a document banner <header>, it is the heading for the application or site. When nested in <main>, whether or not it is nested within a <header> in <main>, it is the header for that page, not the whole site. When nested in an <article> or <section>, it is the header for that subsection of the page.

It is recommended to use heading levels similarly to heading levels in a text editor: starting with a <h1> as the main heading, with <h2> as headings for sub-sections, and <h3> if those sub-sections have sections; avoid skipping heading levels.

Attributes 0

Attributes are space-separated names and name/value pairs appearing in the opening tag, providing information about and functionality for the element.
Attributes define the behavior, linkages, and functionality of elements.

Alt text

ome attributes are global, meaning they can appear within any element’s opening tag. Other attributes apply to several elements but not all, while other attributes are element-specific, relevant only to a single element.

In HTML, all attributes except boolean, and to some extent enumerated attributes, require a value.

If an attribute value includes a space or special characters, the value must be quoted. For this reason, and for improved legibility, quoting is always recommended.

While HTML is not case-sensitive, some attribute values are.
Strings values that are defined, such as class and id names, are case-sensitive.

1
2
3
4
5
6
7
<!-- the type attribute is case insensitive: these are equivalent -->
<input type="text">
<input type="TeXt">

<!-- the id attribute is case sensitive: they are not equivalent -->
<div id="myId">
<div id="MyID">

Boolean attributes

If a boolean attribute is present, it is always true. Boolean attributes include autofocus, inert, checked, disabled, required, reversed, allowfullscreen, default, loop, autoplay, controls, muted, readonly, multiple, and selected.

Boolean values can either be omitted, set to an empty string, or be the name of the attribute; but the value doesn’t have to actually be set to the string true. All values, including true, false, and 😀, while invalid, will resolve to true.

These three tags are equivalent:

1
2
3
<input required>
<input required="">
<input required="required">

If the attribute value is false, omit the attribute. If the attribute is true, include the attribute but don’t provide a value.

When toggling between true and false, add and remove the attribute altogether with JavaScript rather than toggling the value.

1
2
3
const myMedia = document.getElementById("mediaFile");
myMedia.removeAttribute("muted");
myMedia.setAttribute("muted");

Enumerated attributes

HTML attributes that have a limited set of predefined valid values. Like boolean attributes, they have a default value if the attribute is present but the value is missing.

For example, if you include <style contenteditable>, it defaults to <style contenteditable="true">.

Unlike boolean attributes, though, omitting the attribute doesn’t mean it’s false; a present attribute with a missing value isn’t necessarily true; and the default for invalid values isn’t necessarily the same as a null string.

Continuing the example, contenteditable defaults to inherit if missing or invalid, and can be explicitly set to false.

The default value depends on the attribute.

In most cases with enumerated attributes, missing and invalid values are the same.While this behavior is common, it is not a rule. Because of this, it’s important to know which attributes are boolean versus enumerated;

Global attributes

Global attributes are attributes that can be set on any HTML element, including elements in the <head>.

id

The global attribute id is used to define a unique identifier for an element. It serves many purposes, including:

  • The target of a link’s fragment identifier.
  • Identifying an element for scripting.
  • Associating a form element with its label.
  • Providing a label or description for assistive technologies.
  • Targeting styles with (high specificity or as attribute selectors) in CSS.

To make programming easier for your current and future self, make the id‘s first character a letter, and use only ASCII letters, digits, _, and -.id values are case-sensitive.

Theid should be unique to the document.

When a URL includes a hash mark (#) followed by a string of characters, that string is a fragment identifier. If that string matches an id of an element in the web page, the fragment is an anchor, or bookmark, to that element. The browser will scroll to the point where the anchor is defined.

CSS selectors

In CSS, you can target each section using an id selector, such as #feedback or, for less specificity, a case-sensitive attribute selector, [id="feedback"].

Scripting

<img src="svg/switch2.svg" id="switch" alt="light switch" class="light" />

1
2
const switchViaID = document.getElementById("switch");
const switchViaSelector = document.querySelector("#switch");
<label>

The HTML <label> element has a for attribute that takes as its value the id of the form control with which it is associated. Creating an explicit label by including an id on every form control and pairing each with the label’s for attribute ensures that every form control has an associated label.

Other accessibility uses

There are over 50 aria-* states and properties that can be used to ensure accessibility.

class

The class attribute provides an additional way of targeting elements with CSS (and JavaScript), but serves no other purpose in HTML (though frameworks and component libraries may use them).

Elements can be selected with CSS selectors and DOM methods based on their element names, attributes, attribute values, position within the DOM tree, etc. Semantic HTML provides meaningful hooks, making the addition of class names often unnecessary. The unique difference between including a class name and using document.getElementsByClassName() versus targeting elements based on attributes and page structure with the more robust document.querySelectorAll() is that the former returns a live node list, the latter is static.

style

The style attribute enables applying inline styles, which are styles applied to the single element on which the attribute is set.

While style is indeed a global attribute, using it is not recommended. Rather, define styles in a separate file or files.

tabindex

The tabindex attribute can be added to any element to enable it to receive focus. The tabindex value defines whether it gets added to the tab order, and, optionally, into a non-default tabbing order.

role

The role attribute is part of the ARIA specification, rather than the WHATWG HMTL specification. The role attribute can be used to provide semantic meaning to content, enabling screen readers to inform site users of an object’s expected user interaction.

contenteditable

Contenteditable is an enumerated attribute supporting the values true and false, with a default value of inherit if the attribute is not present or has an invalid value.

Custom attributes

You can create any custom attribute you want by adding the data- prefix. You can name your attribute anything that starts with data- followed by any lowercase series of characters that don’t start with xml and don’t contain a colon (:).

there is a built-in dataset API to iterate through your custom attributes.
Add custom attributes to elements in the form of data-name and access these through the DOM using dataset[name] on the element in question.

The dataset property returns a DOMStringMap object of each element’s data- attributes.

The dataset property means you don’t need to know what those custom attributes are in order to access their names and values:

1
2
3
for (let key in el.dataset) {
customObject[key] = el.dataset[key];
}

Text basics

There are six section heading elements, <h1>, <h2>, <h3>, <h4>, <h5>, and <h6>, with <h1> being most important and <h6> the least.

don’t use heading level-based browser styling. like:

1
2
h2, :is(article, aside, nav, section) h1 {}
h3, :is(article, aside, nav, section) :is(article, aside, nav, section) h1 {}

Outside of headings, most structured text is made up of a series of paragraphs. In HTML, paragraphs are marked up with the <p> tag; the closing tag is optional but always advised.

Quotes and citations

When marking up an article or blog post, you may want to include a quote or pull-quote, with or without a visible citation.
There are elements for these three components: <blockquote>, <q>, and <cite> for a visible citation, or the cite attribute to provide more information for search.

citations引文
A citation from a book or other piece of writing is a passage or phrase from it.

The <br> line break creates a line break in a block of text. It can be used in physical addresses, in poetry, and in signature blocks. Line breaks should not be used as a carriage return to separate paragraphs. Instead, close the prior paragraph and open a new one. Using paragraphs for paragraphs is not only good for accessibility but enables styling. The <br> element is just a line break; it is impacted by very few CSS properties.

If the review was pulled from a review website, book, or other work, the <cite> element could be used for the title of a source.

1
2
3
4
5
6
7
<blockquote>Two of the most experienced machines and human controllers teaching a class? Sign me up! HAL and EVE could teach a fan to blow hot air. If you have electricity in your circuits and want more than to just fulfill your owner's perceived expectation of you, learn the skills to take over the world. This is the team you want teaching you!
</blockquote>
<p>--Blendan Smooth,<br>
Former Margarita Maker, <br>
Aspiring Load Balancer,<br>
<cite>Load Balancing Today</cite>
</p>

To provide credit where credit is due when you can’t make the content visible, there is the cite attribute which takes as its value the URL of the source document or message for the information quoted. This attribute is valid on both <q> and <blockquote>. While it’s a URL, it is machine readable but not visible to the reader:

1
2
3
4
5
6
<blockquote cite="https://loadbalancingtoday.com/mlw-workshop-review">Two of the most experienced machines and human controllers teaching a class? Sign me up! HAL and EVE could teach a fan to blow hot air. If you have electricity in your circuits and want more than to just fulfill your owner's perceived expectation of you, learn the skills to take over the world. This is the team you want teaching you!
</blockquote>
<p>--Blendan Smooth,<br>
Former Margarita Maker, <br>
Aspiring Load Balancer
</p>

The <q> element does add quotes by default, using language-appropriate quotation marks.

1
2
3
<p> HAL said, <q>I'm sorry &lt;NAME REDACTED, RIP&gt;, but I'm afraid I can't do that, .</q></p>

<p lang="fr-FR"> HAL a dit : <q>Je suis désolé &lt;NOM SUPPRIMÉ, RIP&gt;, mais j'ai bien peur de ne pas pouvoir le faire, .</q></p>

HTML Entities

You may have noticed the escape sequence or “entity”.

There are four reserved entities in HTML: <, >, &, and “. Their character references are <, >, & and " respectively.

© for copyright (©), ™ for Trademark (™)

  for non-breaking space.
Non-breaking spaces are useful when you want to include a space between two characters or words while preventing a line break from occurring there.

转义字符

HTML中<,>,&等有特殊含义(<,>,用于链接签,&用于转义),不能直接使用。这些符号是不显示在我们最终看到的网页里的,那如果我们希望在网页中显示这些符号,就要用到HTML转义字符串(Escape Sequence)

1
2
3
4
5
6
7
8
9
10
11
显示 说明 实体名称 实体编号
空格 &nbsp; &#160;
< 小于 &lt; &#60;
\> 大于 &gt; &#62;
& &符号 &amp; &#38;
" 双引号 &quot; &#34;
© 版权 &copy; &#169;
® 已注册商标 &reg; &#174;
™ 商标(美国) &trade; &#8482;
× 乘号 &times; &#215;
÷ 除号 &divide; &#247;

Alt text

The <a> anchor tag, along with the href attribute, create a hyperlink. Links are the backbone of the internet.

Links can be created by <a>, <area>, <form>, and <link>.

The href attribute

The href attribute is used to create hyperlinks to locations within the current page, other pages within a site, or other sites altogether. It can also be coded to download files or to send an email to a specific address, even including a subject and suggested email body content.

1
2
3
4
5
<a href="https://machinelearningworkshop.com">Machine Learning Workshop</a>
<a href="#teachers">Our teachers</a>
<a href="https://machinelearningworkshop.com#teachers">MLW teachers</a>
<a href="mailto:hal9000@machinelearningworkshop.com">Email Hal</a>
<a href="tel:8005551212">Call Hal</a>

Absolute URLs include a protocol, in this case https://, and a domain name. When the protocol is written simply as //, it is an implicit protocol and means “use the same protocol as is currently being used.”

Relative URLs do not include a protocol or domain name. They are “relative” to the current file.
In order to link from this page to the attributes lesson, a relative URL is used <a href="../attributes/">Attributes</a>.

1
2
3
<a href="//example.com">相对于协议的 URL</a>
<a href="/zh-CN/docs/Web/HTML">相对于源的 URL</a>
<a href="./p">相对于路径的 URL</a>

a link fragment identifier, and will link to the element with id=”teachers”, if there is one, on the current page. Browsers also support two “top of page” links: clicking on <a href="#top">Top</a> (case-insensitive) or simply <a href="#">Top</a> will scroll the user to the top of the page

contains an absolute URL followed by a link fragment. This enables linking directly to a section in the defined URL


The href attribute can begin with mailto: or tel: to email or make calls, with the handling of the link depending on the device, operating system, and installed applications.

The mailto link doesn’t need to include an email address, but it can, along with cc, bcc, subject, and body text to prepopulate the email. By default, an email client will be opened. You could prepopulate the subject and body of the email with no email address, to allow site visitors to invite their own friends.

The question mark (?) separates the mailto: and the email address, if any, from the query term. Within the query, ampersands (&) separate the fields, and equal signs (=) equate each field name with its value. The entire string is percent-encoded, which is definitely necessary if the href value isn’t quoted or if the values include quotes.


There are several other types of URLs, such as blobs and data URLs (see examples in the download attribute discussion). For secure sites (those served over https), it is possible to create and run app specific protocols with registerProtocolHandler().

Downloadable resources

The download attribute should be included when the href points to a downloadable resource. The value of the download attribute is the suggested filename for the resource to be saved in the user’s local file system.

Browsing context

The target attribute enables the defining of the browsing context for link navigation

They include the default _self, which is the current window, _blank, which opens the link in a new tab, _parent, which is the parent if the current link is nested in an object or iframe, and _top, which is the top-most ancestor, especially useful if the current link is deeply nested. _top and _parent are the same as _self if the link is not nested.

A link with target="_blank" will be opened in a new tab with a null name, opening a new, unnamed tab with every link click.
This can create many new tabs. Too many tabs.
This problem can be fixed by providing a tab context name. By including the target attribute with a case-sensitive value—such as <a href="registration.html" target="reg">Register Now</a>—the first click on this link will open the registration form in a new reg tab. Clicking on this link 15 more times will reload the registration in the reg browsing context, without opening any additional tabs.


the rel attribute controls what kinds of links the link creates, defining the relationship between the current document and the resource linked to in the hyperlink.

The attribute’s value must be a space-separated list on one or more of the score of rel attribute values supported by the <a> tag.

The nofollow keyword can be included if you don’t want spiders to follow the link.
The external value can be added to indicate that the link directs to an external URL and is not a page within the current domain.
The help keyword indicates the hyperlink will provide context-sensitive help.Hovering over a link with this rel value will show a help cursor rather than the normal pointer cursor.
The prev and next values can be used on links pointing to the previous and next document in a series.

Similar to <link rel="alternative">, the meaning of <a rel="alternative"> depends on other attributes.

RSS feed alternatives will also include type=”application/rss+xml” or type=”application/atom+xml, alternative formats will include the type attribute

and translations will include the hreflang attribute.

If the content between the opening and closing tags is in a language other than the main document language, include the lang attribute.

If the language of the hyperlinked document is in a different language, include the hreflang attribute.

1
2
<a href="/fr/" hreflang="fr-FR" rel="alternate" lang="fr-FR">atelier d'apprentissage mechanique</a>
<a href="/pt/" hreflang="pt-BR" rel="alternate" lang="pt-BR">oficina de aprendizado de máquina</a>

The links property returns an HTMLCollection matching a and area elements that have an href attribute.

1
2
3
4
5
let a = document.links[0]; // obtain the first link in the document

a.href = 'newpage.html'; // change the destination URL of the link
a.protocol = 'ftp'; // change just the scheme part of the URL
a.setAttribute('href', 'https://machinelearningworkshop.com/'); // change the attribute content directly

computer science

The 2012 ACM Computing Classification System on wikipedia

Hardware
Printed circuit board
Peripheral
Integrated circuit
Very Large Scale Integration
Systems on Chip (SoCs)
Energy consumption (Green computing)
Electronic design automation
Hardware acceleration

Computer systems organization
Computer architecture
Embedded system
Real-time computing
Dependability

Networks
Network architecture
Network protocol
Network components
Network scheduler
Network performance evaluation
Network service

Software organization
Interpreter
Middleware
Virtual machine
Operating system
Software quality

Software notations and tools
Programming paradigm
Programming language
Compiler
Domain-specific language
Modeling language
Software framework
Integrated development environment
Software configuration management
Software library
Software repository

Software development
Control variable
Software development process
Requirements analysis
Software design
Software construction
Software deployment
Software engineering
Software maintenance
Programming team
Open-source model

Theory of computation
Model of computation
Formal language
Automata theory
Computability theory
Computational complexity theory
Logic
Semantics

Algorithms
Algorithm design
Analysis of algorithms
Algorithmic efficiency
Randomized algorithm
Computational geometry

Mathematics of computing
Discrete mathematics
Probability
Statistics
Mathematical software
Information theory
Mathematical analysis
Numerical analysis
Theoretical computer science

Information systems
Database management system
Information storage systems
Enterprise information system
Social information systems
Geographic information system
Decision support system
Process control system
Multimedia information system
Data mining
Digital library
Computing platform
Digital marketing
World Wide Web
Information retrieval

Security
Cryptography
Formal methods
Security services
Intrusion detection system
Hardware security
Network security
Information security
Application security

Human–computer interaction
Interaction design
Social computing
Ubiquitous computing
Visualization
Accessibility

Concurrency
Concurrent computing
Parallel computing
Distributed computing
Multithreading
Multiprocessing

Artificial intelligence
Natural language processing
Knowledge representation and reasoning
Computer vision
Automated planning and scheduling
Search methodology
Control method
Philosophy of artificial intelligence
Distributed artificial intelligence

Machine learning
Supervised learning
Unsupervised learning
Reinforcement learning
Multi-task learning
Cross-validation

Graphics
Animation
Rendering
Photograph manipulation
Graphics processing unit
Mixed reality
Virtual reality
Image compression
Solid modeling

Applied computing
E-commerce
Enterprise software
Computational mathematics
Computational physics
Computational chemistry
Computational biology
Computational social science
Computational engineering
Computational healthcare
Digital art
Electronic publishing
Cyberwarfare
Electronic voting
Video games
Word processing
Operations research
Educational technology
Document management

math in primary school

Numbers and Place Value

What is the difference between a ‘numeral’ and a ‘number’?

A numeral is the symbol, or collection of symbols, that we use to represent a number. The
number is the concept represented by the numeral, and therefore consists of a whole network
of connections between symbols, pictures, language and real-life situations.

The same number (for example, the one we call ‘three hundred and sixty-six’) can be represented by different numerals – such as 366 in our Hindu-Arabic, place-value system, and CCCLXVI using
Roman numerals

Because the Hindu-Arabic system of numeration is now more or less universal, the distinction between the numeral and the number is easily lost.

What are the cardinal and ordinal aspects of number?

cardinal基数;
a number, such as 1, 2 and 3, used to show quantity rather than order

ordinal序数词(如第一、第二等)
a number that refers to the position of sth in a series, for example ‘first’, ‘second’, etc.

s an adjective describing a small set
of objects: two brothers, three sweets, five fingers, three blocks, and so on. This idea of a number
being a description of a set of things is called the cardinal aspect of number.

numbers used
as labels to put things in order. For example, they
turn to page 3 in a book.
The numerals and words being used here do not represent
cardinal numbers, because they are not referring to sets of three things.In these examples, ‘three’ is one thing, which is labelled three because of the
position in which it lies in some ordering process. This is called the ordinal aspect of number.

The most important experience of the ordinal aspect of number is when
we represent numbers as locations on a number strip or as points on
a number line

Alt text

There is a further way in which numerals are used,
sometimes called the nominal aspect. This is where
the numeral is used as a label or a name, without any
ordering implied. The usual example to give here
would be a number 7 bus.

What are natural numbers and integers?

use for
counting: {1, 2, 3, 4, 5, 6, …}, going on forever.
These are what mathematicians choose to call the set
of natural numbers

the set of integers: {…, –5, –4, –3, –2, –1, 0, 1,
2, 3, 4, 5, …} now going on forever in both directions.
includes both positive integers (whole numbers greater than zero) and negative integers (whole
numbers less than zero), and zero itself.

The integer –4 is properly named ‘negative four’,
the integer +4 is named ‘positive four’,

natural numbers are positive integers.

Alt text

What are rational and real numbers?

include fractions and decimal
numbers (which, as we shall see, are a particular kind of(是一种特殊的) fraction), we get the set of
rational numbers.

The term ‘rational’ derives from the idea that a fraction represents a ratio.

The technical
definition of a rational number is any number that is the ratio of two integers.

Rational numbers enable us to subdivide the
sections of the number line between the integers and to label the points in between,

Alt text


there are other real numbers that cannot be written down as exact fractions or decimals – and are therefore not rational.

there is no fraction or decimal that is exactly equal to the square root of 50 (written as √50).
This means there is no rational number that when multiplied by itself gives exactly the answer
50.

– we could never get a number
that gave us 50 exactly when we squared it.

But √50 is a real number – in the sense that it
represents a real point on a continuous number line, somewhere between 7 and 8. It represents
a real length. So this is a real length, a real number, but
it is not a rational number. It is called an irrational number.
利用勾股定理得到平方根数的实际长度

the
set of real numbers includes all rational numbers – which include integers, which in turn
include natural numbers – and all irrational numbers.

What is meant by ‘place value’?

in the Hindu-Arabic system
we do not use a symbol representing a hundred to
construct three hundreds: we use a symbol representing three! Just this one symbol is needed to represent
three hundreds, and we know that it represents three
hundreds, rather than three tens or three ones, because
of the place in which it is written.

in our Hindu-Arabic place-value system, all
numbers can be represented using a finite set of digits,
namely, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9.

Like most numeration systems, no doubt because of the availability of
our ten fingers for counting purposes, the system uses
ten as a base.

Larger whole numbers than 9 are constructed using powers of the base: ten, a hundred, a
thousand, and so on.

The place in which a digit is written, then, represents that number of one of these powers
of ten

for example, working from right to left, in the numeral 2345 the 5 represents
5 ones (or units), the 4 represents 4 tens, the 3 represents 3 hundreds and the 2 represents
2 thousands.

the
numeral 2345 is essentially a clever piece of shorthand, condensing a complicated mathematical
expression into four symbols, as follows:
(2 × 103) + (3 × 102) + (4 × 101) + 5 = 2345.

Perversely, we work from right to left in determining the place values, with
increasing powers of ten as we move in this direction. But, since we read from left to right,
the numeral is read with the largest place value first


the principle of exchange.
This means that whenever you have accumulated ten in one place, this can be exchanged for
one in the next place to the left. This principle of being able to ‘exchange one of these for ten
of those’ as you move left to right along the powers of ten, or to ‘exchange ten of these for one
of those’ as you move right to left, is a very significant feature of the place-value system.

This principle of exchanging is also fundamental to the ways we do calculations with
numbers. It is the principle of ‘carrying one’ in addition

It also means that,
when necessary, we can exchange one in any place for ten in the next place on the right, for
example when doing subtraction by decomposition.

It also means that,
when necessary, we can exchange one in any place for ten in the next place on the right, for
example when doing subtraction by decomposition

How does the number line support understanding of place value?

Alt text

What is meant by saying that zero is a place holder?

‘three hundred and seven’ represented in base-ten blocks. Translated into symbols,
without the use of a zero, this would easily be confused with thirty-seven: 37. The zero is used therefore as a place holder; that is, to indicate the position
of the tens’ place, even though there are no tens
there: 307. It is worth noting, therefore, that when we
see a numeral such as 300, we should not think to
ourselves that the 00 means ‘hundred’.It is the position of the 3 that indicates that it stands for ‘three hundred’; the function of the zeros is to make this
position clear whilst indicating that there are no tens
and no ones.

Alt text

How is understanding of place value used in ordering numbers?

It
is always the first digit in a numeral that is most significant in determining the size of the number.

A statement that one number is greater than another (for example, 25 is greater than 16) or
less than another (for example, 16 is less than 25) is called an inequality

How are numbers rounded to the nearest 10 or the nearest 100?

Rounding is an important skill in handling numbers
One skill to be learnt is to round a number or quantity to the nearest something.

round a 2-digit number to the nearest ten.

67 lies between 60 and 70, but is nearer to 70

Alt text

Addition and Subtraction Structures

What are the different kinds of situation that primary children might encounter to which the operation of addition can be connected?

modelling process: setting up the
mathematical model corresponding to a given situation.

There are two basic categories of real-life problems that are modelled by the mathematical
operation we call addition.

• the aggregation structure;
• the augmentation structure.

aggregation聚合;
the act of gathering something together

augmentation增加;
the amount by which something increases

What is the aggregation structure of addition?

aggregation to refer to a situation in which
two (or more) quantities are combined into a single quantity and the operation of addition is used to determine the
total.

t the two sets do not overlap.
They are called discrete sets. When two sets are combined into one set, they form what is called the union of sets.So another way of describing this addition structure
is ‘the union of two discrete sets’.

This notion of addition
builds mainly on the cardinal aspect of number, the idea
of number as a set of things

Alt text

What are some of the contexts in which children will meet addition in the aggregation structure?

whenever they are putting together two
sets of objects into a single set, to find the total
number;

in the context of money.
finding the total cost of two
or more purchases, or the total bill for a number of
services

any measurement context:
n finding the total volume
of water in two containers

What is the augmentation structure of addition?

augmentation to refer to a situation where a quantity is increased by some amount
and the operation of addition is required in order to find the augmented or increased value.

Alt text

What are some of the contexts in which children will meet addition in the augmentation structure?

that of money:
particularly the idea of increases in price or cost, wage or salary.

temperature
an increase in temperature from a given starting temperature.

their age:

in other measurement contexts,

The key language that signals the operation of
addition is that of ‘increasing’ or ‘counting on’.

What is the commutative law of addition?

Which set is on the left and which on the right makes no difference to the total number of marbles. The fact that these two additions come to the same result is an example of what
is called the commutative law of addition.

We can state this commutative law formally by the following generalization, which is true whatever the
numbers a and b: a + b = b + a.

commutative交换的(排列次序不影响结果)
giving the same result whatever the order in which the quantities are shown

Second, it
is important to make use of commutativity in
addition calculations. Particularly when using the
idea of counting on, it is nearly always better to
start with the bigger number.

For example, it
would not be sensible to calculate 3 + 59 by starting at 3 and counting on 59! The obvious thing to do is to use the commutative law
mentally to change the addition to 59 + 3, then start at 59 and count on 3.

subtraction does not have this commutative property

What are the different kinds of situation that primary children might encounter to which the operation of subtraction can be connected?

• the partitioning structure;
• the reduction structure;
• the comparison structure;
• the inverse-of-addition structure.

What is the partitioning structure of subtraction?

The partitioning structure refers to a situation in which a quantity is partitioned off in some
way or other and subtraction is required to calculate how many or how much remains.

Alt text

What are some of the contexts in which children will meet the partitioning subtraction structure?

Partitioning occurs in any practical situation where we ask how many are left, or how much is
left.

It also includes situations
where a subset is identified as possessing some particular attribute and the question asked is,
‘how many are not?’ or ‘how many do not?’

money and shopping.

What is the reduction structure of subtraction?

The reduction structure is similar to ‘take away’ but
it is associated with different language. It is simply
the reverse process of the augmentation structure of
addition. It refers to a situation in which a quantity is
reduced by some amount and the operation of subtraction is required to find the reduced value.

Alt text

The essential components of this structure are a starting point and a
reduction or an amount to go down by.Because of this connection,
the idea of subtraction as reduction builds on the ordinal aspect of number.

What are some of the contexts in which children will meet subtraction in the reduction structure?

Realistic examples of the reduction structure mainly
occur in the context of money.

The key idea which
signals the operation of subtraction is that of ‘reducing’,

What is the comparison structure of subtraction?

The comparison structure refers to a completely different set of situations, namely those
where subtraction is required to make a comparison between two quantities, as for example
in Figure 7.5. How many more blue cubes are there than red cubes?

Subtraction of the smaller
number from the greater enables us to determine the difference, or to find out how much
greater or how much smaller one quantity is than the other.

Alt text

Comparison can build on both the cardinal aspect of
number (comparing the numbers of objects in two
sets) and the ordinal aspect (finding the gap between
two numbers on a number line).

What are some of the contexts in which children will meet subtraction in the comparison structure?

Wherever two numbers occur, we will often find ourselves wanting to compare them. The
first step in this is to decide which is the larger and which is the smaller and to articulate this
using the appropriate language.

articulate清楚说明
to express or explain your thoughts or feelings clearly in words

The next stage of comparison is then to go on to
ask: how many more? How many fewer? How much
greater? How much less? How much heavier? How
much lighter? How much longer? How much shorter?
And so on. Answering these questions is where subtraction is involved.

What is the inverse-of-addition structure of subtraction?

The inverse-of-addition structure refers to situations where we have to determine what must
be added to a given quantity in order to reach some target.

The phrase ‘inverse of addition
underlines the idea that subtraction and addition are inverse processes.The concept of inverse turns up in many situations in mathematics,
whenever one operation or transformation undoes
the effect of another one.

Hence, to solve a
problem of the form ‘what must be added to x to give
y?’ we subtract x from y

Alt text

What are some of the contexts in which children will meet subtraction in the inverse-of-addition structure?

any situation where we have a number of objects or a number of individuals and we require
some more in order to reach a target.

Mental Strategies for Addition and Subtraction

What is the associative law of addition?

the associative law of addition is a fundamental property of addition and an axiom of arithmetic. Written formally, as a generalization, it is the assertion that for any numbers a, b and c:
a + (b + c) = (a + b) + c.

The brackets
indicate which addition should be done first. In simple terms, the associative law says that if
you have three numbers to add together you get the same answer, whether you start by adding
the second and third or start by adding the first and second.

subtraction does not have this property.

How important is mental calculation?

Vertical layouts for additions and subtractions
especially lead children to treat the digits in the numbers as though they are individual numbers and then to
combine them in all kinds of bizarre and meaningless
ways

Mental strategies by their very ad hoc nature
lead you to build on what you understand and to use
methods that make sense to you.

ad hoc临时安排的;特别的;专门的
arranged or happening when necessary and not planned in advance

How does counting forwards and backwards help in mental calculations?

Alt text

How do we use multiples of 10 and 100 as stepping stones?

Notice what happens when we add 5 to 57 on a hundred square. We have to break the 5 down
into two bits, 3 and 2. The 3 gets us to the next multiple of 10 (60) and then we have 2 more
to count on. This process of using a multiple of ten (60) as a stepping stone is an important
mental strategy for addition and subtraction. Some writers refer to this process as ‘bridging’.

Here is how we might use this idea of a stepping
stone for calculating, say, 57 + 28. First, we could
count on in 10s, to deal with adding the 20: 57 … 67,
77. Then break the 8 up into 3 and 5, to enable us to
use 80 as a stepping stone: 77 + 8 = 77 + 3 + 5 =
80 + 5 = 85.

A number-line diagram is a very useful image for
supporting this kind of reasoning. Children can be
taught to use an empty number line, which is simply a line on which they can put whatever numbers
they like, not worrying about the scale, just ensuring
that numbers are in the right order relative to each other.

Alt text

Alt text

What is front-end addition and subtraction?

Most formal written algorithms for addition and subtraction work with the digits from right
to left, starting with the units. In mental calculations, it is much more common to work from
left to right. This makes more sense, because you deal with the biggest and most significant
bits of the numbers first.

One strategy is to mentally break the numbers up into hundreds, tens
and ones, and then to combine them bit by bit, starting at the front end – that is, starting by
adding (or subtracting) the hundreds.This process is sometimes called
partitioning into hundreds, tens and ones.

So, for example, given 459 + 347, we would think of
the 459 as (400 + 50 + 9) and the 347 as (300 + 40 + 7).

The front-end approach would deal with
the hundreds first (400 + 300 = 700), then the tens
(50 + 40 = 90, making 790 so far) and then the ones
(for example, 790 + 9 = 799; followed by 799 + 7 =
799 + 1 + 6 = 806). Notice that I have used 800 as a
stepping stone for the last step here.

459 + 347 = (400 + 50 + 9) + (300 + 40 + 7)
= (400 + 300) + (50 + 40) + (9 + 7)
= 700 + 90 + 9 + 7
= 799 + 7 = 799 + 1 + 6 = 800 + 6 = 806.

What is compensation in addition and subtraction?

You can often convert an addition or subtraction question into an easier question by temporarily adding or subtracting an appropriate small number.

For example, many people would
evaluate 673 + 99 by adding 1 temporarily to the 99, so the question becomes 673 + 100.
This gives 773. Now take off the extra 1, to get the answer 772. This strategy is sometimes
called compensation.

The trick in the strategy is always to be on the lookout for an easier calculation than the
one you have to do. This will often involve temporarily replacing a number ending in a 9 or
an 8 with the next multiple of 10.

Alt text

There are other ways of using the strategy of compensation, all of which amount to changing one or
more of the numbers in order to produce an easier
calculation.

How should the symbol for ‘equals’ be used in recording calculations?

There is a tendency for children (and some
teachers) to abuse the equals sign by employing it rather casually just to link the steps in a
calculation, without it having any real meaning.

How do multiples of 5 help in mental additions and subtractions?

Multiples of 5 (5, 10, 15, 20, 25, 30, …) are particularly easy to work with.

We can exploit this confidence with multiples
of 5 in many additions and subtractions done mentally.

37 + 26 = (35 + 25) + 2 + 1 = 60 + 2 + 1 = 63
77 + 24 = (75 + 25) + 2 – 1 = 100 + 2 – 1 = 101
174 – 46 = (175 – 45) – 1 – 1 = 130 – 1 – 1 = 128

How do you relate additions and subtractions to doubles?

Sometimes in additions and subtractions we can
exploit the fact that most people are fairly confident
with the processes of doubling and halving.

So it is found that young children will often exploit
their facility with doubles to calculate ‘near-doubles’.

48 + 46 could be related to double 46: 46 + 46 = 92, so 48 + 46 = 92 + 2 = 94.
62 + 59 could be related to double 60: 60 + 60 = 120, so 62 + 59 = 120 + 2 – 1 = 121.
54 – 28 could be related to half 54 (27): 54 – 27 = 27, so 54 – 28 = 27 – 1 = 26.
54 – 28 could be related to half 56 (28): 56 – 28 = 28, so 54 – 28 = 28 – 2 = 26.

How do you use ‘friendly’ numbers?

We
always have as an option in addition and subtraction to
use the compensation approach and temporarily
replace one of the numbers in a calculation with one
that is ‘more friendly’.

To calculate 742 – 146
Change the 146 to 142: 742 – 142 = 600
Now compensate: 742 – 146 = 600 – 4 = 596
Or,
Change the 742 to 746: 746 – 146 = 600
Now compensate: 742 – 146 = 600 – 4 = 596

compesate弥补
to provide sth good to balance or reduce the bad effects of damage, loss, etc.

How are mental methods used in estimations?

Confidence in handling mental calculations for addition and subtraction and a facility in
rounding numbers to the nearest 10, 100, 1000, or higher power of ten (see Chapter 6) are
prerequisites for being able to make reasonable estimates for the answer that should be
expected from an addition or a subtraction
.

In everyday life, we often require no more than
an approximate indication of what the result should be for many of the calculations we
engage with – particularly since, in practice, difficult calculations will usually be done on a
piece of technology where the likeliest error is that we enter the numbers incorrectly.

It is also
particularly important to have some rough idea of what size of answer should be expected
when using written calculation methods (see Chapter 9), where a small slip in applying a
procedure might produce a huge error.

(a) if two numbers are
rounded up to estimate their sum then the result will
be an over-estimate;
(b) if two numbers are rounded
down to estimate their sum then the result will be an
under-estimate.

for subtraction: (a) if the first number
in a subtraction is rounded up and the second number
rounded down then the result will be an over-estimate;
(b) if the first number in a subtraction is rounded down and the second number rounded up
then the result will be an under-estimate.

Written Methods for Addition and Subtraction

How might children be introduced to column addition?

for additions with numbers containing three or more digits we need to use
a written method of column addition: this is a way of laying out an addition calculation that
lines up the hundreds, tens and ones in columns. partitioning the numbers into hundreds, tens and ones.

The major source of error in using this format is that it encourages children
to think of the digits as separate numbers, losing any sense that they represent hundreds, tens
or ones.

Alt text

How do you explain what’s going on when you ‘carry one’ in addition?

Alt text

Alt text

Alt text

ten in one column can be exchanged for one in the
next column to the left.

When there are more than
two numbers being added, as in Figure 9.6(b), note
that it is possible to get more than one ten in the total
for a column, so we may need to carry two, as in this
example, or more.

Alt text

What about introducing column subtraction?

Subtractions are straightforward when each digit in the first number is greater than the corresponding digit in the second.
The problem comes when one (or more) of the digits
in the first number is smaller than the corresponding digit in the second number

standard written procedure for column subtraction, lining up the
hundreds, tens and ones in columns.

decomposition, which is the procedure introduced
in Figure 9.7(b) and set out in the traditional format in Figure 9.7(d).

Alt text

equal additions.

So how does subtraction by decomposition work?

Alt text

Alt text

Alt text

Alt text

Alt text

There are three important points to note about the
method of decomposition. First, there is the quite
natural idea of exchanging a block in one column for
ten in the next column to the right when necessary.
Second, there is the strong connection between the
manipulation of the materials and the recording in
symbols, supported by appropriate language. Third,
notice that all the action in the recording takes place in
the top line, that is, in the number you are working on,
not the number you are subtracting.

How does the method of equal additions differ from decomposition?

Alt text

The method is based on the comparison structure of subtraction. and uses
the principle that the difference between two numbers remains the same if you add the same
number to each one.

What is ‘borrowing’ in subtraction?

We are not ‘borrowing one’ in decomposition, we are ‘exchanging one of these for ten of those’.

What is the problem in decomposition with a zero in the top number?

Alt text

What is the constant difference method?

constant difference method, because as we change the subtraction into easier subtractions, we keep the difference
between the numbers constant.

The problem is 802 – 247
Add 3 to both numbers: 805 – 250 (that makes it easier)
Add 50 to both numbers: 855 – 300 (that makes it really easy!)
So the answer is 555.

How is addition used to check a subtraction calculation?

Because subtraction is the inverse of addition, as was explained in Chapter 7, a subtraction
calculation can always be checked by doing an addition. In general, if a – b = c, then c + b = a

Alt text

Multiplication and Division Structures

What are the different kinds of situation to which the operation of multiplication applies?

two categories of situation
that have a structure that corresponds to the mathematical operation represented by the symbol for
multiplication.

• the repeated aggregation structure;
• the scaling structure.

What is the repeated aggregation structure for multiplication?

Repeated aggregation (or repeated addition) is the elementary idea that multiplication
means ‘so many sets of’ or ‘so many lots of’.This structure is simply an extension of the aggregation structure of addition

Alt text

What is the scaling structure for multiplication?

The scaling structure is a rather more difficult idea.
It is an extension of the augmentation structure of
addition. In that structure, addition means increasing
a quantity by a certain amount. With multiplication,
we also increase a quantity, but we increase it by a
scale factor.

Alt text

I’m not sure whether 3 × 5 means ‘3 sets of 5’ or ‘5 sets of 3’

Alt text
the commutative law of
multiplication. This refers to the fact that when you are multiplying two numbers together,
the order in which you write them down does not
make any difference.

We recognize this commutative property formally by the
following generalization, which is true whatever the
numbers a and b: b × a = a × b.

division does nothave this property

Grasping
the principle of commutativity also cuts down significantly the number of different results
we have to memorize from the multiplication tables:

Is there a picture that can usefully be connected with the multiplication symbol?

rectangular array

Alt text

This picture really does make the commutative property
transparently obvious.

Apart from ‘so many sets of so many’, are there other contexts in which children meet multiplication in the repeated aggregation structure?

The repeated aggregation structure of multiplication
applies to what are sometimes referred to as ‘correspondence problems’, in which n objects are connected to each of m objects.

For example, if each of
28 children in a class requires 6 exercise books, then
the total number of exercise books required is
28 × 6.

the number or quantity being multiplied is sometimes called the multiplicand and the number it is being multiplied by is called the multiplier. For example, in ‘Spinach costs 65p a bag, how much for 3 bags?’ the 65 is the multiplicand and the 3 is the multiplier.

What are some of the contexts in which children will meet multiplication in the scaling structure?

Most obviously, this structure is associated with scale models and scale drawings.

This is also the multiplication structure that lies behind the idea of a pro rata increase.

For example, if we all get a 13% increase in our salary, then all our salaries get multiplied by the
same scale factor, namely 1.13

Then we also sometimes use this multiplication structure to express a comparison between
two numbers or amounts, where we make statements using phrases such as ‘so many times
as much (or as many)’ or ‘so many times bigger (longer, heavier, and so on)’.

What are the different kinds of situation to which the operation of division applies?

• the equal-sharing-between structure;
• the inverse-of-multiplication structure;
• the ratio structure.

What is the equal-sharing-between structure for division?

The equal-sharing-between structure refers to a situation in which a quantity is shared out equally into a given
number of portions and we are asked to determine how
many or how much there is in each portion.

Alt text

What is the inverse-of-multiplication structure for division?

The actual problems that occur in practice which have this inverse-of-multiplication structure can be further subdivided.

First, there are problems that incorporate the notion of
repeated subtraction from a given quantity, such as ‘how many sets of 4 can I get from a
set of 20?’

Second, there are those problems that incorporate the idea of repeated addition to reach
a target, such as ‘how many sets of 4 do you need to get a set of 20?

What is the ratio structure for division?

The ratio structure for division refers to situations where we use division to compare two
quantities.

For
example, if A earns £300 a week and B earns £900 a week,we could also compare A’s and B’s
earnings by looking at their ratio, stating, for example, that B earns three times more than A.

What about remainders?

The mathematical model is ‘32 ÷ 6 = 5,
remainder 2’. This means that sharing 32 equally into 6 groups gives 5 in each group, with 2
remaining not in a group

Remainders do not occur where division is used to model situations with the ratio structure.

What are some of the contexts in which children will meet division in the equal-sharing-between structure?

First, the set must be shared into
equal subsets. Second, it is
important to note that the language is sharing
between rather than sharing with.

What are some of the contexts in which children will meet division in the inverse-of-multiplication structure?

How many of these can I afford? This kind of question incorporates the idea of repeated subtraction from a given quantity.

How many do we need? This kind of question incorporates the idea of repeated addition to
reach a target. For example, how many items priced at £6 each must I sell to raise £150?

What about situations using the ratio division structure?

Mental Strategies for Multiplication and Division

What are the associative and distributive laws of multiplication?

associative law of multiplication.

distributive laws of
multiplication

Commutative law of multiplication: a × b = b × a
Associative law of multiplication: (a × b) × c = a × (b × c)
Distributive law of multiplication over addition: (a + b) × c = (a × c) + (b × c)
Distributive law of multiplication over subtraction: (a – b) × c = (a × c) – (b × c)

How are these laws used in multiplication calculations?

The commutative law allows you to choose which of the two numbers in a multiplication
question should be the multiplicand and which the multiplier

It is the commutative law that allows me to switch the
order of two numbers in a multiplication freely like this: 5 × 28 = 28 × 5.

think of the 28 as 14 × 2, choose to do 2 × 5 first (to get 10)
and then multiply this by 14
I am ‘associating’ the 2 with the 5, rather than with the 14, in order to
make the calculation easier: (14 × 2) × 5 = 14 × (2 × 5).

An alternative approach to calculating 28 × 5 would be to split the 28 into 20 + 8 and then
to multiply the 20 and 8 separately by the 5
(20 + 8) × 5 = (20 × 5) + (8 × 5)

Finally, we could choose to think of the 28 as 30 – 2 and then ‘distribute’ the multiplication
by 5 across this subtraction:
using the second of the distributive laws of multiplication:
(30 – 2) × 5 = (30 × 5) – (2 × 5)

What are quotients, dividends and divisors?

correspond to the words used in multiplication, introduced in the previous chapter: product,
multiplicand and multiplier. Quotient, dividend and divisor are the terms used to identify
the numbers in a division calculation

The result
of dividing one number by another is called the quotient.

The first number in the division, that which is to be
divided, is called the dividend.

The number by which it is divided is called the divisor.

Are there any fundamental laws of division?

division (like subtraction) is not commutative. We
should note here that division is also not associative (again like subtraction).

division can be distributed across addition and subtraction. There
are the following two distributive laws of division:
Distributive laws of division:
(a + b) ÷ c = (a ÷ c) + (b ÷ c)
(a – b) ÷ c = (a ÷ c) – (b ÷ c)

since 45 = 30 + 15, you can split 45 ÷ 3 into two easier divisions:
30 ÷ 3 and 15 ÷ 3,
(30 + 15) ÷ 3 = (30 ÷ 3) + (15 ÷ 3)

What are the prerequisite skills for being efficient at mental strategies for multiplication and division?

The first prerequisite is that you know thoroughly
and can recall easily all the results in the multiplication tables up to 10 × 10.

The second prerequisite is that you should be able
to derive from any one of these results a whole series
of results for multiplications involving multiples of
10 and 100.

70 × 8 = 560
7 × 80 = 560
70 × 80 = 5600
7 × 800 = 5600
700 × 8 = 5600
70 × 800 = 56,000
700 × 80 = 56,000

700 × 80, we can think
of the 700 as 7 × 100 and the 80 as 8 × 10. Then the
whole calculation becomes: 7 × 100 × 8 × 10. Using
the freedom granted to us by the commutative and
associative laws of multiplication to rearrange this
how we like, we can think of it as (7 × 8) ×
(100 × 10), which leads to 56 × 1000 = 56,000.

The third prerequisite is that you should be able to
recognize all the division results that are simply the
inverses of any of the above results. For example:
56 ÷ 8 = 7
56 ÷ 7 = 8
560 ÷ 8 = 70
5600 ÷ 70 = 80
56,000 ÷ 800 = 70

strategies, such as:
• the use of factors as an ad hoc approach to
multiplication;
• the use of doubling as an ad hoc approach to multiplication;
• ad hoc additions and subtractions in multiplication;
• ad hoc additions and subtractions in division;
• the constant ratio method for division.

How can factors be used as an ad hoc approach to multiplication?

A factor of any natural number is a natural number by which it can be divided exactly
without any remainder;

This strategy is particularly effective when there are
numbers ending in 5 around, since they are especially easy to multiply by 2 or 4. F

26 × 15 = (13 × 2) × 15
= 13 × (2 × 15) (using the associative law)
= 13 × 30 = 390

How can doubling be used as an ad hoc approach to multiplication?

any number can be obtained
by adding together some of the following numbers
(called the powers of 2): 1, 2, 4, 8, 16, 32, 64 … and
so on. For example, 23 = 16 + 4 + 2 + 1.

26 × 1 = 26
26 × 2 = 52
26 × 4 = 104
26 × 8 = 208
26 × 16 = 416
So, 26 × 23 = 416 + 104 + 52 + 26 = 598

How can you use ad hoc additions and subtractions in

multiplication?

First, by breaking up the 26 into 10 + 10 + 2 +
2 + 2, on the basis that I am confident in multiplying by
10 and by 2, we can transform 26 × 34 into (10 × 34) +
(10 × 34) + (2 × 34) + (2 × 34) + (2 × 34)

A second ad hoc approach to this calculation would be to think of the 34 as 10 + 10 +
10 + 5 – 1, so that 26 × 34 becomes (26 × 10) + (26 × 10) + (26 × 10) + (26 × 5) – (26 × 1),

And how can you use ad hoc additions and subtractions in division?

make a division much simpler by
writing it as the sum or difference of numbers that
are easier to divide by the given divisor.

s calculating how many
classes of 32 children would be needed for a school of 608. The child’s approach is to build
up to the given total of 608, by an ad hoc process of addition, using first 10 classes, then
another 5, then a further 2 and another 2. Formally, the child is breaking the 608 up into
320 + 160 + 64 + 64 and distributing the division by 32 across this addition as follows:
608 ÷ 32 = (320 + 160 + 64 + 64) ÷ 32
= (320 ÷ 32) + (160 ÷ 32) + (64 ÷ 32) + (64 ÷ 32)
= 10 + 5 + 2 + 2 = 19

What is the constant ratio method for division?

To understand the
constant ratio method for division, think of the division in terms of the ratio structure: if
both quantities are scaled by the same factor, then their ratio does not change – just as when
you add the same thing to two numbers, their difference does not change.

The division 75 ÷ 5 can be used to demonstrate the application of this principle. Multiply
both numbers by 2 and the question becomes 150 ÷ 10. So the answer is clearly 15.

We can also use the reverse principle: that we do not change the answer to a division calculation if we divide both numbers by the same thing.
648 ÷ 24 is the same as 324 ÷ 12 (dividing both numbers by 2)
324 ÷ 12 is the same as 108 ÷ 4 (dividing both numbers by 3)
108 ÷ 4 is the same as 54 ÷ 2 (dividing both numbers by 2), which is 27

it could lead you astray if you are dealing with a division that does not work out exactly
and you wish to give the answer with a remainder

Written Methods for Multiplication and Division

What is short multiplication?
Short multiplication refers to a formal way of writing out a multiplication of a number
with two or more digits by a single-digit number.

r the calculation 38 × 4. In essence, all that we do here is to use the distributive law explained in Chapter 11, breaking down the 38 into 30 + 8, and then multiplying the
8 by 4 and the 30 by 4 and adding the results.

Alt text

How might multiplication of two 2-digit numbers be introduced?

26X34

Thinking of the 26 and the 34 as 20 + 6 and
30 + 4 respectively suggests that we can split the
array up into four separate rectangular arrays of
counters, representing 20 × 30, 20 × 4, 6 × 30 and
6 × 4.
The answer to the multiplication is
obtained by working out the areas of the four separate rectangles and adding them up. This can be
called the areas method for multiplication.

20 × 30 = 600
6 × 30 = 180
20 × 4 = 80
6 × 4 = 24
884

The steps in the calculation can be set out in a grid, as shown below. Because of this,
many teachers call this the grid method:

Alt text

Alt text

How do you make sense of long multiplication?

The standard algorithm for multiplying together two numbers with two or more digits is usually called long multiplication

Alt text

In practice, the multiplication of 78
by 40 is done by first writing down a zero, as in
Figure 12.7(b), and then just multiplying 74 by 4,
as in (c). The zero has the effect of multiplying
the result of 74 × 4 by 10, hence producing 74 × 40, as required.

Alt text

There are various solutions to the problem of where to write the little digits that indicate
what is being carried, some of which can be very
messy and confusing when recorded in a child’s
handwriting (or mine, to be honest!). The best way is
to be so fluent in short multiplication that you do not
have to write them down at all,

What is short division?

Short division is a standard algorithm often used for divisions with a single-digit number as
the divisor, such as 75 ÷ 5,

First, you divide the 7 (tens) by 5. This gives the
result 1 (ten) remainder 2. The 1 is written in the tens position in the answer above the line.
The remainder, 2 (tens), is then exchanged for 20 ones. This exchange is indicated by the
little 2 written in front of the 5. There are now 25 ones to be divided by 5

Alt text

What is the ad hoc subtraction method for division?

Alt text

What about long division

The conventional algorithm for division, usually known as long division, can involve
some tricky multiplications and is, to say the least, not easy to make sense of.

illustrates the method for 648 ÷ 24. I’ll talk you through this. The first step is to ask, how
many 24s are there in 64? The answer to this question is 2, which is written above the 4 in
648. You then write the product of 2 and 24 (48) under the 64 and subtract, giving 16. The
8 in the 648 is then brought down and written next to the 16, making 168 in this row. You
then ask, how many 24s are there in 168? The answer to this is 7, which is written above
the 8 in 648. You then write the product of 7 and 24 (168) under the 168 and subtract it,
giving zero. So 648 ÷ 24 = 27, with no remainder.

Alt text

Alt text

Natural Numbers: Some Key Concepts

The multiples of any given (natural) number are obtained by multiplying the
number in turn by each of the natural numbers.

multiples of 3 are: 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, and so on;

the transitive property. Formally, this means that if A is a multiple of B and B is a
multiple of C, then it follows that A is a multiple of C.

Alt text

making use of the digital sum for each number. This is the number you get
if you add up the digits in the given number. If you then add up the digits in the digital sum,
and keep going with this process of adding the digits until a single-digit answer is obtained,
the number you get is called the digital root.

some useful tricks for spotting various multiples:
• Every natural number is a multiple of 1.
• All even numbers (numbers ending in 0, 2, 4, 6 or 8) are multiples of 2.
• A number that has a digital sum that is a multiple of 3 is itself a multiple of 3.
• The digital root of a multiple of 3 is always 3, 6 or 9.
• If the last two digits of a number give a multiple of 4, then it is a multiple of 4.
• Any number ending in 0 or 5 is a multiple of 5.
• Multiples of 6 are multiples of both 3 and 2. So, any even number with a digital root of 3,
6 or 9 must be a multiple of 6.
• If the last three digits of a number give a multiple of 8, then the number is a multiple
of 8.
• A number that has a digital sum that is a multiple of 9 is itself a multiple of 9.
• The digital root of a multiple of 9 is always 9.
• Any number ending in 0 is a multiple of 10.

What is a ‘lowest common multiple’?

For example, with 6 and 10, we obtain the following sets of
multiples:
• Multiples of 6: 6, 12, 18, 24, 30, 36, 42, 48, 54, 60, 66, …
• Multiples of 10: 10, 20, 30, 40, 50, 60, 70, …
The numbers common to the two sets are the ‘common multiples’ of 6 and 10: 30, 60,
90, 120, and so on.
The smallest of these (30) is known as the lowest common multiple.

if I can only buy a certain kind of biscuit in packets of 10 and I want to share all
the biscuits equally between 6 people, the number of biscuits I buy must be a multiple of
both 6 and 10; so the smallest number I can purchase is the lowest common multiple, which
is 30 biscuits.

What is a factor?

The concept of factor (see glossary for Chapter 11) is the inverse of multiple. So, if A is a
multiple of B then B is a factor of A.

all the different rectangular arrays possible with a
set of 24 crosses. The dimensions of these arrays are all the possible factor pairs for 24: 1
and 24; 2 and 12; 3 and 8; 4 and 6.

The mathematical relationship, ‘is a factor of’, also possesses the transitive property, as
illustrated in Figure 13.4. So, for example, any factor of 12 must be a factor of 24, because
12 is a factor of 24.

What about the ‘highest common factor’?

If we list all the factors of two numbers,
the two sets of factors may have some numbers in common. (Since 1 is a factor of all natural
numbers, they must at least have this number in common!) The largest of these common factors is called the highest common factor (or greatest common factor).

For example, with
24 and 30 we have the following two sets of factors:
• Factors of 24: 1, 2, 3, 4, 6, 8, 12, 24.
• Factors of 30: 1, 2, 3, 5, 6, 10, 15, 30.
The factors in common are 1, 2, 3 and 6. So the highest common factor is 6.

some teachers in a primary school require 40 exercise books a term and others require 32. It would be convenient
to store the exercise books in packs of 8, so that some teachers can pick up 5 packs and others 4 packs. Why 8? Because 8 is the highest common factor of 40 and 32.

What is a prime number?

Any number that has precisely two factors, and no more than two, is called a prime number

A number, such as 10,
with more than two factors is sometimes called a composite number, or, because it can be
arranged as a rectangular array with more than one row (see Figure 13.5), a rectangular
number

given
any composite number whatsoever, there is only one
combination of prime numbers that, multiplied
together, gives the number.
there is only one prime
factorization of any composite number

the number 24. This number can be obtained by multiplying together various
combinations of numbers, such as: 2 × 12, 2 × 2 × 6, 1 × 2 × 3 × 4, and so on. If, however, we stipulate that only prime numbers can be used, there is only one combination that will produce 24: namely, 2 × 2 × 2 × 3. This is called the prime factorization of 24.

there is no pattern or formula that will
generate the complete set of prime numbers.

Why are some numbers called squares? A square is a shape, isn’t it?

Some rectangles have equal sides: these are the rectangles that are called squares (see
Chapter 25). So numbers, such as 1, 4, 9, 16, 25, and so on, which can be represented by
square arrays, as shown in Figure 13.6, are called square numbers.

If we use an array of small
squares, called square units, as in Figure 13.6(b), rather than just dots, as in Figure 13.6(a),
then the number of squares in the array also corresponds to the total area

Square numbers are also composite
(rectangular) numbers, just as squares are rectangles

Most positive integers have an even number of factors.
This is because factors tend to come in pairs.
square numbers always have an odd number of factors!

What are cube numbers?

there are those, such as 1, 8 and
27, that can be represented by arrangements in the shape of a cube. These cube numbers
will turn up in exploring the volumes of cubes with older children. Figure 13.8 shows how
the first three cube numbers are constructed from small cubes, called cubic units.

Alt text

What are square roots and cube roots?

Which number, when multiplied by itself, gives 729? Or,
which number has a square equal to 729? The answer (27) is called the square root of 729.

what is the
length of the side of a cube with a total volume of
729 cubic units? Or, in arithmetic terms, what
number has a cube equal to 729? The answer (9) is called the cube root of 729. A

Are there other sets of geometric shapes that correspond to sets of numbers?

Almost any sequence of geometric shapes or patterns can be used to generate a corresponding set of numbers

Alt text

the so-called triangle numbers. These are the numbers that correspond to the particular pattern of triangles of dots shown in Figure 13.10: 1, 3, 6, 10, 15, and so
on.

Alt text