Exercise 2 : Python Basics

Output to terminals

  • print “hello world”
  • print 1+1

Variables

  • integer, strings, float
  • convert integer to strings and vice versa
    • str(5)
    • int(age)
  • 5/3 = 1.6666(float) or 1(int)
  • calculate the string length len()

Declaration (Comments)

  • # comments out a line of code
  • “”“ paragraph ”“” comments out one or more lines of code

Statement

  • age = 10
  • print age

Keywords

The following is a list of keywords for the Python programming language.

and del from not while
aselifglobalorwith
assertelseif passyield
breakexceptimportprintclass
exec inraisecontinuefinally
isreturndefforlambda
try
 import keyword
 print "Python keywords: ", keyword.kwlist

Operators

SymbolTypeWhat it Does
+ MathematicalAddition
- MathematicalSubtraction
* MathematicalMultiplication
/ MathematicalDivision
% ModulosReturns the remainder from a division
& LogicalAnd
pipeLogicalOr
«ShiftLeft Shift
»ShiftRight Shift
~LogicalBitwise Negation
<ComparisonLess than
>ComparisonGreater than
==ComparisonEqual to
!=ComparisonNot Equal To
>=ComparisonGreater than or Equal To
ComparisonLess than or Equal To
=AssignmentAssigns a value
+=AssignmentAdds and assigns a value
-=AssignmentSubtracts and Assigns a value
*=AssignmentMultiplies and assigns a value
/=AssignmentDivides and assigns a value
%=AssignmentModulus and assigns
»AssignmentShifts and assigns
«AssignmentShifts and assigns
AndBoolean
OrBoolean
NotBoolean

other operators are

TruncatingDivision                   [//]
Mathematical Powers                  [**]
Bitwise XOR                          [^]
Truncate Divides and assigns a value [//=]
Powers and assigns                   [**=]

Functions() and importing

def increment(x):
  return x+1
  
import math
  math.sqrt(4)
  

Always remember the flow of execution - the identation

Conditions and Recursions

  • Boolean & logical expressions
    • 26 == 26
    • True
    • !=, >, <; >=, ⇐, %, and, …
  • Alternative executions
    • if, else, elif,
    • Nested layers
  • return, continue

Iterations/loops

  • while n > 20:
  • for i in range(0, 20):
  • for char in fruit:
  while i < n:
      print txt
      
  for x in range(0,20):
       print x*x
  fruit = "Banana"
  for char in fruit:
      print char
      

Nested loops

  for x in xrange(1,11):
  for y in xrange(1,11):
      print '%d * %d = %d' % (x,y,x*y)

Early exit

  for x in xrange(3):
  if x==1:
      break

For..Else

  for x in xrange(3):
      print x
  else:
      print 'Final x = %d' % (x)

Strings as an iterable

  string = "Hello World"
  for x in string:
      print x

Lists as an iterable

  collection = ['hey',5,'d']
  for x in collection:
      print x
      

Lists of lists

 list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
 for list in list_of_lists:
    for x in list:
        print x

Creating your own iterable

  class Iterable(object):
     def __init__(self,values):
        self.values = values
        self.location = 0
     def __iter__(self):
        return self
     def next(self):
        if self.location == len(self.values):
            raise StopIteration
        value = self.values[self.location]
        self.location += 1
        return value

Classes

  • Class Area:
    • def square_area(w, h):
    • area = w*h
    • return area
  • import Area()
  • ar = Area.Area()
  • print ar.squre_area(20, 20)

Other

Lot more stuffs can be explored and you have a vast internet.

Tutorial

Download this Exercise 2 Code Skeleton and follow the class tutorial.

solution to the skeleton: Exercise2_Solution

Important sources and references