Python

Our short knowledge bytes help you build skills on Python as Beginner to Expert

The Turtle module is a drawing tool for beginners that be used to draw shapes with python programs. It implements object-oriented programming. An instance of a ‘turtle’ object can be declared in a program and appears on the screen as an object with the default shape (a few other shapes can also be selected) of a little turtle on the screen. The object acts as the drawing head that traces its path as is moved around on the screen programmatically. It can be turned ‘right’ or ‘left’, move ‘forward’ or ‘backward’, etc. The distance to move is passed as the parameter to the method call. A ‘penup’ option prevents the turtle from tracing its path while moving. Moving the turtle programmatically can be used to draw interesting shapes and patterns.

The basic functions under the module are-

  • forward() 
  • backward() 
  • right()
  • left() 
  • pendown()
  • penup() 
  • pensize()
  • pen()
  • Color()

Given below is a simple program demonstrating the use of turtle module

import turtle           # importing the turtle module
wn = turtle.Screen()    # creates a graphical screen
turt = turtle.Turtle()  # create a turtle object named turtturt.color(“green”)
turt.forward(150)       # move turt forward by 150 units
turt.left(90)           # turn by 90 degrees
turt.forward(75)

The first line tells Python to load a module named turtle. We use the Turtle() and Screen() constructor functions to declare instances of a turtle object and a screen object. 

We have backward method, which is useful to make your turtle move in the backward direction. It is worth noting that turt.backward(-200) is same as turt.forward(200).

A turtle’s pen can be picked up or put down. This allows us to move a turtle to a different place without drawing a line. The methods are up and down.

The shape of turtle can be set by the shape method which takes name of shape as parameter. The allowed shapes which are- arrow, blank, circle, classic, square, triangle, turtle.

e.g.  turt.shape(“arrow”)

You can speed up or slow down the turtle’s animation speed. Speed can be set between 1  to 10. But if you set the speed to 0, it has a special meaning — turn off animation and go as fast as possible.

Eg. Turt.speed(5)

Use of loop in drawing turtle

Giving the forward() and left() commands for each step can be tedious, so it is better to use loop for drawing.

Below is a demonstration of the same

import turtle
scr = turtle.Screen()
turt = turtle.Turtle()
d= 50

for I in range(10):
    turt.forward(d)
    turt.left(90)
    d+=10

Data types are the categorization of data items representing the kind of value that tells what operations can be performed on a particular data.

Following are the standard or built-in data type of Python:

  • String
  • Number
  • Dictionary
  • List
  • Tuple

Strings In Python

Strings can be defined as sequential collections of characters. This means that the individual characters that make up a string are in a particular order from left to right. A string that contains no characters, often referred to as the empty string, is still considered to be a string. It is simply a sequence of zero characters and is represented by ‘’ or “” (two single or two double quotes with nothing in between).

Useful functions and methods of String-

MethodDescription
upperReturns a string in all uppercase
lowerReturns a string in all lowercase
countReturns the number of occurrences of item
indexReturns the leftmost index where the substring item is found and causes a runtime error if item is not found
stripReturns a string with the leading and trailing whitespace removed
replaceReplaces all occurrences of old substring with new

List In Python

list is a sequential collection of Python data values, where each value is identified by an index. The values that make up a list are called its elements. Lists are similar to strings, which are ordered collections of characters, except that the elements of a list can have any type and for any one list, the items can be of different types.

There are several ways to create a new list. The simplest is to enclose the elements in square brackets ( [ and ]).

Useful functions and methods of list-

MethodDescription
appendAdds a new item to the end of a list
insertInserts a new item at the position given
popRemoves and returns the last item
sortModifies a list to be sorted
reverseModifies a list to be in reverse order
indexReturns the position of first occurrence of item
countReturns the number of occurrences of item
removeRemoves the first occurrence of item

Tuples In Python

tuple, like a list, is a sequence of items of any type. The printed representation of a tuple is a comma-separated sequence of values, enclosed in parentheses. In other words, the representation is just like lists, except with parentheses () instead of square brackets [].

One way to create a tuple is to write an expression, enclosed in parentheses, that consists of multiple other expressions, separated by commas.

The key difference between lists and tuples is that a tuple is immutable, meaning that its contents can’t be changed after the tuple is created.

Useful functions and methods of Tuples-

MethodDescription
lenReturns the total length of the tuple
maxReturns the item from the tuple with the max value
minReturns the item from the tuple with the min value

Dictionaries In Python

Data can sometimes be organized more usefully by associating a key with the value we are looking for. A sort of direct look up of a value in Python is done with an object called a Dictionary. Dictionaries are a different kind of collection. They are Python’s built-in mapping type. A map is an unordered, associative collection. The association, or mapping, is from a key, which can be of any immutable type, to a value which can be any Python data object. 

Python has a set of built-in methods that you can use on dictionaries.

MethodDescription
clear()Removes all the elements from the dictionary
copy()Returns a copy of the dictionary
fromkeys()Returns a dictionary with the specified keys and value
get()Returns the value of the specified key
items()Returns a list containing a tuple for each key value pair
keys()Returns a list containing the dictionary’s keys
pop()Removes the element with the specified key
popitem()Removes the last inserted key-value pair
setdefault()Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
update()Updates the dictionary with the specified key-value pairs
values()Returns a list of all the values in the dictionary

A file is some information or data which stays in the computer storage devices. Different kinds of files are music files, video files, text files. Python gives you easy ways to manipulate these files. The Python programs that you write are stored as text files. We can create these files in any of a number of ways. For example, we could use a text editor to type in and save the data. We could also download the data from a website and then save it in a file. Regardless of how the file is created, Python will allow us to manipulate the contents.In Python, we must open files before we can use them and close them when we are done with them. As you might expect, once a file is opened it becomes a Python object just like all other data.Data files can be stored in two ways- Text and Binary

The functions and methods that can be used to open and close files are-


r

Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
rb
Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.
r+
Opens a file for both reading and writing. The file pointer placed at the beginning of the file.
rb+
Opens a file for both reading and writing in binary format. The file pointer placed at the beginning of the file.
w
Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
wb
Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
w+
Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
wb+
Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.
a
Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
ab
Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.
a+
Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.
ab+
Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

Using A Text File

Once you have a file “object”, the thing returned by the open function, Python provides three methods to read data from that object. The read() method returns the entire contents of the file as a single string (or just some characters if you provide a number as an input parameter. The readlines method returns the entire contents of the entire file as a list of strings, where each item in the list is one line of the file. The readline method reads one line from the file and returns it as a string. The strings returned by readlines or readline will contain the newline character at the end.

MethodExplanation
write()Add a string to the end of the file. filevar must refer to a file that has been opened for writing.
read(n)Read and return a string of n characters, or the entire file as a single string if n is not provided.
readline(n)Read and return the next line of the file with all text up to and including the newline character. If n is provided as a parameter, then only n characters will be returned if the line is longer than n. Note the parameter n is not supported in the browser version of Python, and in fact is rarely used in practice, you can safely ignore it.
readlines(n)Returns a list of strings, each representing a single line of the file. If n is not provided then all lines of the file are returned. If n is provided then n characters are read but n is rounded up so that an entire line is returned. Note Like readline readlines ignores the parameter n in the browser.

Using A Binary File

Inserting/Appending a record in a binary file Inserting or appending a record into a binary file requires importing pickle module into your program followed by dump() method to write onto the file.

Basic syntax of inserting a record in the binary file-

import pickle
fh=open([file name enclosed in “”],[method of execution in ‘’])
pickle.dump([record to insert],fh)

Reading the contents from binary file student uses load() method of pickle module. It is used to read the object from the opened file. The syntax for this is given by the statement—    

object = pickle.load(file)

Once the contents are read, it gets stored inside the object.

Random Access In Files Using TELL() And SEEK()

seek()

seek() function is used to change the position of the file handle (file pointer) to a given specific position. File pointer is like a cursor, which defines from where the data has to be read or written in the file. Python file method seek() sets the file’s current position at the offset. This argument is optional and defaults to 0, which means absolute file positioning. Other values are: 1, which signifies seek is relative (may change) to the current position, and 2, which means seek is relative to the end of file. There is no return value. The reference point is defined by the “from_what” argument. It can have any of the three values: 0: sets the reference point at the beginning of the file, which is by default. 1: sets the reference point at the current file position. 2: sets the reference point at the end of the file. seek() can be done in two ways:

• Absolute Positioning

• Relative Positioning

Absolute referencing using seek() gives the file number on which the file pointer has to position itself. The syntax for seek() is:   

f.seek(file_location)  #where f is the file pointer

tell()

tell() returns the current position of the file read/write pointer within the file.

The syntax for tell() is :

f.tell()      #where f is file pointer

When you open a file in reading/writing mode, the file pointer rests at 0th byte. When you open a file in append mode, the file pointer rests at the last byte.

Using a CSV file

CSV is a simple flat file in a human readable format which is extensively used to store tabular data, in a spreadsheet or database. A CSV file stores tabular data (numbers and text) in plain text.

Files in the CSV format can be imported to and exported from programs that store data in tables, such as Microsoft Excel or OpenOffice Calc. CSV stands for “comma separated values”. Thus, we can say that a comma separated file is a delimited text file that uses a comma to separate values. Each record consists of fields separated by commas (delimiter). Each line of the file is called a record. Thus, CSV organizes data into a structured form and, hence, the proper and systematic organization of this large amount of data is done by CSV. Since CSV file formats are of plain text format, it makes it very easy for website developers to create applications that implement CSV.

Reading from a CSV file is done using the reader object. The CSV file is opened as a text file with Python’s built-in open() function, which returns a file object. This creates a special type of object to access the CSV file (reader object), using the reader() function. The reader object is an iterable that gives us access to each line of the CSV file as a list of fields. File methods for reading are – readreadline, and readlines, which simply iterate over the file object itself – will work on CSV files. You can also use next() directly on it to read the next line of the CSV file, or you can treat it like a list in a for loop to read all the lines of the file (as lists of the file’s fields).

To write to a CSV file in Python, we can use the csv.writer() function. The csv.writer() function returns a writer object that converts the user’s data into a delimited string. This string can later be used to write into CSV files using the writerow() function. In order to write to a CSV file, we create a special type of object to write to the CSV file “writer object”, which is defined in the CSV module, and which we create using the writer() function. The writerow() method allows us to write a list of fields to the file. The fields can be strings or numbers or both. Also, while using writerow(), you do not need to add a new line character

In Python, a function is a chunk of code that performs some operation that is meaningful for a person to think about as a whole unit. The syntax for creating a named function, a function definition, is:

def name( parameters ):
    statements

You can use any names you want for the functions you create, except that you cannot use a name that is a Python keyword, and the names must follow the rules for legal identifiers. The parameters specify what information, if any, you have to provide in order to use the new function. Another way to say this is that the parameters specify what the function needs to do its work. There can be any number of statements inside the function, but they have to be indented from the def.

In a function definition, the keyword in the header is def, which is followed by the name of the function and some parameter names enclosed in parentheses. The parameter list may be empty, or it may contain any number of parameters separated from one another by commas. In either case, the parentheses are required.

  1. A header line which begins with a keyword and ends with a colon.
  2. A body consisting of one or more Python statements, each indented with 4 spaces, the Python standard.

Function Invocation

Defining a new function does not make the function run. To execute the function, we need a function call. This is also known as a function invocation.

The way to invoke a function is to refer to it by name, followed by parentheses

Function Parameters

With parameters, functions are even more powerful, because they can do pretty much the same thing on each invocation, but not exactly the same thing. The parameters can cause them to do a little different each time. A function needs certain information to do its work. These values, often called arguments or actual parameters or parameter values, are passed to the function by the user.

When a function has one or more parameters, the names of the parameters appear in the function definition, and the values to assign to those parameters appear inside the parentheses of the function invocation.

In the definition, the parameter list is sometimes referred to as the formal parameters or parameter names. These names can be any valid variable name. If there is more than one, they are separated by commas.

In the function invocation, inside the parentheses one value should be provided for each of the parameter names. These values are separated by commas. The values can be specified either directly, or by any python expression including a reference to some other variable name.

Function that return some value

Functions that return values are sometimes called fruitful functions. The return statement is followed by an expression which is evaluated. There is one more aspect of function return values that should be noted. All Python functions return the special value None unless there is an explicit return statement with a value other than None

def double(n):
     return n*2
num=int(input())
print(double(num))

Python is an object oriented programming language. A Class is like a “blueprint” for creating objects.

To create a class, use the keyword class:

class MyTestClass:
  a = 1

Now we can use the class named MyTestClass to create objects. Create an object named obj, and print the value of a:

obj = MyTestClass()
print(obj.a)

The __init__() Function

To understand the meaning of classes it is important to understand the built-in function  __init__().

All classes have a function called __init__(), which is always executed when the class is being initiated. The __init__() function is called automatically every time the class is being used to create a new object.

Create a class named Person, use the __init__() function to assign values for name and age:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

obj = Person("John", 36)

print(obj.name)
print(obj.age)

Object Methods

Objects can also contain methods. Methods in objects are functions that belong to the object.

Let us create a method in the Person class. Insert a function that prints a greeting, and execute it on the p1 object:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

  def myfunc(self):
    print("Hello my name is " + self.name)

p1 = Person("John", 36)
p1.myfunc()

Modify Object Properties

You can modify properties on objects like this:

p1.age = 40

Delete Object Properties

You can delete properties on objects by using the del keyword:

del p1.age

Delete Objects

You can delete objects by using the del keyword:

del p1

NumPy stands for Numerical Python. NumPy is a Python library used for working with arrays. It also has functions for working with linear algebra, fourier transformation, and matrices.

NumPy aims to provide an array object which is 50 times faster than the traditional Python lists.

The array object in NumPy called ndarray, provides supporting functions that make working with ndarray very easy. Arrays are also very frequently used in data science, where speed and resources are important.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

Create a NumPy ndarray Object

NumPy is used to work with arrays. The array object in NumPy is called ndarray.

We can create a NumPy ndarray object by using the array() function.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr)

print(type(arr))

To create an ndarray, we can pass a list, tuple or any array-like object into the array() method, and it will be converted into an ndarray:

import numpy as np

arr = np.array((1, 2, 3, 4, 5))

print(arr)

NumPy Array Dimension

An array can have any number of dimensions. When the array is created, you can define the number of dimensions by using the ndmin argument.

import numpy as np

arr = np.array([1, 2, 3, 4], ndmin=5)

print(arr)
print('number of dimensions :', arr.ndim)

In this array the innermost dimension (5th dim) has 4 elements, the 4th dim has 1 element that is the vector, the 3rd dim has 1 element that is the matrix with the vector, the 2nd dim has 1 element that is 3D array and 1st dim has 1 element that is a 4D array.

NumPy Array Indexing

You can access an array element by referring to its index number. The indexes in NumPy arrays start with 0, meaning that the first element has index 0, and the second has index 1 etc.

Get third and fourth elements from the following array and add them.

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr[2] + arr[3])

Negative indexing can be used to access an array from the end.

import numpy as np

arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])

print('Last element from 2nd dim: ', arr[1, -1])

NumPy Array Slicing

Slicing in python means taking elements from one given index to another given index.

We pass slice instead of index like : [start:end].

We can also define the step, like : [start:end:step].

If we don’t pass start its considered 0

If we don’t pass end its considered length of array in that dimension

If we don’t pass step its considered 1

# Slice elements from index 1 to index 5

import numpy as np

arr = np.array([1, 2, 3, 4, 5, 6, 7])

print(arr[1:5])


# Slice elements from index 4 to the end of the array

print(arr[4:])


# Slice from the index 3 from the end to index 1 from the end:

print(arr[-3:-1])


# Return every other element from index 1 to index 5:

print(arr[1:5:2])


## Slicing 2-D Arrays

# From the second element, slice elements from index 1 to index 4 (not included):

arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])

print(arr[1, 1:4])

Data Types in NumPy

NumPy has some extra data types, and refer to data types with one character, like i for integers, u for unsigned integers etc. Below is a list of all data types in NumPy and the characters used to represent them.

  • i – integer
  • b – boolean
  • u – unsigned integer
  • f – float
  • c – complex float
  • m – timedelta
  • M – datetime
  • O – object
  • S – string
  • U – unicode string
  • V – fixed chunk of memory for other type ( void )

Checking the Data Type of an Array

The NumPy array object has a property called dtype that returns the data type of the array:

# Get the data type of an array object:

import numpy as np

arr = np.array([1, 2, 3, 4])

print(arr.dtype)

We use the array() function to create arrays, this function can take an optional argument: dtype that allows us to define the expected data type of the array elements:

import numpy as np

arr = np.array([1, 2, 3, 4], dtype='S')

print(arr)
print(arr.dtype)

Numpy Array Search

You can search an array for a certain value, and return the indexes that get a match. To search an array, use the where() method.

# Find the indexes where the value is 4:


import numpy as np

arr = np.array([1, 2, 3, 4, 5, 4, 4])

x = np.where(arr == 4)

print(x)

The example above will return a tuple: (array([3, 5, 6],). Which means that the value 4 is present at index 3, 5, and 6.

Search Sorted

There is a method called searchsorted() which performs a binary search in the array, and returns the index where the specified value would be inserted to maintain the search order.

import numpy as np

arr = np.array([6, 7, 8, 9])

x = np.searchsorted(arr, 7)

print(x)

The number 7 should be inserted on index 1 to remain the sort order. The method starts the search from the left and returns the first index where the number 7 is no longer larger than the next value.

Python provides built-in functions map(), filter(), and zip() work to make you more efficient with processing data in Python !

Map

Python’s map() function is used to apply a function on all elements of a specified iterable and return a map object.

map() will take 2 required positional arguments.

  1. A function to run against iterables
  2. An iterable (ie. list)

map(func, [...])

The expected output of this would be a map object with a memory position.

Lets take an example that applies the function square() to a list of integers which returns a list of squared numbers from our original list.

def square(number):
    return number*number

Writing the code without using map()

def square(number):
    return number*number

numbers = [1,2,3,4,5]
squared_numbers = []

for number in numbers:
    squared = square(number)
    squared_numbers.append(squared)

Writing the code using map()

def square(number):
    return number*number

numbers = [1,2,3,4,5]
squared_numbers = map(square, numbers)

Filter

Python’s filter() function checks a condition of each element in an iterable and returns a filtered data structure only containing elements who match the given conditions.

filter() will take 2 required positional arguments.

1. A function to run against iterables.

2. An iterable (ie. list).

filter(func, [...])

The function passed to filter() must return a boolean (True or False)

The expected output of this would be a filter object with a memory position.

Lets take an example that applies the function even() to a list of integers. The objective here is to get a list that only contains even numbers.

def odd(number):
    if (number  % 2) != 0:
        return True
    return False

Writing code without using filter()

def odd(number):
    if (number % 2) != 0:
        return True
    return False

numbers = [1,2,3,4,5]

odd_numbers = []
for number in numbers:
    if odd(number):
        odd_numbers.append(number)

Writing code with filter()

def odd(number):
    if (number % 2) != 0:
        return True
    return False

numbers = [1,2,3,4,5]
odd_numbers = filter(odd, numbers)

Zip

Python’s zip() function combines elements of 2 lists with matching indexes into an interable of tuples.

zip() will take an undefined number of arguments where each argument is an iterable to zip.

zip([...], [...], [...], ...)

The expected output of this would be a zip object containing tuples of the same-index element of each iterable with a memory position..

Let’s take the above 2 examples combined to create a list of even numbers with their respective squared results.

def even(number):
    if (number % 2) == 0:
        return  True
    return  False

def square(number):
    return number*number

numbers = [1,2,3,4,5]
even_numbers = filter(even, numbers)
even_numbers_squared = map(square, even_numbers)

Writing code without zip()

...
even_numbers = [2,4]
even_numbers_squared = [4, 8]
combined = []
even_numbers_index = 0
for number  in even_numbers:
    squared = even_numbers_squared[even_numbers_index]
    squared_tuple = (number, squared)
    combined.append(squared_tuple)

Writing code with zip()

...
even_numbers = [2,4]
even_numbers_squared = [4, 8]
zipped_result = zip(even_numbers, even_numbers_squared)

Using zip() we can combine values with matching indexes from multiple lists without creating a buffer list or iterating with a for loop.