Python is a high-level, dynamically typed programming language used extensively in Digital technologies. It is used from rapid prototyping to industrial-grade enterprise applications. Below we will learn about the basics of the language. In this classroom, we will use Python version 3 as Python version 2 is now discontinued. Lets look at this video to get the basic understanding for of Python
from IPython.display import YouTubeVideo
YouTubeVideo('28-oixCfK9c', width=860, height=460)
Like other programming languages, python also provides basic data structures like integers, floats, booleans, and strings. Integers and floats work same as in other languages, but don't have unary ++ or -- operator. Booleans use 'True' and 'False' to denote the bool type, these variables can be evaluated using and, or, not. Strings in python provide a lot of functionality as we see in the below examples.
#initailizing variable
num = 5
num_f = 6.5
print(num)
print(type(num))
print(num_f)
print(type(num_f))
# Operations
print(num+2)
print(num-2)
print(num+num_f)
print (num/2)
print (num*2)
print (num**2)
# Shortcuts
num += 3
print (num)
# Booleans
t, f = True, False
print (type(t))
print (t or f)
print (t and f)
# Strings
d = ' digital '
t = 'technology'
# String concatenation
print (d+' '+t)
# String Methods
print ('{0} {1}'.format(d,t))
print (d.capitalize())
print (d.upper())
print (d.replace('d','g'))
print (d.strip())
Apart from the basic data types, python provides containers to use and manipulate the basic data types with ease. These containers are built in the core of the language and don't need explicit libraries to work with. Python also supports a concept of iteration over containers using generators. Let's discuss each of these topics in detail.
Lists in python is an ordered, mutable collection of objects. You can think of lists as an array with additional functionalities. These additional functionalities include list slicing, resizing, looping and list comprehensions. Lists are created using square brackets, i.e. []. Let's explore more about Lists in the cell below.
# Lists
pt = [3, 6, 9]
print (type(pt))
print (pt, pt[2])
pt[2] = 'digital'
print (pt)
pt.append('Technologies')
print (pt)
# List Slicing
pt = list(range(7))
print (pt)
print(pt[2:5])
print(pt[-1])
print (pt [:4])
print (pt[3:])
# List loops
pt = list (range(7))
print (pt)
for value in pt:
print (value**2)
#List comprehension
pt = list (range(7))
sqrt = [x**2 for x in pt ]
print(sqrt)
Dictionaries in python is a unordered set of key-value pairs. It is indexed by keys, which can be any immutable type. You can think of dictionaries as an “associative array”. Dictionaries are created using braces, i.e. {}. Similar to list, it provides additional functionalities include dictionary slicing, resizing, looping and dict comprehensions. Let's explore more about Dictionaries in the cell below.
# Dictionaries
val = {'sky':'blue','grass':'green','flower':'red'}
print (val)
print(val['sky'])
for k, v in val.items():
print ('{0} is {1}'.format(k,v))
A set is an unordered unique collection of objects. Unlike lists or tuples, a set cannot have multiple occurrences of the same element. You can create a set using set() command. Let's explore more about sets in the cell below.
# Sets
vehicle = {'car','truck','bikes'}
print(vehicle)
vehicle.add('scooter')
print(vehicle)
vehicle.remove('car')
print(vehicle)
for i in vehicle:
print(i)
Tuples are similar to lists but are not mutable. Tuples are faster and smaller than a list. One key feature of a tuple is that unlike lists, it can be used as a key in dictionaries and as elements of sets. A tuple can be created with an () or with the tuple() builtin function. Let's explore more about sets in the cell below.
# Tuples
t = (1,3)
print (type(t))
for i in t:
print (i)
# Dict comprehension with tuples
dt = {(x,x**2): x for x in range(10)}
print (dt)
Functions help abstract the functionality into a module. Functions make the program more organized, modular and manageable as it grows in size. Functions in python are created using def Keyword. Let's explore functions in the cell below.
def mult(a, b):
return(a*b)
def add(a,b):
return(a+b)
print (mult(2,4))
print (add(3,5))
Like in other Object-oriented languages, classes in python provide a mechanism of encapsulating variables and functions and serve as a blueprint for the objects. In python, a class is created by the keyword class. Let's explore classes in the cell below.
# Classes
class hello:
def __init__(self, name):
self.name = name
def greet(self):
print ("Hello {0} to the class".format(self.name))
h = hello('learner')
h.greet()
from IPython.display import YouTubeVideo
YouTubeVideo('cZGGtxUTNIg', width=860, height=460)
Arrays and matrices are used in processing data in scientific, and statistical programming used in machine learning, computer vision and other digital technologies. NumPy provides a high-performance multidimensional array object and tools for working with these arrays. NumPy library will be very useful in our next tutorials on linear algebra.
# Numpy
import numpy as np
mt1 = np.array([2,3,4])
print (mt1)
print (mt1.shape)
# Other ways
mt2 = np.zeros((2,2))
print (mt2)
mt3 = np.ones((2,2))
print (mt3)
mt4 = np.full((2,2),8)
print (mt4)
import numpy as np
arr1 = np.full((2,2), 4)
arr2 = np.full((2,2), 3)
print(np.add(arr1, arr2))
print(np.subtract(arr1,arr2))
print(np.multiply(arr1,arr2))
print(np.divide(arr1,arr2))
arr = np.array(([1,2,3],[4,5,6],[7,8,9]))
row_1 = arr[1,:]
row_2 = arr[1:2,:]
print (row_1, row_1.shape)
print (row_2, row_2.shape)
col_1 = arr[:,1]
col_2 = arr[:,1:2]
print (col_1, col_1.shape)
print (col_2, col_2.shape)
Matplotlib is a python library for creating static, animated, and interactive visualizations in Python. Matplotlib is very useful in visualization of data in the digital world. Below we will explore matplotlib plot function, which allows you to plot 2D data.
import numpy as np
import matplotlib.pyplot as plt
year = [2011,2012,2013,2014,2015,2016]
goog = [10,14,15,16,18,33]
appl = [5,6,8,10,17,21]
plt.plot(year,goog,
year,appl)
plt.xlabel("Year")
plt.ylabel("Shares")
plt.show()
On the same plot, we can use subplot to plot different functions. We can use add_subplot to create multiple plots in the same figure. In add_subplot "111" means "1x1 grid, first subplot" and "334" means "3x3 grid, 4th subplot".
fig = plt.figure(1, figsize=(15,4))
chart1 = fig.add_subplot(122)
chart2 = fig.add_subplot(121)
chart1.plot(year, appl)
chart2.plot(year,goog)
def housingData():
"""
Accept area and cost
"""
housingData()
def housingData():
"""
Accept area and cost
"""
def calculateTotalArea():
"""
Calculate total area and cost
"""
housingData()
calculateTotalArea()
def housingData():
"""
Accept area and cost
"""
def calculateTotalArea():
"""
Calculate total area and cost
"""
def plotData():
"""
Plot the data for the 2D Values
"""
housingData()
calculateTotalArea()
plotData()