| Interactive Mode | Source File Execution | Variables | Statements |
| Expressions | Comments | Data Types | Operations & Operators |
| Order of Operation | Input / Output | Control: if | Control: while |
| Control: for |
For more details on the points covered in this quick-start see Introduction to Python: www.mhuffman.com/notes/language/py_intro.htm and the many fine beginner tutorials and descriptions at www.python.org/doc/Intros.html
Python is an interpreted language, even though there is a compile step in the translation from ASCII text source code to binary machine language. However, because the source code is interpreted the compile step occurs each time you execute a Python program, and no compiled machine-readable object file is created.
Python is a command line application; on Windows operating systems it runs in a Windows Console (a.k.a. Command Prompt window or DOS window). Your command to run Python must either include the full path to the Python interpreter OR you must include the full path to the Python interpreter in your PATH environment variable. See Command Line User Interface > Setting the PATH: www.mhuffman.com/notes/dos/dos.htm#PATH
Note:
The phrase "Enter the command ..." means type the command at the prompt
and press the Enter key.
C:\Python23 is an example; replace
C:\Python23
with the actual drive letter and directory where your Python is
installed.
Note:
filename means you
must replace the text filename with the
name of the file including extension that you are using.
C:\Python23 is an example; replace
C:\Python23
with the actual drive letter and directory where your Python is
installed.
If standard Python file extensions like .py are associated with Python (the default for a standard Windows installation) then you can simply double-click a Python source file in Windows Explorer to run the script. There are 2 problems with this method:
raw_input("Press ENTER to continue...")
The Python distribution includes IDLE, which is essentially a Python script calling Python Graphic User Interface (GUI) modules and libraries. If Win32 Extensions are installed, there is an additional IDE called Pythonwin. Most tutorials and online books include a section on IDLE. One Day of IDLE Toying: http://hkn.eecs.berkeley.edu/~dyoo/python/idle_intro/index.html is an excellent introduction to IDLE as well as the Python interactive interpreter.
Python variables are named identifiers that bind the name with a location in memory that stores a value. Python variables are case- sensitive (foo and FOO are different identifiers). Variable names may use any upper or lower case letter, any digit, and the under-score character. However, variable names may not begin with a digit.
Statements are like English sentences. Statements issue a complete command or instruction consisting of Python keywords and expressions to the computer to execute. Python statements and when you end the line and start a new statement on the next line. A Python program is composed of one or more statements.
print "2 ** 8 =", 2 ** 8 # output statement using print area = 3.14159 * 5 ** 2 # assignment statement
Expressions are elements of Python syntax that have a value. Expressions can be as simple as a single variable name or literal value. 21, foo, "Hello World" are all expressions. 21 + 2.3, foo * 3 / 5, "Hello " + user_name + ", and welcome!" are also expressions composed of simpler expressions. A statement will usually be made up of one or more expressions and a Python keyword, assignment operator, or function.
In interactive mode Python will display the value of an expression by itself; in source files interpreted by Python expressions are part of statements (assignment, conditional, looping, etc.)
3.14159 * 5 ** 2 # expression area # expression "Hello World" # expression
The # character begins a comment (text that is ignored by the interpreter). Comments begin with # (except # within string literals) and continue to the end of the line.
# compute area of circle area = 3.14159 * 5 ** 2 # '**' is the exponentiation operator
Data types do not need to be declared in Python. The first time you assign a value to a variable Python binds the name to the variable and creates memory based on the type of data being assigned. If you later assign a different data type to same name it will have the new data type. However, while a variable name is bound to a chunk of data the data type will not change (until you bind to a different type). In other words, the string "911" will always be a string of 3 ASCII characters and not magically turn into the integer nine hundred eleven.
Sequences are somewhat like arrays in other languages, except that individual items in any given Python sequence can be of any other Python type, including another sequence. A sequence is an ordered collection, each item is accessed by a sequential index starting at 0.
Dictionaries are called associative arrays, hashes, and maps in other languages. A Dictionary is an unordered collection, each value is accessed by a named index (e.g. a string), called a key. Collectively dictionary items are a key-value pair.
| Assignment | = | a = 3, name = "Fred" | |
| Operations on Numbers |
|||
|---|---|---|---|
| Addition | + | 8 + 3 | 11 |
| Subtraction | - | 8 - 3 | 5 |
| Multiplication | * | 8 * 3 | 24 |
| Division | / | 8 / 3 8 / 3.0 |
2 # 2.6666666666666665 |
| Integer Division | // | 8 // 3 8 // 3.0 |
2 2.0 |
| Modulus | % | 8 % 3 | 2 |
| Exponentiation | ** | 8 ** 3 | 512 |
| Operations on Bits |
|||
| a = 00001101 base 2 (13 base 10); b = 00011000 base 2 (24 base 10) | |||
| Bit shift left | << | a << 1 | 00011010 (26 base 10) |
| Bit shift right | >> | b >> 2 | 00000110 (6 base 10) |
| Bitwise and | & | a & b | 00001000 (8 base 10) |
| Bitwise or | | | a | b | 00011101 (29 base 10) |
| Bitwise xor (exclusive or) | ^ | a ^ b | 00010101 (21 base 10) |
| Bitwise not (negation) | ~ | ~a | 11110010 (242 base 10, unsigned) 11110010 (-14 base 10, sign extended) |
| Operations on Strings |
|||
| Concatenation | + | "one" + "two" | "onetwo" |
| Repetition | * | "one" * 3 | "oneoneone" |
| Comparison Operators |
|||
| a = 8; b = 3 | |||
| Greater than | > | a > b a > a |
1 (true) 0 (false) |
| Greater than or equal | >= | a >= b a >= a |
1 1 |
| Less than | < | a < b a < a |
0 0 |
| Less than or equal | <= | a <= b a <= a |
0 1 |
| Equal | == | a == b a == a |
0 1 |
| Not equal | != | a != b a != a |
1 0 |
| Logical Operators |
|||
| Logical AND | and | a > b and a != b | 1 (true) |
| Logical OR | or | a > b or a == b | 1 |
| Logical NOT | not | not a == b | 1 |
| Augmented Assignment |
|||
| str = "foo" | |||
| += | a += 5 str += "bar" |
a = a + 5 str = str + "bar" |
|
| -= | a -= 5 | a = a - 5 | |
| *= | a *= 5 str *= 3 |
a = a * 5 str = str * 3 |
|
| /= | a /= 5 | a = a / 5 | |
| //= | a //= 5 | a = a // 5 | |
| %= | a %= 5 | a = a % 5 | |
| **= | a **= 5 | a = a ** 5 | |
Python operators, like operators in math, follow rules of precedence, and the arithmetic-like operators behave as you would expect (exponents evaluate before multiplication & division, which evaluates before addition & subtraction, etc). With the exception of exponentiation ( **) all operations evaluate from left to right.
Default precedence can be overridden with the use of parentheses just like in mathematics: 3 + 4 * 5 = 23, however (3 + 4) * 5 = 35. It never hurts to use parentheses even when not strictly required if it helps clarify the meaning of the statement. If you do not want to keep a precedence chart handy a good rule is to simply remember that exponents evaluate before multiplication and division, which evaluates before addition and subtraction; for all other cases use parentheses. Anyone else who reads your code will be appreciative, and you will be also a week later when you read your code.
| Order of Operation (Highest to Lowest) |
|||
|---|---|---|---|
| (...), [...], {...} | Tuple, list, dictionary creation | ||
| s[i], s[i:j] f(...) |
Index & slice operations Function calls |
||
| +x, -x, ~x | Unary operators | ||
| x ** y | Exponentiation (evaluates right to left) | ||
| x * y, x / y, x // y, x % y | Multiplication, division, integer division, modulus (remainder) division | ||
| x + y, x - y | Addition, subtraction | ||
| x << y, x >> y | Bit shift | ||
| x & y | Bitwise and | ||
| x ^ y | Bitwise exclusive or (xor) | ||
| x | y | Bitwise or | ||
| x < y, x <= y, x > y, x >= y, x == y, x != y x is y, x is not y x in y, x not in y |
Comparison & equality Identity Membership |
||
| not x | Logical negation | ||
| x and y | Logical and | ||
| x or y | Logical or | ||
Use the print keyword to display output to the screen. Python will add a newline at the end of a print statement unless the statement ends with a comma. Items following print separated with a comma will be displayed separated with a space.
print 3 + 7 # displays 7, moves cursor to next line print 1, 2, 4, 8 # displays 1 2 4 8 then moves cursor to next line print "Hello", # displays "Hello" and a space print "World" # displays "World" on same line as "Hello"
Use the raw_input() function with a prompt string to get user input from the keyboard. If the input is a number (used in a calculation) convert it to the applicable date type using int(), long(), or float().
As a general rule, if you are expecting numeric input use raw_input() and convert it to a floating point number. You can then further convert the floating point number to an integer if needed. However, trying to convert the string representation of a floating point number directly to an integer is an error.
name = raw_input("Enter your name: ") # user enters Fred
print "Hello", name # Hello Fred
number = raw_input('Enter a Number: ') # user enters 8.6
number = int(number) # ValueError: invalid literal for int(): 8.6
number = raw_input('Enter a Number: ') # user enters 8.6
number = float(number) # number = 8.6
print number, "/ 3 =", number / 3 # 8.6 / 3 = 2.86666666667
# time passes and we need to use number as an integer
number = int(number) # number = 8
print number, "/ 3 =", number / 3 # 8 / 3 = 2
Python functions return values that can be used as arguments to other functions. If you know you want an integer, and are happy to simply truncate the fractional part if a user enters a floating point number, you can nest raw_input() and float() within int().
number = int(float(raw_input('Enter an integer: '))) # user enters 5.5
# number = 5
Python control structures are contained within blocks delimited by indentation. The start of a control structure is noted by a line with the if, while, or for key word; a logical expression to control the structure, and a colon(:). The logical expression does not need to be enclosed in parentheses unless needed to establish precedence, but it does not hurt.
Unlike most other high-level languages, Python does not use BEGIN ... END statements or special punctuation (such as the "curly brace" in C, C++, Java, Perl, etc.). The indentation must be the same for the entire block. Tabs or spaces may be used; do not mix tab and spaces in the same block. A preferred "style" guideline among Python programmers seems to be the use of only spaces. Most text editors support an option that converts tabs to spaces.
if <condition>:
# uniformly indented statement(s)
elif <condition>:
# uniformly indented statement(s)
else:
# uniformly indented statement(s)
elif and else blocks are optional. <condition> is a comparison expression, or compound logical and comparison expression. Each if, elif, else block is a compound statement, sometimes called a clause. The block is delimited by the if, elif, else keyword, a comparison or logical expression, and a colon followed by one or more indented lines. Each block ends when the interpreter reads a line that is not indented the same amount. Be careful when spelling elif, which varies between languages that support a similar construct.
children_present = 1 # 1 = true, 0 = false
light_flashing = 0 # 1 = true, 0 = false
if children_present:
speed = 20
elif light_flashing:
speed = 20
else:
speed = 35
Another way to express the same logic:
if children_present or light_flashing:
speed = 20
else:
speed = 35
And yet another way:
speed = 35 # default speed
if children_present or light_flashing:
speed = 20 # condition fails, speed remains 35
while <condition>:
# uniformly indented statement(s)
The same rules apply for determining the limits of the compound while statement or compound for statement as the compound if above. Use break and continue to change the normal flow of a loop. Python does not have a "do while" or "do until" loop, therefore if you must always make at least one pass through the loop (for example, get user input, read at least one line of a file, etc.) the Python idiom is an infinite loop with a break statement.
while 1: # infinite loop
number = raw_input("Enter a number ('Q' to Quit): ")
# do something with the number ...
if number == 'Q' or number == 'q': # condition to end loop
break
In most cases the infinite loop can be redesigned such that the initial read (or what ever else needs to be done at least once) can be done outside the loop, then test a condition and decide whether or not to continue with the loop. Typically there will be some repeated code at the bottom of the loop, but note that the if statement has been removed, and therefore there is only one test.
number = raw_input("Enter a number ('Q' to Quit): ") # "prime" the loop
while not (number == 'q' or number == 'Q'):
# do something with the number ...
number = raw_input("Enter a number ('Q' to Quit): ") # get additional input
Note the parentheses surrounding the compound logical expression following the not keyword. not has higher precedence than ==, and we want it to apply to both equality conditions. Another way to express the same logic:
while number != 'q' and number != 'Q':
for <n> in <sequence>:
# uniformly indented statement(s)
The for loop is designed to iterate over every item in a sequence (string, list, tuple).
mylist = [1, 1, 2, 3, 5, 8, 13]
for i in mylist:
print i, # 1 1 2 3 5 8 13
The built-in range() function creates a list "on the fly" so we can construct a for loop similar to other languages where we loop for a predetermined number of iterations.
sum = 0
for i in range(1,11): # 10 iterations: 1, 2, ..., 9, 10
sum += i
range() takes 1, 2, or 3 arguments:
for i in range(10): # 10 iterations: 0, 1, 2, ..., 8, 9 for i in range(5, 10): # 5 iterations: 5, 6, 7, 8, 9 for i in range(0, 10, 2): # 5 iterations: 0, 2, 4, 6, 8