Based mostly on the Tutorial, sections 1-4
Initializing Python: PYTHONSTARTUP environment variable, if set, gives the name of a file containing start-up commands for the interpreter
What is a script?
Making the script executable:
#!/usr/bin/pythonor
#!/usr/bin/python3or
#!/usr/bin/env pythonor
#!/usr/bin/env python3
$ chmod u+x script # executable by you $ chmod u+x,g+x,o+x script # executable by everyone
$ ./scriptor if its directory is in PATH, just
$ script
Running with arguments:
./script arg1 arg2 ...
Getting the arguments in the script:
import sys
sys.argv is an array of strings:
[''] if just running the Python interpreter (no script);
['script', 'arg1', 'arg2', ...] otherwise,
where 'script' is the exact name of the script used in the
command to run it, e.g., './script1.py'
→ Example: script.py
Concatenation:
Repetition: s1 * n
Indexing: s1[0], etc.
Slicing:
s1[3:5] s1[3:] s1[:5] s1[:] # (copies the whole of s1)
String methods are documented in the Python Standard Library
documentation for the str type.
You can also access this documentation by
typing help(str) in Python.
There are two approaches to formatting in Python.
One uses % as a formatting operator
and is documented under
printf-style String Formatting.
The newer approach uses the
Format class from the string module;
see
String Formatting.
I haven't used the new method much.
What is Unicode?
In Python 2, you had to prefix Unicode strings with
u because strings used ASCII encoding by default:
u'text' or u"text".
In Python 3, strings are Unicode strings by default,
so the u prefix is unnecessary—in fact,
it would be a syntax error.
Example:
(Note that for non-ASCII literals, but not for the "\u" escape codes, the file must contain a "coding: " declaration in the first or second line.)
Control: the do-nothing 'pass' statement
for i in range(10):
pass
def donothing ():
pass
donothing() => None
None is a value (!) which means "no value" (!).
E.g., it is the value of a function which returns no value.
It is usually suppressed by the repl, but you can explicitly
print it:
print(donothing())
Functions with fixed argument lists
Default values with optional and keyword arguments
"Catch-all" tuples for optional arguments
"Catch-all" dictionaries for optional keyword arguments
Unpacking tuples or dictionaries when calling a function
→ Example: funargs.py
Anonymous functions using the lambda form:
lambda arg: return-value-expression
lambda arg1, arg2, ..., argn: return-value-expression
lambda: return-value-expression
→ Example: lambdafunctions.py
s1 = "a5d",
s2 = "7z", and s3 = "elephant",
write string expressions using
the variables to produce these values: