Scripting >> Python >> Cheatsheet >> Python 2 quick reference

 

 

Variables

Assigning values to variables

>>> message = 'And now for something completely different'
>>> n = 17
>>> pi = 3.1415926535897931

variables must be initialized with some value before they can be updated e.g. to increment an integer value
x = 0
x = x +1

Variable Types
  • int
  • str
  • bool
  • float

To obtain variable types

>>> type(message)
<type 'str'>
>>> type(n)
<type 'int'>
>>> type(pi)
<type 'float'>

 

Variable Display >>> print n
17
>>> print pi
3.14159265359
Variable naming rules
  • can contain both letters and numbers
  • cannot start with a number
  • can include underscore (_)
  • cannot use python keywords e.g. class
  • cannot include @
Python keywords 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

Modulus operator

use the % sign

>>> quotient = 7 / 3
>>> print quotient
2
>>> remainder = 7 % 3
>>>

String concatenation operator

Use + sign

>>> 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

 

>>> s = 'Monty Python'
>>> print s[0:5]
Monty
>>> print s[6:12]
Python

 

String methods

List the available methods for a string variable by using dir() function

>>> var = "Hello"
>>> dir(var)
['capitalize', 'center', 'count', 'decode', 'encode',
'endswith', 'expandtabs', 'find', 'format', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace',
'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'partition', 'replace', 'rfind', 'rindex', 'rjust',
'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']

get help on the method by

>>> help(str.method)

capitalize

>>> help(str.capitalize)
capitalize(...)
S.capitalize() -> string
Return a copy of the string S with only its first character
capitalized

format

>>> help(str.format)
format(...)
    S.format(*args, **kwargs) -> string

    Return a formatted version of S, using substitutions from args and kwargs.
    The substitutions are identified by braces ('{' and '}').
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)   

 

swapcase

>>> help(str.swapcase)
swapcase(...)
S.swapcase() -> string

Return a copy of the string S with uppercase characters
converted to lowercase and vice versa.

e.g.
>>> S = First
>>> print S.swapcase()
fIRST

 

.

format

>>> help(str.format)
format(...)
    S.format(*args, **kwargs) -> string

    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).

>>> print 'ab123'.isalnum()
True
>>> print 'ab123#'.isalnum()
False

str.isalpha()
- This method checks if all the characters of a string are alphabetical (a-z and A-Z).

>>> print 'abcD'.isalpha()
True
>>> print 'abcd1'.isalpha()
False

str.isdigit()
- This method checks if all the characters of a string are digits (0-9).

>>> print '1234'.isdigit()
True
>>> print '123edsd'.isdigit()
False

str.islower()
- This method checks if all the characters of a string are lowercase characters (a-z).

>>> print 'abcd123#'.islower()
True
>>> print 'Abcd123#'.islower()
False

str.isupper()
- This method checks if all the characters of a string are uppercase characters (A-Z).

>>> print 'ABCD123#'.isupper()
True
>>> print 'Abcd123#'.isupper()
False
 

Refer to https://pyformat.info/ for more examples

str.ljust(width)

This method returns a left aligned string of length width.

>>> width = 20
>>> print 'abcdefghij'.ljust(width,'-')
abcdefghij----------  

str.center(width)

This method returns a centered string of length width.

>>> width = 20
>>> print 'abcdefghij'.center(width,'-')
-----abcdefghij-----

str.rjust(width)

This method returns a right aligned string of length width.

>>> width = 20
>>> print 'abcdefghij'.rjust(width,'-')
----------abcdefghij



 

 

String escape codes
For this Use this Setting x to: Printing x will yield:
' \' 'Don\'t do that' Don't do that
" \" "She said \"hi\"" She said "hi"
\ \ "Backslash: \" Backslash: \
[newline] \n "1\n2" 1
2
[carriage return] \r "1\r2" 2 overwrites the 1
[horizontal tab] \t "1\t2" 1 2
[backspace] \b "12\b3" 13
[16 bit unicode] \uxxxx "Katakana a: \u30A1" Katakana a: ァ
[32 bit unicode] \Uxxxxxxxx "Katakana a: \u000030A1" Katakana a: ァ
User Input Function

Example 1

>>> input = raw_input()
Some silly stuff
>>> print input
Some silly stuff

Example 2

>>> name = raw_input('What is your name?\n')
What is your name?
Chuck
>>> print name
Chuck

Variable type conversions

String to Integer : use int() 

>>> speed = "10"
>>> newspeed = int(speed) + 5
>>> print newspeed
15
 

Comments

Prefix with #

# 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'

>>> def divide(x, y):
...     try:
...         result = x / y
...     except ZeroDivisionError:
...         print "division by zero!"
...     else:
...         print "result is", result
...     finally:
...         print "executing finally clause"
...
>>> divide(2, 1)
result is 2
executing finally clause
>>> divide(2, 0)
division by zero!
executing finally clause
>>> divide("2", "1")
executing finally clause
Traceback (most recent call last):   File "<stdin>", line 1, in ?   File "<stdin>", line 3, in divide
TypeError: 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='')
Data Types

 

Type Initialize by Characteristics Operations
List L1=[]
L2=[1,2,3]
L3=["one","two"]
  • sequence of objects
  • objects can be changed
  • use []
  • x in L ..... True if x is an item in L
  • x not in L . False if x is an item in L
  • L1 + L2 .... Concatenate the 2 lists
  • L*n ........ add L into itself n times
  • L[i] ....... ith item of L, origin 0
  • L[i:j] ..... slice from i to j
  • L[i:j:k] ... slice from i to j step k
  • len(L) ..... lenth of L
  • min(L) ..... smallest item in L
  • max(L) ..... largest item in L
  • L.index(x) . index of first occurrence
                                  of x in L
  • L.count(x) . total number of occurrence
                 of x in L
Tuple T1=()
T2=(1,2,3)
T3=("one","two")
  • sequence of objects
  • Immutable i.e. objects cannot be changed
  • use ()
 
List manipulation See here
Modules

List modules

>>> help()
help> modules

Search
- from command line

pip search packagename

Install
- from command line

pip install numpy

 

Capture output from OS/shell command to variable  commands.getstatusoutput(cmd)

   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

python 2.6

>>> print "{0} + {1} = {2}".format('1','2','3')
1 + 2 = 3

python 2.7

>>> print "{0} + {1} = {2}".format('1','2','3')
1 + 2 = 3

or

>>> print "{} + {} = {}".format('1','2','3')
1 + 2 = 3

 
Example 2: with length and type format specifier

python 2.6

>>> print "{0:02d} + {1:02d} = {2:02d}".format(1,2,3)
01 + 02 = 03
 

python 2.7

>>> print "{0:02d} + {1:02d} = {2:02d}".format(1,2,3)
01 + 02 = 03

or

>>> print "{:02d} + {:02d} = {:02d}".format(1,2,3)
01 + 02 = 03