adapted from https://docs.python.org/3.4/tutorial/
There were incompatible changes between Python 2 and Python 3. Treat Python 2 and Python 3 as similar, but distinct, languages.
This tutorial will discuss Python 3. Specifically, Python 3.4, because that’s the latest version available on the CSU lab machines as of this writing (October 2015).
For backward compatibility, the default is Python 2.
Therefore, you have to execute python3 to get Python 3.
% python -V
Python 2.7.8
% python2 -V
Python 2.7.8
% python3 -V
Python 3.4.1
% ls -l /usr/bin/python
lrwxrwxrwx 1 root root 7 Jul 5 08:16 /usr/bin/python -> python2
The pydoc3 program tells you about functions:
% pydoc3 abs
Help on built-in function abs in module __builtin__:
abs(...)
abs(number) -> number
Return the absolute value of the argument.
pydoc3 can also tell you about control flow:
% pydoc3 for
The ``for`` statement
*********************
The ``for`` statement is used to iterate over the elements of a
sequence (such as a string, tuple or list) or other iterable object:
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
...
python3, with no arguments, starts in a “calculator” mode:
% python3 -q
>>> 2+2
4
>>> a=10
>>> from math import sqrt
>>> sqrt(a)
3.1622776601683795
>>> control-D to exit
%
The previous lines can be edited using the arrow keys.
To execute a single line of Python, use -c:
% python3 -c 'v=355/113; print(v)'
3.1415929203539825
A Python script starts with #! /usr/bin/python3:
% cat hi
#! /usr/bin/python3
print("Hello, world!")
% ./hi
Hello, world!
%
| Name | Examples | Notes |
|---|---|---|
| Boolean | True, False | capitalized |
| Number | 1, 3.4, 4.5e8, 2**1000 | big big big |
| String | "Don't" 'believe' r'every\thing' """you read!""" | immutable |
| List | [1,2.3,"fruit",[45,5]] | mutable |
| Tuple | (23, "skidoo") | immutable |
| Set | {1,2,3} | mutable |
| Dictionary | {"Jack":"CT320", "Chris":"CS160"} | mutable |
# Note lack of typing
val=42
val="hello there folks"
Δ=[val, 42]
Note the colon and lack of braces and then/fi
if a>100:
print("Holy Toledo, a is too big at", a)
a=100
b=a
Tabs are interpreted as every eight character positions. Changing the tab stops in your editor will not alter how Python interprets tab characters.
Wise Pythoners have their editor expand tabs to spaces, which avoids the whole problem.
if age<18:
print("You’re a punk")
elif age>=65:
print("You’re a geezer")
elif age==58:
print("You’re the ideal age")
else:
print("Whatever.")
This is as close as we get to a switch statement.
while a>=0:
print(a, end=" ")
a-=1 # No ++ or --
print("Blastoff!")
The for loop iterates over a list:
for p in [2,3,5,7,11,13,17,19]:
print(p)
Or anything else that’s iterable:
sum=0
for n in range(100):
sum+=n
print("The sum of 0..99 is", sum)
Though a real Pythoner will do this:
print("The sum of 0..99 is", sum(range(100)))
Sorry, C fans: no C-style for loop.
break: end this loop, as in C
continue: go to the next iteration, as in C
pass: do nothing—used when the syntax requires a statement
for n in range(2, 100):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n/x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
The indentation is correct: the else is associated with the
inner for, not the if! The else clause is executed
if the for loop ended “normally”, not via break.
def factorial(n):
if n<=1:
return n
else:
return n*factorial(n-1)
Also:
Ignoring modules, there are only two scopes: global and function local.
Variables that are only referenced inside a function are implicitly global.
If a variable is assigned a value anywhere within the function’s body,
it’s assumed to be a local unless explicitly declared as global.
Boolean operators: and, or, not
and and or are short-circuiting, and return the last value evaluated.
3 and 5 yields 5
9 or 0 yields 9
False or "hello" yields "hello"
Sorry, C fans: no &&, ||
+ - * / %
& | ^ ~ << >>
**
//
< > = <= >= != a<b<c)
Sorry, C fans: no ++ or --
"hi" * 3 yields "hihihi"
"foo" + "bar" yields "foobar"
"foo" "bar" yields "foobar", for adjacent string literals
'xyz' in 'Mxyzptlk' yields True
'x' not in 'Mxyzptlk' yields False
< > = <= >= !=
"%d/%d=%.3f" % (355,133,355/133)
del s[3] fails—immutable! Use: s=s[:3]+s[4:]
l += item
del l[3]
(1,2,3)+(3,1,99) yields (1,2,3,3,1,99)
(1,2,3)*2 yields (1,2,3,1,2,3)
(a,b) = (c,d)
s|r: union
s&r: intersection
s^r: symmetric difference (things in s or r, but not in both)
s-r: difference (things in s but not in r)
d[key] = value
del d[key]
key in d
Strings, lists, tuples, and sets are all sequences, with many methods.
for item in sequence:
item in sequence
item not in sequence
len(sequence)
sequence[i]
sequence[i:j] (including i, but not j)
sequence[i:] (i until the end)
sequence[:j] (up to but not including j)
max = 100
s = set(range(2,max))
for candidate in range(2,max):
s -= set(range(candidate*2, max, candidate))
print(s)
A variable holds a reference to an object. This code:
a=[1,2,3,4,5]
b=a
a[2] = 33
print(a)
print(b)
Produces this:
[1, 2, 33, 4, 5]
[1, 2, 33, 4, 5]
To make a copy, use b=a[:] or b=a.copy().
Long way:
squares = []
for x in range(10):
squares.append(x**2)
Short way:
squares = [x**2 for x in range(10)]
Multiple for loops and if statements are allowed.
print(value, …, sep=' ', end='\n', file=sys.stdout, flush=False)
Prints values, separated by sep, with end after all values, to file, with optional flushing.
print("hello")
print "hello"
Show nameserver lines in /etc/resolv.conf:
f = open('/etc/resolv.conf', 'r')
for line in f:
if "nameserver" in line:
print(line, end='')
f.close()
or:
with open('/etc/resolv.conf', 'r') as f:
for line in f:
if "nameserver" in line:
print(line, end='')
f.read(n): read up to n bytes
f.read(): read the rest of the file
f.readline()
f.write(string)
f.close()

try / finally
|
Modified: 2015-11-03T13:44 User: Guest Check: HTML CSSEdit History Source |
Apply to CSU |
Contact CSU |
Disclaimer |
Equal Opportunity Colorado State University, Fort Collins, CO 80523 USA © 2015 Colorado State University |
|