Python
Chapter summary - Unit 1
- Unit 1
Python Fundamentals:
An Introduction to Python programming: Introduction to Python, IDLE to develop programs;
How to write your first programs: Basic coding skills, data types and variables, numeric data, string data, five of the Python functions;
Control statements: Boolean expressions, selection structure, iteration structure;
Define and use Functions and Modules: define and use functions, more skills for defining and using functions and modules, create and use modules, standard modules
Contents
- What is python?
Python is a high level interpreted language that is preffered in rapid development of programs due to it’s easy and simple syntax. - IDLE
IDLE is the short form of integrated development learning environment. - Data types in python
int(5), string(’this is a string’ or this is a string), tuple( (5,3,5) ), float(5.3), bool(true/false) … - Python interation structure
Unlike other languages python uses indententation instead of using brackets.
Comments
Comments are a piece of code that is essentially “dead code” these are essential to show the programmer what the code does and not to do anything.
Comments in python -
|
|
Basic IO in python
- Printing a statement \
|
|
Putting another variable in the output message
|
|
- Concatenation Concatenation is the process of joining two or more strings. Concatenation can be done in python by the following way.
Here we have added a space to seperate the hello and the world.
- Getting input by a python statement
- fstrings
fstrings make it easier for the user to shove in multiple variables in the same print statement.
Function chaining, taking numerical inputs and type casting
Inputs in python can be easily be obtained from the input command, however this command only provides the data to the interpretor as a string to the variable. To change the datatype for the variable we have to use explicit type casting.
This will give the output as an integer since we have used explicit type conversion. \
Note
Implicit type conversion is when the program automatically changes the datatype of a variable to suit the needs of the further process. Explicit type conversion is when the programmer has to manually change the datatype of a value for the change of the datatype.
Loops
Python has mainly two loops, these are for and while loops
For loop is a collection based loop, that is it works by operating on a set where as while works as a condition based loop where the loop operates on a condition.
Syntax of for loops \
Python interpretor will prioritise the arguments in the …range() function in this way ending_num > starting_num > step. So using an Syntax of while loops \
Examples of the loops - printing numbers from 1 to 9
Multiline statements in python
Since python uses indentation for its language instaed of having code inside of brackets it is not natural to write multiline statements inside python. Usage of the “\” symbol signals the interpretor that its a multiline statement.
Logical statements
There are a few logical statements in python this includes if, else, elif, and, or.
Example
There are a few logical statements in python this includes if, else, elif, and, or.
The usage of basic if-else statements
Example
The usage of compound if-else statement with and/or
|
|
Switch statements
Switch statements are the extension of if-else ladder and built for shotening the syntax. However this feature is only supported on python versions above 3.10.
Syntax
- Option can be replaced with the veariable you want the switch to run
- Case 1, 2, 3 can be replaced the the value of variable you want to be and it also supports string values
- The
case _
gives the default value and executes if none of the cases match
Functions
Functions is a set of code that can be called by the user at anytime based on the need. A function is reusable any number of times.
Syntax of a function
Modules
Modules or packages are a way to package your code into a collective for another program. There are a lot of modules in python such as numpy and math.
Example
Creating your own package
- In a python file make functions
- Save the file in which your other program is present
- Import the module into your own file.
Link
Default arguments
Default arguments are the what the funcion seeks to when the user provides no arguments when a function is called.
Default arguments must always be given from right to left
Global variables
There are two types of variables in python, local and global variables. Local variables are only defined within a function block and global variables are defined within the whole program.
Typically global variables are frowned upon, since they posess potential security vurnerablities.
Multiple variable assignments
In python multiple variable values can be assigned in the same line, this can be extensively used if you use a swapping function.
This will swap the values
Chapter summary - Unit 2
Higher Data Constructs: Lists and tuples: Basic skills for working with lists, list of lists, more skills for working with lists,
tuples;
Dictionaries: get started with dictionaries, more skills for working with dictionaries;
Strings: Basic skills for working with strings, split and join strings;
Dates and times: get started with dates and times
Text Book 1 – Chapters 6,12,10,11
Datatypes - complex
- Lists: A list is a mutable datatype in which all the elements are indexed from 0 to n
|
|
- Tuples: A tuple is an immutable datatype in which all the elements are indexed from 0 to n
|
|
- Dictionaries: A dictionary is a complex mutable datatype in which the elements are indexed upon the user’s needs, this is called the key value pairs.
|
|
- Sets: A set is a datatype of unordered, unindiexed and non-duplicated elements.
|
|
Lists in python
Lists are a datatype that can hold multiple values of different datatypes and is mutable i.e. values can be changed without fundamentally changing the variable.
- Initialising a list
- Accessing and printing the list
- List methods
Note: In the below example if return is specified means the orignal list is not modified and just returns a value in the variable. If return is not specified means that the list will be modified. If the function modifies the orignal list then the function/method will not be applicable for tuples.
|
|
Functions that require the random module
- List spiclng
The lists in python can be divided into subparts, this is known as splicing.
|
|
Here start gives the value of which index to start from, stop gives the final index and step gives the increment count.
Shallow and deep copy
There are a couple of difference in how the interpretor accesses a list compared to an immputable object. Whenever an immutable object is referred by another variable it copies the value of the object at that very instance, so if the variable’s data is changed the variable’s data gets destroyed and a new object is created. So in an nutshell if it’s an immutable object then the value remains same even if the host variable’s data is changed.
In the case of a mutable Object is referred then the interpreter makes a shallow copy of the object what this means is when the host object data is changed the others variables data also changes. The other variable doesn’t take the exact snapshot of the variable when the object was first referred to the variable references the variable and if the host variable changes the second variable also changes.
To remove this anomaly python introduces a new module called as copy. So as we have seen in the previous instances the python interpreter makes a shallow copy of the object. With the use of the copy Module we can make a deep copy of the object that is given above . With the deep copy method if the main object is changed the secondary object takes an exact snapshot of the main object and even after the main object changes the secondary object never changes.
Tuples
Tuples are the mutable conterpart of lists. This is an ordered, indexed and immutable datatype. Almost all the list methods are compatable except those which change lists value.
Refer the list functions above where the orignal list is not modified. If the functions/methods don’t modify the orignal list then the function is also applicable for tuples.
Sets
Sets are ordered, unindexed, immutable datatype with no duplicates.
Dictionary
Dictionaries are ordered indexed and mutable datatype with custiom key-value pairs.
Using a for loop to print out keys and values of the text
Note: There are a couple of points to remember when working with dictionaries. The value of an item can be anything, however the key of an item is only limited to immutable datatypes and no duplicates.
Dictionary methods
|
|
Strings
A string is a combination of more than one charecters.
- capitalize()
- count()
- find()
- isalnum()
- isdigit()…
Creation and modification of datetime
- Showing values
- Creating objects
Chapter summary - Unit 3
File I/O: An introduction to file I/O, test files, CSV files, binary files;
Exception Handling: handle a single exception, handle multiple exceptions, Two more skills;
Work with a database: An introduction to relational databases, SQL statements for data
manipulation, SQLite Manager to work with a database, use Python to work with a database
File write modes
- “x” - Create - will create a file, returns an error if the file exist
- “a” - Append - will create a file if the specified file does not exist
- “w” - Write - will create a file if the specified file does not exist
|
|
This will create a file object, and operations can be made from the folllowing file object.
Working with csv files
- Writing to a csv file
- import csv module
- obtain the writer object
|
|
- write data to the csv file
|
|
- Reading from a csv file
- import csv module
- ontain the reader onject
|
|
- read data using the reader obbject
- Example of working with a simple csv file
Output
- Example of working with a csv files with fields
|
|
Output
- Example of reading from a csv file
Output
- Example of working with binary files in python
Binary files can be opened with the pickle module
Exception handling in python
Whenever an error is occured any program spits out an error message and genrally terminates the program. With exception hadling in python, the interpretor manages the error in a specific way and enables the user to handle the exception in a custom manner.
Exception handling in python
This error code can be also written in this way to specify the custom error.
Here type error is a custom error, this can be replaced by the following errors.
- Raising an exception in python
A standard exception in python can be raised whenever a condition is met
- Use of finally in python The finally clause is executed regardless of whether or not an exception occurs in the try block. The finally clause is often used to close files or free up resources.
Here is an example of how to use the finally clause with the try…except statement:
SQLite with Python
SQLite is a lightweight, embedded relational database management system (RDBMS) that is included in the Python standard library. It is a popular choice for storing small to medium-sized amounts of data, and it is often used in web applications, desktop applications, and scientific computing.
To use SQLite with Python, you can import the sqlite3
module. This module provides a simple API for creating, connecting to, and querying SQLite databases.
Here is an example of how to create a new SQLite database and add a row to it:
|
|
You can also use the sqlite3
module to query SQLite databases. Here is an example of how to select all rows from the my_table
table:
|
|
Operations in SQlite
- Fetchall - Fetches all the rows and columns as a array
- Fetchone - Fetches one line in the form of a string (recursive call needed)
- Commit - Commit the saves
- Execute - Runs the command in the command script
Chapter summary - Unit 4
Object Oriented Programming:
Define and use your own classes: An introduction to classes and objects, define a class,
object composition, encapsulation;
Inheritance: Inheritance, override object methods;
Design an object oriented program: Techniques for object-oriented design
Text Book 1 – Chapters 14,15,16
Creating your own class
A class can be created in python by using the class keyword
This creates a blueprint for the objects to be defined. Methods and members can be defined in the class.
Constructors
Python classes need constructors to initialise the members and methods, it is initiated by the init keyword.
The self keyword acts as a self pointing object. Here when the object is generated the constructor is called and the msg variable is initiated. The usage of the self keyword is also crutial is called methods within classes.
This code can be also changed to accept paramatrised constructor
The self keyword here also sometimes acts like the super keyword in java.
Lambda functions
Lambda functions are functions are anoymous functions, it can have n number of arguments but can only have one expression.
Example:
Encapsulation
Encapsuation is the way of wrapping the data and the functions withing a class isolated from the ouytside interference. Encapsualation can be achieved in python by using private and public attributes at stretigic places to ensure the data safety.
Inheritance
Inheritance is a way for the derived class to get all the properties of base class including the class methods and class members.
Syntax of inheritance
Example of a program that follows polymorphism
|
|
IsInstance in python
The isinstance()
function in Python is used to check if an object is an instance of a specified class. The syntax of the isinstance() function is
|
|
Here is an example of the isinstance() function showing the difference between two inherited classes
Virtual environments in python
Before proceeding to the packages module in python, it is important to know about virtual environments. Note that you may proceed to packages without knowing about virtual environments, however it is recommended to know about virtual environments because it helps in keeping isolated packages for different projects as some deprecated packages might not work on newer projects and similarly newer packages may not work on legacy projects.
Requiremnets
- Python 3
- Pip
Steps
Installing virtual environemnt package
Creating virtual environent
Activating virtual environemt
Downloading required packages
Chapter summary - Unit 5
Packages:
How to build a GUI Program: Create a GUI that handles an event, more skills for working
with components;
Numpy Basics: Arrays and Vectorized Computation: Creating ndarrays, Data Types for
ndarrays, Operations between Arrays and Scalars, Basic Indexing and Slicing, Indexing with
slices, Boolean Indexing, Transposing Arrays and Swapping Axes;
Getting started with Pandas: Introduction to Pandas Data Structures, Summarizing and
Computing Descriptive Statistics, Handling missing data;
Plotting and Visualization: A Brief matplotlib API Primer, Plotting Functions in panda
GUI with Tkinter
Tkinter is a package in python that aids graphical applications. Installation of Tkinter can be done by
|
|
Creating a window
Mainloop aids the program in running recursively. This can be further improved by naming each part of the root window.
- Widgets: Widgets are the graphical objects that are found in tkinter. This inclues the root window all the labels and the entry field etc. The widgets should be mapped to other objects in order to work which can be a canvas or the root window as a base window.
Some example of widgets
- Label: displays text or image on the screen
- Button: adds a clickable button to the application
- Entry: allows single line text input from user
- Text: allows multi-line text input and formatting
- Frame: holds and organizes other widgets
- Scale: provides a graphical slider to select a value
- Listbox: displays a list of items to choose from
- Checkbutton: displays a toggle button with two states (on/off)
- Radiobutton: displays a button that can be selected from a group of buttons
Calling function in tkinter
An application made in Tkinter
|
|
Numpy
The numpy library is a python library that can be used to manupulate and work on complex numberical applications. NumPy supports numpy array which is ideal to perform large array operations since the faster access time. The NumPy library also supports broadcasting which is performing an operation throughout the array without using a for loop.
N dimentional array (Nd Array)
- Why is NumPy faster than lists
- NumPy arrays are stored at one continuous place in memory unlike lists, so processes can access and manipulate them very efficiently.
- This behavior is called locality of reference in computer science.
- This is the main reason why NumPy is faster than lists. Also it is optimized to work with latest CPU architectures.
- Operating on the elements in a list can only be done through iterative loops, which is computationally inefficient in Python.
- The NumPy package enables users to overcome the shortcomings of the Python lists by providing the data storage object called ndarray
- The ndarray is similar to lists, but rather than being highly flexible by storing different types of objects in one list, only the same type of element can be stored in each column.
- For example, with a Python list, you could make the first element a list and the second another list or dictionary. With NumPy arrays, you can only store the same type of element, e.g., all elements must be floats, integers, or strings.
- Despite this limitation, ndarray wins hands down when it comes to operation times, as the operations are sped up significantly.
- Creating ND array
|
|
- Slicing the ND array
The slicing works in a similar fashion as compared to for loops (except the step). You can nest string slicing to reduce the dimentions of the nDarray.