Today: loose ends: comprehension-if, truthy logic, format strings, is None, tech and society

## Comprehensions - Recall 1-2-3

• There is one more feature of list comprehensions
• Recall - comprehension re-uses syntax of other contructs
• 1. type in a pair of outer brackets [ ]
• 2. inside write a foreach "for n in nums" - choose var name "n" or "s" ..
e.g. typical Python: choose var name to keep your ideas straight
• 3. then the result expression "n * n" goes on the left

## Comprehension + If

• Can add "if" filter on the right hand side
add at right: `if n > 3`
Mnemonic: re-use syntax again
• Left hand side can be just "n" to pass value through unchanged
```>>> nums = [1, 2, 3, 4, 5, 6]
>>> [n for n in nums if n > 3]
[4, 5, 6]
>>> [n * n for n in nums if n > 3]
[16, 25, 36]
```

## Comprehension - 1 Line

Can get into Comprehension Fever - trying to write your whole program as nested comprehensions. Probably 1-line is the sweet spot.

Using regular functions, loops etc. for longer phrases is fine.

## You Try It - Comprehensions

These are all 1-liner solutions with comprehensions. We'll just do 1 or 2 of these.

Syntax reminder - e.g. make a list of nums doubled where n > 3

```[2 * n for n in nums if n > 3]
```
> Comprehensions

Try these in class

For more detail see "truthy" section in the if-chapter Python If - Truthy

## Truthy True/False

• Think if/while with boolean
• Actualy *any value works
• What does this do?
• What does `s` mean in an if-test?
```s = 'hello'
if s:
print('truthy')
```

## Truthy False

Truthy logic says that "empty" values count as `False`. These all count as `False` - zero, emtpy-string, empty-list,...

```# Count as False:
0
0.0
None
''
[]
{}
```

## Truthy True

Any other value counts as `True`

```# Count as True
6
3.14
'Hello'
[1, 2]
{1: 'b'}
```

## Truthy bool()

The `bool()` function takes any value and returns a formal bool `False/True` value, so it's a way for us to see how truthy logic works in the interpreter:

```>>> bool(0)
False
>>> bool(0.0)
False
>>> bool('')   # empty string - False
False
>>> bool([])   # empty list - False
False
>>> bool(None)
False
>>> bool(6)       # non-zero int - True
True
>>> bool('hi')    # non-empty string - True
True
>>> bool([1, 2])  # list of something - True
True
>>> bool('False')  # ??? - what's this one?
???
>>> bool([0, 0])   # ???
???
>>>
```

## Truthy Shorthand

Why does the truthy system exist? It makes it easy to test, for example, for an empty string like the following. Testing for "empty" data is such a common case, it's nice to have a shorthand for it. For CS106A, you don't ever need to use this shorthand, but it's there if you want to use it. Also, many other computer languages also use this truthy system.

```# long form screen out empty string
if len(s) > 0:
print(s)

# shorter way, handy!
if s:
print(s)
```

> not_empty

## What's this `__name__` Thing?

• By the end of CS106A..
• Explain every single line in, say, wordcount.py
• What is this thing at the bottom of the file
• Basically, every Python file as this at the bottom
```if __name__ == '__main__':
main()
```

## Two Ways wordcount.py Is Loaded Into Python

There are two ways wordcount.py is loaded into Python. (1) is the obvious way (2) is less common but does happen.

```# 1. From the command line:
\$ python3 wordcount.py poem.txt

# 2. Loaded as an import into
# some other python file
...
import wordcount
```

## Q: When To Run main()

Which of those two forms should run main()? The answer is .. just the (1) form, running wordcount.py from the command line. The other form .. don't run main()

## A: That's What This Does

The symbol `__name__` will be `'__main__'` for the (1) case. This if-statement checks for that symbol, and if so, calls the main() function.

```if __name__ == '__main__':
main()
```

## Remember: End With Those Two lines

That's a lot of detail for a kind of rare case. Just remember this: have that if-statement at the bottom of your file. It calls the main() function when this file is run on the command line.

## `==` vs. `is` Comparisons

To compare things, use the `==` operator. That is the main one and it is quite reliable.

However, there is another comparison called `is`. This checks if two variables refer to the exact same object in memory.

You can go an entire lifetime and never need to use `is` operator in code - it just does not compute something that code typically needs to know. You should default to using `==` to compare values.

That said, here is a demo of `is`

```>>> a = [1, 2, 3]
>>> b = a
>>> a is b          # "is" True case
True
>>> c = [1, 2, 3]   # c looks like a
>>> a is c          # "is" False case
False
>>> a is not c      # "is not" variant
True
>>>
>>> a == c          # == returns True
True
>>>
```

## PEP8 `is None` Rule

The one time you need to use `is` is for PEP8 conformance. PEP8 says to use `is` for the values `None, True, False`, but really `None` is the one that comes up all the time.

So for PEP8, it's preferable to use `is` instead of `==`, like this. The reasons for this are a bit obscure, but it's simplest to just follow PEP8.

```if x == None:          # NO not this way
print('nothing')

if x is None:          # YES this way
print('nothing')
```

We will never mark off CS106A code that uses `==` here (which in fact will work perfectly), but for PEP8 you can write it with `is`.

## Format Strings

• Neat, new feature
• Paste values into a string
• 1. Begin string with `f` to left of quote mark
`s = f'A format string'`
• 2. Curly braces are expressions which can refer to variables
Python evaluates each expressions
Pastes in the result

Try in the interpreter:

```>>> name = 'Sally'
>>> scores = [19, 34, 22]
>>>
>>> s = f'Name:{name} count:{len(scores)}'
>>> s
'Name:Sally count:3'
>>> s = f'Name:{name} count:{len(scores)} max score:{max(scores)}'
>>> s
'Name:Sally count:3 max score:34'
```

Amazingly, within the curly braces, just write any old expression like `{name}` referring to a variable, or even `max(scores)` which calls a function, pasting in what it returns.

To include a literal `{` or `}` in the string, double them up - so `{{` to make one `{`

```>>> f'A curly brace: {{'
'A curly brace: {'
```

Quick tech and society points, just for fun.

## 1. Why Is Everything on the Internet Free?

• Disclosure: I used to work for Google
• 1. Content you want
• 2. Ads right next to the content
• The ads provide the money to pay writers to create the content
• Like (1) is the meal, and (2) is the check showing up at the end
• The ads are a little irritating
• But appreciate .. the ads fund the creation of the content
• This model functions ok, funding a tons of content
• This is the same model as, say, NBC TV .. content + ads

## 1b Pay For Content Model

• Netflix is another model
• You pay Netflix
• Netflix uses some of the money to pay writers, actors etc. to make the content
• Except there are tons of ads .. just for Netflix shows!

Mostly, technology getting better has made life better. But not this story!

## e.g. Flat Earth Disinformation Story

• Suppose a user watches a "flat earth" video on youtube
This is conspiracy minded / disinformation
The earth is not flat!
It's a bunch of lies
• It turns out, more disinformation is very compelling for these users
• Like a drug
• What is the optimal choice for that next video?
• More conspiracy type content is the most compelling/profitable choice
• The algorithm shows them more disinformation content .. it's the best fit for that user

## Disinformation - What to do?

• Disinformation content is very compelling
For those who like it
A feature of human nature
• Therefore it is profitable
• Therefore the algorithm wants to show them more
• My opinion:
This situation where disinformation is promoted seems bad for society
The disinformation is like a form of pollution
However 1st amendment free-speech is an important right
So I don't know how society fixes this

## 3. Open Source - Python is an Example

You have noticed that Python works well on your machine, and yet it's free. How does that work? Python is a great example of "open source" software.

Much of the internet is based on open standards - TCP/IP, HTML, JPEG - and open source software: Python (language), Linux (operating system), R (statistics system).

## How Open Source Works:

Let's look at Python

## Open Source License - Contributions

• The "source code" is the code to produce Python itself
• Python has an "open source" license
Basically encourages contributing improvements back to Python source code
• There are many variations in open source licenses, but free and "contribute-back" are the keys

## Open Source Economics

• This is an incredibly successful model
• Anyone can build their work on Python, free, not dependent on one vendor
e.g. Build on Microsoft Visual Basic
Microsoft charged for it
And eventually they discontinued it