and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try
Statements
Is a unit of code that the Python interpreter can execute
2 types
print
assignment
Operators
Assignment
=
Addition / Concatenation
+
Subtraction
-
Multiplication
*
Exponentiation
**
Division (float)
/
Division (integer)
//
Modulus
%
Logical AND
and
Logical OR
or
Logical NOT
not
Test for presence of substring
in
Order of Operators
P - parentheses
E - exponentiation
M - Multiplication
D - Division
A - Addition
S - Subtraction
>>> first = '100'
>>> second = '150'
>>> print first + second
100150
String splicing
extract a segment or substring from a string
syntax:
stringvariable[n:m] - returns from the nth (inclusive) to the (m-1)th
stringvariable[:m] - return first m characters
stringvariable[n:] - return from nth to the last character
Return a formatted version of S, using substitutions from args and kwargs.
The substitutions are identified by braces ('{' and '}').
e.g. 1 x = int(input("Enter an integer: "))
y = int(input("Enter another integer: "))
sum = x+y
sentence = 'The sum of {} and {} is {}.'.format(x, y, sum)
print(sentence)
e.g. 2 - re-arranging the order of the arguments >>> print "{1} to {0}".format("front","back")
back to front
e.g. 3 align right
>>> '{:>10}'.format('test') test
e.g. 4 alight left
'{:10}'.format('test') test
e.g. 3 - left aligned suffixed with specific character
>>> print '{:_<10}'.format('test') test______
e.g. 4 - right aligned prefixed with specific character
>>> print '{:_>10}'.format('test') ______test
String validation methods :-
str.isalnum() - This method checks if all the characters of a string are alphanumeric (a-z, A-Z and 0-9).
# this is a comment
percentage = (minute * 100) / 60 # percentage of an hour
Boolean expression
evaluates to either true or false
x == y # x is equal to y
x != y # x is not equal to y
x > y # x is greater than y
x < y # x is less than y
x >= y # x is greater than or equal to y
x <= y # x is less than or equal to y
x is y # x is the same as y
x is not y # x is not the same as y
Conditional
if .. elif .. else ..
try .. except / else .. finally
>>> if x < 10:
... print 'Small'
if x%2 == 0 :
print 'x is even'
else :
print 'x is odd'
if x < y:
print 'x is less than y'
elif x > y:
print 'x is greater than y'
else:
print 'x and y are equal'
inp = raw_input('Enter Fahrenheit Temperature:')
try:
fahr = float(inp)
cel = (fahr - 32.0) * 5.0 / 9.0
print cel
except:
print 'Please enter a number'
>>> defdivide(x,y):... try:... result=x/y... exceptZeroDivisionError:... print"division by zero!"... else:... print"result is",result... finally:... print"executing finally clause"...>>> divide(2,1)result is 2executing finally clause>>> divide(2,0)division by zero!executing finally clause>>> divide("2","1")executing finally clauseTraceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in divideTypeError: unsupported operand type(s) for /: 'str' and 'str'
Try Except Finally
Starts with execution of the "try" block
if no error, skips the except block
if error. executes the "except" block
Lastly will always execute "finally" block is it is there
Common built in functions
max() - find largest item in the list
min() - find smallest item in the list
len() - get number of items in the argument, e.g. number of characters in a string
int() - converts the argument to an integer
float() - converts the argument to a floating point value
str() - converts the argument to a string
random() - returns a random floating point number between 0.0 and 1.0 (including 0.0 but not including 1.0)
random.randint(low,high) - returns a random integer between low and high
random.choice(list) - choose a random element from a sequence
math.log10() - log base 10
math.sin(radians) - sine of an angle in radians
math.cos(radians) - cosine of an angle in radians
math.sqrt() - square root
Defining a function
def print_helloworld():
print "Hello, World"
>>> print_helloworld()
Hello, World
Indefinite Iterations
iteration variables must be initialized before they are incremented in iterations
x = 0
...
x = x+1
while
n = 5
while n > 0:
print n
n = n -1
print "Done"
break
- to exist from infinite loops
while True:
line = raw_input('> ')
if line == 'done':
break
print line
print 'Done!'
continue
- skip to the next iteration without finishing body of the loop
while True:
line = raw_input('> ')
if line[0] == '#' :
continue
if line == 'done':
break
print line
print 'Done!'
Definite Iterations
for
fruits = ['apple','orange','grape']
for fruit in fruits:
print "I like",fruit
for number in [1,2,3,4,5]:
print 'Count: ',count
Example 1 - Finding maximum
largest = None
for itervar in [3, 41, 12, 9, 74, 15]:
if largest is None or itervar > largest :
largest = itervar
print 'Loop:', itervar, largest
print 'Largest:', largest
Example 2 - Finding minimum
smallest = None
for itervar in [3, 41, 12, 9, 74, 15]:
if smallest is None or itervar < smallest:
smallest = itervar
print 'Loop:', itervar, smallest
print 'Smallest:', smallest
User defined functions
(i) Defining and invoking function without any parameter
def f():
print('In function f')
print('When does this print?')
f()
(ii) Defining function with parameters
def sumProblem(x, y):
sum = x + y
sentence = 'The sum of {} and {} is {}.'.format(x, y, sum)
print(sentence)
(iii) Defining & invoking function with return values
def f(x):
return x*x
print(f(3))
print(f(3) + f(4))
(iv) Defining a function with a list parameter
def takes_list(a_list):
for item in a_list:
print item
map
maps each item in a list by applying the specified function
e.g.
print ''.join( map(str, range(1,10) ) )
range(1,10) generates a list of integers from 1 to 9
str is the function to apply each item in the list
map function returns a new list with each item converted by the str() function
print
Example 1, print mix of variables
print('The sum of', x, 'plus', y, 'is', x+y)
Example 2, print blank line
print()
Example 3, print with non-default separator
'''Hello to you! Illustrates sep with empty string in print. '''
person = input('Enter your name: ')
print('Hello ', person, '!', sep='')
Execute the string cmd in a shell with os.popen() and return a 2-tuple (status, output).
cmd is actually run as { cmd ; } 2>&1, so that the returned output will contain output
or error messages. A trailing newline is stripped from the output.
The exit status for the command can be interpreted according to the rules for the C
function wait().
commands.getoutput(cmd)
Like getstatusoutput(), except the exit status is ignored and the return value is a
string containing the command’s output.
e.g.
status,output = commands.getstatusoutput('ps -ww -f | grep cmdline_dev')
lines = output.split('\n')
for line in lines:
if 'IOR' in line:
break
Spliting strings
paragraph = " The quick brown fox\nJumped over the lazy dog"
lines = paragraph.split('\n')
for line in lines:
words = line.split()
for word in words:
print word + "\n"
Formatted print
Example 1 : without length or type format specifier