1 / 89

Unit I- Introduction to Python Concepts

Datatypes-Strings-List-Tuples-Dictionaries- Regular Expression

Gomathi6
Télécharger la présentation

Unit I- Introduction to Python Concepts

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SRI RAMAKRISHNA ENGINEERING COLLEGE [Educational Service : SNR Sons Charitable Trust] [Autonomous Institution, Accredited by NAAC with ‘A’ Grade] [Approved by AICTE and Permanently Affiliated to Anna University, Chennai] [ISO 9001:2015 Certified and all Eligible Programmes Accredited by NBA] VATTAMALAIPALAYAM, N.G.G.O. COLONY POST, COIMBATORE – 641 022. Department of Artificial Intelligence and Data Science 20AD2E51 - PYTHON FRAMEWORKS FOR MACHINE LEARNING PRESENTATION BY Mrs.V.GomathiSankari ASSISTANT PROFESSOR / AI&DS 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  2. 20AD2E51 PYTHON FRAMEWORKS FOR MACHINE LEARNING 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  3. Introduction To Python Language 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  4. Python • Python is a popular programming language. • It was created by Guido van Rossum , in 1991. • It is used for: Web Development Software Development Mathematics System Scripting and Machine Learning Applications. 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  5. Python Features • Object oriented and Functional • A Programming Language that can model a real world is said to be object oriented. • Python supports Object-Oriented style or technique of programming that encapsulates code within objects. • It’s Free • Python language is freely available at the official website and you can download it from the given download link below  https://www.python.org/downloads/ • Since it is open-source, this means that source code is also available to the public. So you can download it as, use it as well as share it. 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  6. Python Features • It’s Portable • Python is a portable Language. For Example : If we have Python Code for Windows Machine , we do not need to change it, we can run this code on any platform.(Mac,Linux) • It’s Powerful • Dynamic typing : It doesn’t require complicated type and size declarations in your code. • Automatic memory management : Python automatically allocates objects and reclaims (“garbage collects”) them when they are no longer used. • Programming-in-the-large support : Python includes tools such as modules, classes, and exceptions. • Built-in object types :lists, dictionaries, and strings. • Built-in tools : concatenation ,slicing ,sorting, mapping, and more. • Library utilities : large collection of precoded library tools (Scikit learn) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  7. Python Features • It’s Mixable • Python programs can easily be “glued” to components written in other languages in a variety of ways. • For example, Python’s C API lets C programs call and be called by Python programs flexibly. • It’s Relatively Easy to Use • Compared to other programming languages like C++, Java, and C#, Python programming seems simple to most observers. • Python programs are simpler, smaller, and more flexible to execute the programs immediately. • It’s Relatively Easy to Learn • Python has few keywords, simple structure, and a clearly defined syntax 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  8. Python Interpreter • The Programming Languages like c++ or Java,we must compile the code and then run it . But in python there is no need to compile the code. • Internally the python code is converted into immediate form called bytecode. • In python the code is executed line by line and not all at once. • The Python interpreter performs following tasks to execute a Python program : • Step 1 : The interpreter reads a python code or instruction. Then it verifies that the instruction is well formatted, i.e. it checks the syntax of each line.If it encounters any error, it immediately halts the translation and shows an error message. 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  9. Python Interpreter • Step 2 : If there is no error, i.e. if the python instruction or code is well formatted then the interpreter translates it into its equivalent form in intermediate language called “Byte code”.Thus, after successful execution of Python script or code, it is completely translated into Byte code. • Step 3 : Byte code is sent to the Python Virtual Machine(PVM).Here again the byte code is executed on PVM.If an error occurs during this execution then the execution is halted with an error message 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  10. Program Execution • It means to write and run a Python script in two different views, as a programmer, or as a Python interpreter • The Programmer’s View • A Python program is just a text file containing Python statements. • For example, the following file, named script.py, is one of the simplest Python scripts print('hello world') print(2 ** 100) • This file contains two Python print statements, which simply print a string (the text in quotes) and a numeric expression result (2 to the power 100) to the output stream. • By convention, Python program files are given names that end in .py • After you’ve typed these statements into a text file, you must tell Python to execute the file 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  11. Program Execution • The following command is used to execute the python script, C:\code> python script0.py hello world 1267650600228229401496703205376 • Python’s View • A basic understanding of the runtime structure of Python can help you grasp the bigger picture of program execution. • It’s first compiled to something called “byte code” and then routed to something called a “virtual machine.” • If the Python process has write access on your machine, it will store the byte code of your programs in files that end with a .pyc extension (“.pyc” means compiled “.py” source) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  12. Program Execution • When you execute a program, Python first compiles your source code into a format known as byte code. • Compilation is simply a translation step, and byte code is a lower-level, platform-independent representation of your source code. • Roughly, Python translates each of your source statements into a group of byte code instructions by decomposing them into individual steps. • The Python Virtual Machine (PVM) • Once your program has been compiled to byte code, it is shipped off for execution to something generally known as the Python Virtual Machine. • The PVM is the runtime engine of Python; it’s always present as part of the Python system, and it’s the component that truly runs your scripts. Technically, it’s just the last step of what is called the “Python interpreter.” 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  13. Program Execution 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  14. 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  15. The Interactive Prompt • The simplest way to run Python programs is to type them at Python’s interactive command line, sometimes called the interactive prompt. • There are a variety of ways to start this command line: in an IDE, from a system console, and so on. • Assuming the interpreter is installed as an executable program on your system, the most platformneutral way to start an interactive interpreter session is usually just to type python at your operating system’s prompt, without any arguments. 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  16. The Interactive Prompt • On Windows, you can type python in a DOS console window—a program named cmd.exe and usually known as Command Prompt. • Anytime you see the >>> prompt, you’re in an interactive Python interpreter session—you can type any Python statement or expression here and run it immediately. • Running Code Interactively 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  17. IDLE 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  18. IDLE • IDLE (short for Integrated Development and Learning Environment) is an integrated development environment for Python, which has been bundled with the default implementation of the language. • IDLE is intended to be a simple IDE and suitable for beginners. •  its main features are: • Multi-window text editor with syntax highlighting, autocompletion, smart indent and other. • Python shell with syntax highlighting. • Integrated debugger with stepping, persistent breakpoints, and call stack visibility. • List of Some of the IDE’s for Python are: • IDLE • PyCharm • Microsoft Visual Studio Code • Ninja 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  19. Python Data Types 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  20. Python Object Types Python Object Types • Immutable • Int • Float • String • Tuple • Mutable • list • Dictionary • Set 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  21. V.Gomathi Sankari, Assistant Professor(OG), AI&DS DatatypesandExample • Whenyouassign avaluetoavariable datatype isset : int float str a=10 a=2.5 a=“GKTCS” complex list tuple a=2x a=[“python", “Java", “Html“] a=(“python", “Java", “Html“)

  22. V.Gomathi Sankari, Assistant Professor(OG), AI&DS dict bool set a=True a = { “python", “Java", “Html“ } a={ "name":“Amit", "age":25} complex bytearray bytes a=2x a=bytearray(5) a=b”GKTCS”

  23. Python Numeric Types ( Mutable) • There are three numeric types in python • Int • Float • Complex x = 1 y = 2.8 z = 1+2j print(type(x)) print(type(y)) print(type(z)) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  24. Python Type Casting • Type Casting • It is used for data type conversion • Two types : • Implicit type Conversion • Explicit Conversion 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  25. Python Type Casting Implicit type conversion: • Python automatically converts one data type to another data type. This process doesn't need any user involvement. num_int = 123 num_flo = 1.23 num_new = num_int + num_flo print("datatype of num_int:",type(num_int)) print("datatype of num_flo:",type(num_flo)) print("Value of num_new:",num_new) print("datatype of num_new:",type(num_new)) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  26. Python Type Casting • Predefined functions like int( ), float( ) and complex( ) are used for data type conversion. Explicit type conversion: x = int(1) y = int(2.8) z = int("3") print(x) print(y) print(z) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  27. Python Strings (Immutable) • Strings is sequence of Unicode characters. We can use single quotes or double quotes to represent strings. Multi-line strings can be denoted using triple quotes, ''' or """. • Strings, however, are immutable. • In Python, individual characters of a String can be accessed by using the method of Indexing • Indexing allows negative address references to access characters from the back of the String 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  28. Python Strings (Immutable) Accessing a string String1 = "Python_programming" print("Initial String: ") print(String1) # Printing First character print("\nFirst character of String is: ") print(String1[0]) # Printing Last character print("\nLast character of String is: ") print(String1[-1]) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  29. Python Strings (Immutable) String Slicing String1 = “Python_programming" print("Initial String: ") print(String1) # Printing 3rd to 12th character print("\nSlicing characters from 3-12: ") print(String1[3:12]) # Printing characters between 3rd and 2nd last character print("\nSlicing characters between " + "3rd and 2nd last character: ") print(String1[3:-2]) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  30. Python Strings (Immutable) String updation : Updating a character in the string # Python Program to Update character of a String String1 = "Python_programming" print("Initial String: ") print(String1) # Updating a character of the String String1[2] = 'O' print("\nUpdating character at 2nd Index: ") print(String1) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  31. Python Strings (Immutable) String updation : Updating entire string # Python Program to Update entire String String1 = "Python_programming" print("Initial String: ") print(String1) # Updating a String String1 = "Welcome to Programming world" print("\nUpdated String: ") print(String1) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  32. Python Strings (Immutable) String updation : Deleting a character in the string # Python Program to Delete characters from a String String1 = "Python_programming" print("Initial String: ") print(String1) # Deleting a character of the String del String1[2] print("\nDeleting character at 2nd Index: ") print(String1) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  33. Python Strings (Immutable) String updation : Deleting entire string # Python Program to Delete entire String String1 = “Python_programming" print("Initial String: ") print(String1) # Deleting a String with the use of del del String1 print("\nDeleting entire String: ") print(String1) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  34. Python Strings (Immutable) Finding the length of a string: def findLen(str1): counter = 0 for i in str1: counter += 1 return counter str1 = "python_class" print(findLen(str1)) str1 = "python“ Print(len(srt1) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  35. Python Strings (Immutable) Python program to remove the characters which have odd index values of a given string def odd_values_string(str): result = "" for i in range(len(str)): if i % 2 == 0: result = result + str[i] return result print(odd_values_string('abcdef')) print(odd_values_string('python')) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  36. Python List (Mutable) • List is an ordered sequence of items. It is one of the most used data type in Python and is very flexible. • All the items in a list do not need to be of the same type. Items separated by commas are enclosed within brackets [ ] • Lists in Python can be created by just placing the sequence inside the square brackets[]. • Eg: a = [1, 2.2, 'python'] 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  37. Python List (Mutable) Creating a list: # Creating a List List = [] print("Blank List: ") print(List) # Creating a List of numbers List = [10, 20, 14] print("\nList of numbers: ") print(List) # Creating a List of strings and accessing using index List = ["Python", "programming", "class"] print("\nList Items: ") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['python', 'programming'] , ['class']] print("\nMulti-Dimensional List: ") print(List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  38. Python List (Mutable) Creating a list with duplicate and multiple types of values: # Creating a List with duplicate values List = [1, 2, 4, 4, 3, 3, 3, 6, 5] print("\nList with the use of Numbers: ") print(List) # Creating a List with mixed type of values List = [1, 2, 'Geeks', 4, 'For', 6, 'Geeks'] print("\nList with the use of Mixed Values: ") print(List) Knowing the size of the list: # Creating a List List1 = [] print(len(List1)) # Creating a List of numbers List2 = [10, 20, 14] print(len(List2)) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  39. Python List - Adding elements to the list using append() # Creating a List List = [] print("Initial blank List: ") print(List) # Addition of Elements in the List List.append(1) List.append(2) print("\nList after Addition of Two elements: ", List) # Adding elements to the List using Iterator for i in range(1, 4): List.append(i) print("\nList after Addition of elements from 1-3: ", List) # Adding Tuples to the List List.append((5, 6)) print("\nList after Addition of a Tuple: ", List) # Addition of List to a List List2 = ['For', 'Python_class'] List.append(List2) print("\nList after Addition of a List: ", List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  40. Python List - Adding elements to the list using insert() • append() method only works for addition of elements at the end of the List, for addition of element at the desired position, insert() method is used. • Unlike append() which takes only one argument, insert() method requires two arguments(position, value). # Creating a List List = [1,2,3,4] print("Initial List: ") print(List) # Addition of Element at specific Position List.insert(3, 12) List.insert(0, 'Python') print("\nList after performing Insert Operation: ") print(List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  41. Python List - Adding elements to the list using extend() • Other than append() and insert() methods, there’s one more method for Addition of elements, extend(), this method is used to add multiple elements at the same time at the end of the list. # Creating a List List = [1,2,3,4] print("Initial List: ") print(List) # Addition of multiple elements # to the List at the end List.extend([8, 'Python', 'Programming']) print("\nList after performing Extend Operation: ") print(List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  42. Python List – Accessing Elements in a multi – dimensional array Accessing elements in a multi - dimensional lists: List = ["List", "accessing", "index"] # accessing a element from the # list using index number print("Accessing a element from the list") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [['Python', 'programming'] , ['class']] # accessing an element from the # Multi-Dimensional List using # index number print("Accessing a element from a Multi-Dimensional list") print(List[0][1]) print(List[1][0]) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  43. Python List – Removing elements from the array using remove() Removing elements from the lists: • remove() method only removes one element at a time, to remove range of elements, iterator is used. The remove() method removes the specified item. List = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] print("Intial List: ") print(List) # Removing elements from List # using Remove() method List.remove(5) List.remove(6) print("\nList after Removal of two elements: ") print(List) # Removing elements from List # using iterator method for i in range(1, 5): List.remove(i) print("\nList after Removing a range of elements: ") print(List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

  44. Python List – Removing elements from the array using pop() Removing elements from the lists: • By default pop() removes only the last element of the set, to remove element from a specific position of the List, index of the element is passed as an argument to the pop() method.. List = [1,2,3,4,5] List.pop() print("\nList after popping an element: ") print(List) # Removing element at a specific location List.pop(2) print("\nList after popping a specific element: ") print(List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  45. Python List – Slicing a list Slicing a list: # Creating a List List = ['P','Y','T','H','O','N', 'P','R','O','G','R','A','M'] print("Intial List: ") print(List) # Print elements of a range Sliced_List = List[3:8] print("\nSlicing elements in a range 3-8: ") print(Sliced_List) # Print elements from a pre-defined point to end Sliced_List = List[5:] print("\nElements sliced from 5th " "element till the end: ") print(Sliced_List) # Printing elements from beginning till end Sliced_List = List[:] print("\nPrinting all elements using slice operation: ") print(Sliced_List) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  46. Python List (Mutable) Program to multiply all the items in a list: def multiply_list(items): tot =1 for x in items: tot *= x return tot print(multiply_list([1,2,-8])) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  47. Python Dictionary (Mutable) • Dictionary is an unordered collection of key-value pairs. • It is generally used when we have a huge amount of data. Dictionaries are optimized for retrieving data. We must know the key to retrieve the value. • In Python, dictionaries are defined within braces {} with each item being a pair in the form key:value. Key and value can be of any type. my_dict = {'name': 'Jack', 'age': 26} print(my_dict['name']) print(my_dict.get('age')) print(my_dict.get('address')) print(my_dict['address']) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  48. Python Dictionary (Mutable) Changing and adding and removing dictionary elements my_dict = { 'name' : 'abi' , 'age' : 20 } my_dict ['age' ] = 25 print (my_dict ) my_dict['address'] = 'Coimbatore' print(my_dict) dict2={ 1 : 10, 2 : 20, 3 : 30, 4 : 40, 5 : 50} print (dict2.pop(4)) print(dict2) print(dict2.popitem()) print(dict2) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  49. Python Dictionary (Mutable) Multiplying all elements in dictionary: my_dict = {'data1':10,'data2':-54,'data3':20} result=1 for key in my_dict: result=result * my_dict[key] print(result) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.GomathiSankari

  50. Python Dictionary (Mutable) Merging two dictionaries: d1 = {'a': 100, 'b': 200} d2 = {'x': 300, 'y': 200} d = d1.copy() d.update(d2) print(d) 20AD2E51 –PYTHON FRAMEWORKS FOR MACHINE LEARNING– Mrs.V.Gomathi Sankari

More Related