In [6]:
x = 5
y = 6
_sum = x+y # sum of 2 numbers
_mul = x*y # multiplication of 2 numbers
_div = float(x)/y # division of 2 numbers
_sub = x-y # subtraction of 2 numbers
# print formating in python
print 'sum = %s , mul = %s , div = %s and sub = %s' %(_sum, _mul, _div, _sub)
print 'Mathematical Operations over x and y are sum = {x} , mul = {y} , div = {z} and sub = {f}'.format(x = _sum, y = _mul, z = _div, f = _sub)
x +=5 # another way to do x = x+5
print 'sum = {f} , mul = {g} , div = {d} and sub = {s}'.format(f = _sum,g = _mul, d = _div ,s = _sub)
print 'sum is {s} where sum is {s} and sum is {s}'.format(s = _sum)
In [7]:
x = 'Hello '
y = 'World'
text = x+y # Concatenate multiple strings
print 'text is {x}'.format(x = text)
print 'length of string is: {x}'.format(x = len(text))
textUpper = text.upper() # convert charachters to upper case
textLower = text.lower() # convert charachters to lower case
print 'Upper case of text is: {x} '.format(x = textUpper)
print 'Lower case of text is: {x} '.format(x = textLower)
firstCharacter = text[0] # index the first character in the string
print 'First character of text is: {x} '.format(x = firstCharacter)
slicedText = text[1:7] # index a range of characters in a string
print 'Sliced text is: {x} '.format(x = slicedText)
replacedCharacter = text.replace(text[1],'f') # replace the second character with 'f'
print 'Replaced text is: {x} '.format(x = replacedCharacter)
In [8]:
mylist = [1,2,3,4,'Hello','C',4.5] # initalize a list
print 'my list is: {x}'.format(x = mylist)
removeLastElement = mylist.pop() # retrieve the last element in the list and then delete it from list
print 'my list after removing last element is: {x}'.format(x = mylist)
removeSpecificElement = mylist.pop(2) # retrieve the third element in the list and then delete it from list
print 'my list after removing element at index 2 is: {x}'.format(x = mylist)
mylist[0] = 'Hi' #replace element in a list
print 'my list after replacing element at index 0 is {x}'.format(x = mylist)
mylist.append(100) #Add element to a list
print 'my list after appending elements [1,2,3] is {x}'.format(x = mylist)
#slicing 1D list
slicedList = mylist[2:] # retrieve the charachters from the 3rd character to the end of the string
print 'my sliced list is: {x}'.format(x = slicedList)
#2D List
l1 = [1,2,5,9] # first row
l2 = [2,5,8,10] # second row
l3 = [10, 7, 5,11] # third row
matrix = [l1,l2,l3] # construct the 2D matrix
print 'My 2D matrix is: {x} '.format(x = matrix)
#Slicing 2D Matrix
secondRow = matrix[1] # retrieve the 2nd row in the matrix
print 'second row in matrix is: {x} '.format(x = secondRow)
firstColumn = [matrix[0][0], matrix[1][0],matrix[2][0]] # retrieve 1st column in the matrix
print 'first column in matrix is: {x}'.format(x = firstColumn)
# retrieve a selected sub-matrix out of the matrix
slicedMatrix = [[matrix[1][1], matrix[1][2]],[matrix[2][1],matrix[2][2]]]
print 'Sliced matrix is: {x}'.format(x = slicedMatrix)