X is positive
Lecture 03
Python supports typical if / else style conditional expressions,
This is a fairly unique feature of Python - expressions are grouped together via indenting. This is relevant for control flow (if
, for
, while
, etc.) as well as function and class definitions and many other aspects of the language.
Indents should be 2 or more spaces (4 is generally preferred based on PEP 8) or tab character(s) - generally your IDE will handle this for you.
Conditional expressions do not have their own scope, so variables defined within will be accessible / modified outside of the conditional.
This is also true for other control flow constructs (e.g. for
, while
, etc.)
while
loopswill repeat until the provided condition evaluates to False
,
for
loopsiterate over the elements of a sequence,
break
and continue
allow for either an early loop exit or a step to the next iteration respectively,
else
Both for
and while
loops can also include an else
clauses which execute when the loop is completes by either fully iterating (for
) or meetings the while
condition, i.e. when break
is not used.
pass
is a placeholder expression that does nothing, it can be used when an expression is needed syntactically.
List comprehensions provides a concise syntax for generating lists (or other sequences) via iteration over another list (or sequences).
if
List comprehensions can include a conditional clause(s) to filter the input list / object,
[0, 4, 16, 36, 64]
[1, 9, 25, 49, 81]
for
keywordsSimilarly, the comprehension can also contain multiple for
statements which is the equivalent of nested for
loops,
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
zip
Is a useful function for “joining” the elements of multiple sequences (so they can be jointly iterated over),
zip
and length mismatchesThe length of the shortest sequence will be used, additional elements will be ignored (silently)
Using list comprehensions, complete the following tasks:
Create a list containing tuples of x and y coordinates of all points of a regular grid for \(x \in [0, 10]\) and \(y \in [0, 10]\).
Count the number of points where \(y > x\).
Count the number of points \(x\) or \(y\) is prime.
Functions are defined using def
, arguments can be defined with out without default values.
return
statementsFunctions must explicitly include a return
statement to return a value.
Functions can return multiple values using a tuple or list,
A common practice in Python is to document functions (and other objects) using a doc string - this is a short concise summary of the objects purpose. Docstrings are specified by supplying a string as the very line in the function definition.
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
str(object='') -> str
str(bytes_or_buffer[, encoding[, errors]]) -> str
Create a new string object from the given object. If encoding or
errors is specified, then the object must expose a data buffer
that will be decoded using the given encoding and error handler.
Otherwise, returns the result of object.__str__() (if defined)
or repr(object).
encoding defaults to sys.getdefaultencoding().
errors defaults to 'strict'.
Return a copy of the string converted to lowercase.
In Python the argument order matters - positional arguments must always come before keyword arguments.
def f(pos1, pos2, /, pos_or_kwd, *, kwd1, kwd2):
----------- ---------- ----------
| | |
| Positional or keyword |
| - Keyword only
-- Positional only
For the following function x
can only be passed by position and z
only by name
If the number of arguments is unknown / variable it is possible to define variadic functions using *
or **
. The former is for unnamed arguments which will be treated as a tuple
, the latter is for named arguments which will be treated as a dict
.
are defined using the lambda
keyword, they are intended to be used for very short functions (syntactically limited to a single expression, and do not need a return statement)
Python nows supports syntax for providing metadata around the expected type of arguments and the return value of a function.
These annotations are stored in the __annotations__
attribute
kg_to_lb
, that converts a list of weights in kilograms to a list of weights in pounds (there a 1 kg = 2.20462 lbs). Include a doc string and function annotations.total_lb
, that calculates the total weight in pounds of an order, the input arguments should be a list of item weights in kilograms and a list of the number of each item ordered.Sta 663 - Spring 2023