Chapter 1
- Again, I assume these concepts are familiar. I’m just going to highlight the aspects that are
specific to Python.
- Open “In-Class 1”
- Log into PrairieLearn,
- navigate to the assessment named “In-Class 1”
- Set up a group, if you like.
- Launch the workspace
- Open
playspace
- “play” with it. Both the markdown and the code.
- Demonstrate some markdown features
- Demonstrate some python features
- variables carry from window to window.
- if you run cell-by-cell, the code goes in execution order, not “top-down”
Variables
- Letters, numbers, underscores.
- Can’t start with a number.
- Convention is to use
snake_case
not camelCase
- Avoid names that begin with two underscores.
- Doesn’t need to be declared (like with C or Java). Just assign a value (
x = 7
)
- Can’t be read before being assigned.
- modify sample code to reference variable that doesn’t exist and show resulting error.
- String literals go in quotes.
Output
print
method
- comma-separated list of items to print.
- Python inserts space between parameters!
- This is different from many other languages.
- Give demo.
print
ends with a newline by default.
- To override:
print('No newline', end=' ')
- You can also use string interpolation.
- Put
f
before string.
- Put code to be interpolated in braces.
- Notice that braces can contain code, not just variable.
print(f"The cost with tax is ${cost*1.06}")
- zyBook uses comma-separated list. You can use whichever technique you prefer.
- https://www.programiz.com/python-programming/string-interpolation
- Use string interpolation to format floating-point values
print(f'{myFloat:.2f}')
- You can also use the same pattern to format integers
printf(f'{someInt:.05})
to produce leading zeros.
input()
returns the entire line (except the newline) typed by the user as a string
- return value of
input
is always a string
- use
int()
function to convert it to an integer.
- show what happens if you forget conversion
f = input()
print(f"You entered->{f+4}<-")
- Use
float()
to convert to floating-point.