This is a basic to advanced python course for beginners
Size: 555.46 KB
Language: en
Added: Sep 07, 2024
Slides: 94 pages
Slide Content
Introduction to Python
Introduction to Python & Jupyter Notebook
What is Python? Python is a Programming Language
Why Programming Languages? The computer understands 1 s and 0 s only To communicate a real life problem to the computer, you need to create a specific type of text, called a source code or a human readable code that software can read and then process to the computer in 1 s and 0 s
Why Python? Python is an open source, general purpose high level programming language Open Source : Open source means it is free. Python has a large and active scientific community with access to the software’s source code and contributes to its continuous development and upgrading, depending on users ’ needs. General Purpose : There is a broad set of fields where Python could be applied web programming , analysis of financial data, analysis of big data, and more High-level : High level languages employ syntax a lot closer to human logic, which makes the language easier to learn and implement
What we need? We need a language kernel or a compiler + interpreter for Python An interface or an IDE to write our programs
Jupyter The Jupyter Notebook App is a server client application that allows you to edit your code through a web browser The Jupyter installation always comes with an installed Python kernel, and the other kernels can be installed additionally The Jupyter server provides the environment where a client is matched with a corresponding languages kernel In our case, we will focus on Python and a web browser as a client
Create a new Folder & a notebook Select Documents Go to new -> Folder Select New Folder Created Click Rename Give a name (Introduction to Python) Now select the same folder -> New -> Python 3 Notebook Your new notebook will open in a separate tab
Your Notebook
Save your notebook Click on Untitled Enter a name and click rename
Executing code Type the code in an input field Press Shift + Enter to execute If your coding has an output, it will be displayed in an output field
Variables
What is a variable? A variable is a container which holds a value. When ever we want use the value in our program, we use the variable name in our code instead of the value.
Assigning a value to a Variable If you are already familiar with Java, you’ll feel working with variables in Python is lot more easier than Java In python we don’t have to specify the data type of the variable You can assign a value to a variable using the assignment operator (=) x = 88 You can define more than one variable in a line x , y = 10,20
Python Data Types Python support 4 data types Integer Float Stirng Boolean
Functions with Variables When you want to check the data type of your variable use: t ype(variable name or value) When you want to convert to another data type: You have integer 10 stored in a variable and you want to convert it into float 10 (10.0) X = 10 float(x)
Logical Operators NOT AND NOT Result True NOT(True) False False NOT(False) True Cond1 Cond2 Result True True True True False False False True False False False False
Logical Operators OR Cond1 Cond2 Result True True True True False True False True True False False False NOT AND OR
Conditional Statements
Conditions Applying a condition if (condition) : statements to execute when the condition is True else : statements to execute when the condition is False
start Define variable marks and assign a value marks > 50 Print “Congratulations” Print “try again” end NO YES Conditions
Conditions if ( condition 1): statements to execute when the condition1 is True elif (condition 2): statements to execute when the condition1 is false and condition2 is True else: Statements to execute when both condition1 & condition2 are false
Functions
User Defined Functions Syntax to define a function def function_name ([ parameter_list ]): method implementation Ex: def display_my_name (): print(“Sasheena”)
Call the function defined You can call the function using the function name. If function take parameters, pass values to those parameters // calling function display_my_name ();
Functions with Parameters def add_10( x ): print(x+10) //call the function add_10( 50 ) X is the parameter here 50 is the value passed to x and called argument
Return Statement We can use return statement to return values from our function to the calling environment def multiply_by_5(x): result = x * 5 print( x,”multiplied by 5”) return result
Function within a Function def cal_tax (basic): tax = basic * 0.02 print ("tax deduction",tax ) return tax //we are going to use cal_tax inside cal_net_sal def cal_net_sal (basic): tax = cal_tax (basic) net = basic - tax print ("Net Salary after tax:",net )
Function within a Function We have to call only cal_net_sal function. Cal_tax function is invoked or called inside the cal_net_sal function
Functions with multiple parameters def cal_net_sal ( basic,otRate,otHrs ): tax = cal_tax (basic) ot = cal_ot ( otRate,otHrs ) net = basic+ot-tax print ("Net Salary after tax:",net )
Built – in Functions There are lot of built – in functions available in Python The difference of built – in functions is we do not have to implement the operation. We can directly use these functions with proper arguments inside our code. Lets look into few.
Built – in Functions m ax will help you find the maximum value from a value set m ax(10,35,105) m in will help you find the minimum value from a value set min(25,16,69) a bs returns the absolute value of a given value abs(-22) s um returns the total of a list list_1 =[25,36,95,74] sum(list_1)
Built – in Functions round will return the rounded value for the given number of decimal points round(5.333333,2) r ound (3.6) pow function take two parameters and return the first parameter to the power of second parameter pow(2,10) len function returns number of elements l en (“Sasheena”)
Sequences
What is a sequence A sequence is a container which can hold multiple values. In Python there are Lists Tuples Dictionaries
Lists Create a list students = ["Aruna", " Kasun "," Dilini "," Rivini "] Display all values students Indexes Access an element students[1] Aruna Kasun Dilini Ruvini 1 2 3
Lists Access last element students [ -1 ] Changing values in the list students[2] = “ Nadee ” Delete an element del students[1 ]
Built-in Methods for Lists There are methods associated with Lists. We can use them without implementation. append Takes only one argument and add it at the end of the list. s tudents.append (“Sasheena”)
Built-in Methods for Lists Extend([a list]) Can take another list as an argument and add it to the existing list. students.extend ([“Sahan”,”Dinusha”,”Gayani”]) len () returns number of elements in a list. len (students)
List Slicing You can take parts of a list, using their index numbers. If you want to slice the 2 nd and 3 rd elements from the students list students[1:3] List_name [ Starting index of the slice last index of the slice , +1 ]
List Slicing If your slice starts from the 1 st element no need to indicate it. students[:4] To get the last two elements students[-2:]
Iterations
Iterations or Loops are use to execute a code segment repeatedly Python support For Loop While Loop
For Loop Even = [0,2,4,6,8,10,12,14,16,18,20] We going to print the values in this list with one single print() statement for n in Even: print( n )
For Loop If you want to print the numbers in the same line then modify your code as follows for n in Even: print( n, end=“ “ )
While loop Syntax: x = 0 while x <= 20: print(x, end=“ “) x=x+2
Advanced Python Tools
Object O riented Programming
Python Modules, Packages (Library) & Classes Class A Class B Function1() Class C Class D Function2() m odule_1 module_2 Module 1 Module 2 package
Pythons’ Standard Library A collection of modules available as soon as you install Python
Import Modules into your Code There are 4 ways to import modules into your code Method 1: import math math.sqrt (16) Method 2: If you need only the sqrt function from math module from math import sqrt sqrt (25)
Import Modules into your Code Method 3: same as method 2, but here we use a shorter name for function from math import sqrt as s s(36) Method 4: here we gives a shorter name for the module i mport math as m m.sqrt (100)
Numpy Numerical Python
What is Numpy? NumPy is a python library used for working with arrays. It also has functions for working in domain of linear algebra, fourier transform, and matrices.
Why? In Python we have lists that serve the purpose of arrays, but they are slow to process . numpy aims to provide an array object that is up to 50x faster than traditional Python lists . The array object in numpy is called ndarray , it provides a lot of supporting functions that make working with ndarray very easy . Arrays are very frequently used in data science, where speed and resources are very important.
How to import? import numpy in your applications by adding the import keyword : import numpy Now numpy is imported and ready to use . Or you can give an alias for numpy to avoid typing the name repeatedly in your programs import numpy as np
Create an ndarray object 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 ))
Create an ndarray object 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 Use a tuple to create a numpy array import numpy as np arr = np.array ((1, 2, 3, 4, 5)) print( arr )
Dimensions in Arrays 1-D Arrays import numpy as np arr = np.array ([1, 2, 3, 4, 5]) print( arr )
2-D Arrays An array that has 1-D arrays as its elements is called a 2-D array . These are often used to represent matrix import numpy as np arr = np.array ([[1, 2, 3], [4, 5, 6]]) print( arr )
3-D arrays Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6 import numpy as np arr = np.array ( [ [ [ 1, 2, 3], [4, 5, 6] ] , [ [ 1, 2, 3], [4, 5, 6 ] ] ] ) print( arr )
Check Number of Dimensions import numpy as np a = np.array (42) b = np.array ([1, 2, 3, 4, 5]) c = np.array ([[1, 2, 3], [4, 5, 6]]) d = np.array ([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]]) print( a.ndim ) print( b.ndim ) print( c.ndim ) print( d.ndim )
Access Array Elements 1-D Arrays import numpy as np arr = np.array ([1, 2, 3, 4]) print( arr [0 ])
Access Array Elements The first number represents the first dimension, which contains two arrays : [[1, 2, 3], [4, 5, 6]] and: [[7, 8, 9], [10, 11, 12 ]] Since we selected , we are left with the first array : [[1, 2, 3], [4, 5, 6]] 4 5 6 1 2 3 10 11 12 7 8 9 1
Access Array Elements The second number represents the second dimension, which also contains two arrays : [1, 2, 3] and: [4, 5, 6 ] Since we selected 1, we are left with the second array : [4, 5, 6] 4 5 6 1 2 3 1
Access Array Elements The third number represents the third dimension, which contains three values : 4 5 6 we selected 2, we end up with the third value: 6 4 5 6 1 2
Array Slicing Slicing in python means taking elements from one given index to another given index . We pass slice instead of index like this: [ start:end ]. We can also define the step, like this: [ start:end:step ]. If we don't pass start its considered If we don't pass end its considered length of array in that dimension If we don't pass step its considered 1
5 1 Array Slicing Slice elements from index 1 to index 5 from the following array : import numpy as np arr = np.array ([1, 2, 3, 4, 5, 6, 7]) print( arr [1:5 ]) 1 6 7 4 2 3 4 5 The result includes the start index, but excludes the end index.
Array Slicing Slice elements from index 4 to the end, of the array : print( arr [4 :]) Slice elements from the beginning to index 4 (not included ): print( arr [:4])
Negative Slicing Slice from the index 3 from the end, to index 1 from the end : import numpy as np arr = np.array ([1, 2, 3, 4, 5, 6, 7]) print( arr [-3:-1])
Step Use the step value to determine the step of the slicing : import numpy as np arr = np.array ([1, 2, 3, 4, 5, 6, 7]) print( arr [1:5: 2 ])
Step Return every other element from the entire array : import numpy as np arr = np.array ([1, 2, 3, 4, 5, 6, 7]) print( arr [::2])
Slicing 2-D Arrays From the second element, slice elements from index 1 to index 4 (not included ): import numpy as np arr = np.array ([ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10] ]) print( arr [ 1 , 1:4 ])
Slicing 2-D Arrays From both elements, return index 2 : import numpy as np arr = np.array ([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print( arr [0:2 , 2])
Slicing 2-D Arrays From both elements, slice index 1 to index 4 (not included), this will return a 2-D array : import numpy as np arr = np.array ([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]) print( arr [0:2 , 1:4])
Copy and View The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a view of the original array . The copy owns the data and any changes made to the copy will not affect original array, and any changes made to the original array will not affect the copy . The view does not own the data and any changes made to the view will affect the original array, and any changes made to the original array will affect the view.
Copy
View
Array Shape The shape of an array is the number of elements in each dimension.
Reshaping arrays Reshaping means changing the shape of an array. The shape of an array is the number of elements in each dimension. By reshaping we can add or remove dimensions or change number of elements in each dimension.
Reshape From 1-D to 2-D Convert the following 1-D array with 12 elements into a 2-D array. The outermost dimension will have 4 arrays, each with 3 elements:
Reshape From 1-D to 3-D
Splitting Array Splitting breaks one array into multiple . We use array_split () for splitting arrays, we pass it the array we want to split and the number of splits. import numpy as np arr = np.array ([1, 2, 3, 4, 5, 6]) newarr = np.array_split ( arr , 3) print( newarr )