x
, my_variable
, or variable_1
=
Variable names in Python can contain alphanumerical characters a-z
, A-Z
, 0-9
and some special characters such
as _
. Normal variable names must start with a letter.
By convention, variable names start with a lower-case letter, and Class names start with a capital letter.
In addition, there are a number of Python keywords that cannot be used as variable names. These keywords are:
and, as, assert, break, class,
continue, def, del, elif, else,
except, exec, finally, for, from,
global, if, import, in, is, lambda,
not, or, pass, print, raise,
return, try, while, with, yield
Note: Be aware of the keyword lambda
, which could easily be a natural variable name in a scientific program. But
being a keyword, it cannot be used as a variable name.
Since Python is dynamically typed, it automatically sets the types of your variables upon assignment
Operators are defined as "constructs which can manipulate the values of operands"...
Arithmetic operators:
+
-
*
/
//
(integer division)**
(power)%
(modulus)
Note: don't try to use the caret (^) for power in Python! For the curious: https://docs.python.org/2/reference/expressions.html#binary-bitwise-operations
Comparisons are operators which evaluate properties
of their operands and always return either True
or False
Common comparisons:
<
>
==
>=
<=
!=
is
and is not
check whether two things point to the same object, not just equality
and
: x and y
first evaluates x
x
is false, its value is returnedy
is evaluated and the resulting value is returnedor
: x or y
first evaluates x
x
is true, its value is returnedy
is evaluated and the resulting value is returnednot
: yields True
if its argument is false, False
otherwiseand
¶
or
¶
not
¶
You can pull out different chunks of the string using [start:end:step]
start
defaults to 0end
defaults to len(string)-1
(i.e. the last character)step
defaults to 1
Tuples are like lists but immutable, meaning they cannot be changed
{key1 : value1, ...}
if
, elif
(else if), and else
if condition:
and are then indented below
for
loops¶
while
loops¶while
loops keep executing until they evalute to False
Ctl+C
(or Ctl+D
) if you do...
To use a module in a Python program it first has to be imported. A module can be imported using the import
statement. For example, to import the module math
, which contains many standard mathematical functions, we can do:
$ \cos(2 \pi) = 1 $
$ \cos(\frac{\pi}{2}) = 0 $
# https://docs.python.org/2/tutorial/floatingpoint.html
Importing from modules
import *
Functions are reusable and flexible bits of Python code
Functions are scoped - they have access to global variables, but variables created inside of them are local to the function and invisible outside of it
def func_name(x):
return x**2