1 Python Language
Topics for Today – Python Primer • Python Introduction • Installation/IDE uses • Lists & its Operations • Dictionary & its Operations • String & its Operations • Control Structure – Looping – Conditions • Data Structure – List – Sets – Dictionary 2
Python Usage 3
Where Python 4
Why Python? • Python is easy to use – Python typically operates at a much higher level of abstraction. – Syntax rules are very simple. – Python to take one-fifth the time it would if coded in C or Java
Why Python? – Python is expressive • Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages • Example: – In java • int temp = var1; • var1 = var2; • var2 = temp; – Python • var2, var1 = var1, var2 2/12/2018 1
Why Python? – Python is readable • one can guess easily what’s happening in code #Perl version. sub pairwise_sum { my($arg1, $arg2) = @_; my(@result) = (); @list1 = @$arg1; @list2 = @$arg2; for($i=0; $i < length(@list1); $i++) { push(@result, $list1[$i] + $list2[$i]); } return(@result); } # Python version. def pairwise_sum(list1, list2): result = [] for i in range(len(list1)): result.append(list1[i] + list2[i]) return result
Why Python? • Python is complete – Python standard library comes with modules for handling email, web pages, databases, operating system calls, GUI development, and more. • Python is cross-platform – Python runs on many different platforms: Windows, Mac, Linux, UNIX, and so on. • Python is free – Python was originally, and continues to be, developed under the open source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal applications, and you don’t need to pay a dime.
Installing Python • Installing Python is a simple matter, regardless of which platform you’re using. the most recent one can always be found at www.python.org.
command-line
The IDLE integrated development environment
Interactive and Programing Mode
Using IDLE’s Python Shell window
Comments • For the most part, anything following a # symbol in a Python file is a comment and is disregarded by the language.
Variables and assignments
del statement • The del statement deletes the variable.
Expressions • Python supports arithmetic and similar expressions; these will be familiar to most readers. The following code calculates the average of 3 and 5, leaving the result in the variable z:
Strings • You can use single quotes instead of double quotes. The following two lines do the same thing: • x = "Hello, World" • x = 'Hello, World'
Numbers • Python offers four kinds of numbers: integers, floats, complex numbers, and Booleans.
Numbers
Built-in numeric functions • Python provides the following number- related functions as part of its core: • abs, divmod, cmp, coerce, float, hex, int, long, max, min, oct, pow, round
Getting input from the user • You can also use the input() function to get input from the user. Use the prompt string you want displayed to the user as input’s parameter:
Lists • Lists are like arrays • A list in Python is much the same thing as an array in Java or C or any other language. It’s an ordered collection of objects. You create a listd by enclosing a comma separated list of elements in square brackets, like so: • Example • x = [1, 2, 3]
List indices Elements can be extracted from a Python list using a notation like C’s array indexing. Like C and many other languages, Python starts counting from 0; asking for element 0 if indices are negative numbers, they indicate positions counting from the end of the list, with –1 being the last position in the list, –2 being the second-to-last position, and so forth.
List indices • In thelist ["first", "second", "third", "fourth"], you can think of the indices as pointing like this:
Slicing in List • enter list[index1:index2] to extract all items including index1 and up to (but not including) index2 into a new list.
Slicing in List • When slicing a list, it’s also possible to leave out index1 or index2. Leaving out index1 means “go from the beginning of the list,” and leaving out index2 means “go to the end of the list”:
Slicing in List • Omitting both indices makes a new list that goes from the beginning to the end of the original list; that is, it copies the list. This is useful when you wish to make a copy that you can modify, without affecting the original list:
Modifying lists • You can use list index notation to modify a list as well as to extract an element from it.
Modifying lists • Slice notation can be used here too. Saying something like lista[index1:index2] = listb causes all elements of lista between index1 and index2 to be replaced with the elements in listb. listb can have more or fewer elements than are removed from lista, in which case the length of lista will be altered. You can use slice assignment to do a number of different things, as shown here:
Append, Extend • Appending a single element to a list is such a common operation that there’s a special append method to do it: The extend method is like the append method, except that it allows you to add one list to another:
Insert • insert is used as a method of lists and takes two additional arguments; the first is the index position in the list where the new element should be inserted, and the second is the new element itself:
The del statement • The del statement is the preferred method of deleting list items or slices. It doesn’t do anything that can’t be done with slice assignment, but it’s usually easier to remember and easier to read:
removes • remove looks for the first instance of a given value in a list and removes that value from the list:
Sorting lists • Lists can be sorted using the built-in Python sort method:
List membership with the in operator • It’s easy to test if a value is in a list using the in operator, which returns a Boolean value. You can also use the converse, the not in operator:
+ operator and * operator • To create a list by concatenating two existing lists, use the + (list concatenation) operator. This will leave the argument lists unchanged.
Min/Max • You can use min and max to find the smallest and largest elements in a list
List search with index • If you wish to find where in a list a value can be found (rather than wanting to know only if the value is in the list), use the index method.
List matches with count • count also searches through a list, looking for a given value, but it returns the number of times that value is found in the list rather than positional information:
Summary of list operations
Summary of list operations
Nested lists • Lists can be nested. One application of this is to represent two-dimensional matrices. The members of these can be referred to using two-dimensional indices. Indices for these work as follows:
Strings • strings can be considered sequences of characters which means you can use index or slice notation:
Escape sequences
The split and join string methods • join takes a list of strings and puts them together to form a single string with the original string between each element.
The split and join string methods • split returns a list of substrings in the string • By default, split splits on any whitespace, not just a single space character, but you can also tell it to split on a particular sequence by passing it an optional argument:
Converting strings to numbers
Modifying strings with list manipulations
index • Returns the location of substring in text
Excercise • Write a Program that input a name and and print in abbreviated form – Eg. Kamrn Ahmed – K. Ahmed
Replace • Replaces the first occurrence of substring with other one.
upper • Convert into upper case
Title • Capitalize the string
Excercise • Write a Program that input a name convert into capital, lower and upper Case. – Eg. Kamrn ahmed • Kamran Ahmed • KAMRAN AHMED • kamran ahmed
Range function
Comprehension
Looping
Exercise • Write a program that print EVEN numbers (2-20)
Home-Work • Write a program to generate Fibonacci series
Fibonacci series – Home Work
While Loop – Table
Exercise • Write a program to produce following output
For Loop
For Loop
The for loop with range function • Sometimes you need to loop with explicit indices (to use the position at which values occur in a list). You can use the range command together with the len command on lists to generate a sequence of indices for use by the for loop.
For Loop
For Loop output?
For Loop output?
Comprehension
String operations
Today’s Class • Topic 1. Python Dictionary and Sets 2. Probabilistic Algorithms (GA) 3. Research Paper Titled “Genetic Algorithm Implementation in Python” • Assignments 1. Write code of basic Genetic Algorithm in Python with reference of above research paper. Last Date: Two Weeks 72
Python Dictionary 73
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Dictionary
Accessing Values in Dictionary • Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. 81
Updating Dictionary • You can update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example 82
Updating Dictionary • What about concatenating dictionaries, like we did with lists? There is something similar for dictionaries: the update method update() merges the keys and values of one dictionary into another, overwriting values of the same key: 83
Delete Dictionary Elements • you can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. • To explicitly remove an entire dictionary, just use the del statement. Following is a simple example − 84
Iterating over a Dictionary 85
Iterating over a Dictionary 86
Dictionaries from Lists • Now we will create a dictionary, which assigns a dish to a country, of course according to the common prejudices. For this purpose we need the function zip(). The name zip was well chosen, because the two lists get combined like a zipper. 87
Dictionaries from Lists 88
Sets in Python 89 • The data tpye "set", which is a collection type, has been part of Python since version 2.4. A set contains an unordered collection of unique and immutable objects. The set data type is, as the name implies, a Python implementation of the sets as they are known from mathematics. This explains, why sets unlike lists or tuples can't have multiple occurrences of the same element.
Creating Sets 90
Set from List 91 We can pass a list to the built-in set function, as we can see in the following:
Frozensets • Frozensets are like sets except that they cannot be changed, i.e. they are immutable: 92
Set Operations 93
add(element) 94
clear 95
copy 96
difference 97
Difference Update 98
discard(el) 99
remove 100
intersection(s) 101
issubset() 102
issuperset() 103
pop 104
Useful Modules, Packages and Libraries
Useful Modules, Packages and Libraries
Useful Modules, Packages and Libraries
Useful Modules, Packages and Libraries
Useful Modules, Packages and Libraries
Useful Modules, Packages and Libraries
Useful Modules, Packages and Libraries
GUI
WxPython
Boa Constructor - wxPython GUI Builder
Visual Python for 3D graphics
Game Development
Plotting
Thank You
References • http://www.python-course.eu/ 119

"Automata Basics and Python Applications"

  • 1.
  • 2.
    Topics for Today –Python Primer • Python Introduction • Installation/IDE uses • Lists & its Operations • Dictionary & its Operations • String & its Operations • Control Structure – Looping – Conditions • Data Structure – List – Sets – Dictionary 2
  • 3.
  • 4.
  • 5.
    Why Python? • Pythonis easy to use – Python typically operates at a much higher level of abstraction. – Syntax rules are very simple. – Python to take one-fifth the time it would if coded in C or Java
  • 6.
    Why Python? – Pythonis expressive • Expressive in this context means that a single line of Python code can do more than a single line of code in most other languages • Example: – In java • int temp = var1; • var1 = var2; • var2 = temp; – Python • var2, var1 = var1, var2 2/12/2018 1
  • 7.
    Why Python? – Pythonis readable • one can guess easily what’s happening in code #Perl version. sub pairwise_sum { my($arg1, $arg2) = @_; my(@result) = (); @list1 = @$arg1; @list2 = @$arg2; for($i=0; $i < length(@list1); $i++) { push(@result, $list1[$i] + $list2[$i]); } return(@result); } # Python version. def pairwise_sum(list1, list2): result = [] for i in range(len(list1)): result.append(list1[i] + list2[i]) return result
  • 8.
    Why Python? • Pythonis complete – Python standard library comes with modules for handling email, web pages, databases, operating system calls, GUI development, and more. • Python is cross-platform – Python runs on many different platforms: Windows, Mac, Linux, UNIX, and so on. • Python is free – Python was originally, and continues to be, developed under the open source model, and it’s freely available. You can download and install practically any version of Python and use it to develop software for commercial or personal applications, and you don’t need to pay a dime.
  • 9.
    Installing Python • InstallingPython is a simple matter, regardless of which platform you’re using. the most recent one can always be found at www.python.org.
  • 10.
  • 11.
    The IDLE integrateddevelopment environment
  • 12.
  • 13.
  • 14.
    Comments • For themost part, anything following a # symbol in a Python file is a comment and is disregarded by the language.
  • 15.
  • 16.
    del statement • Thedel statement deletes the variable.
  • 17.
    Expressions • Python supportsarithmetic and similar expressions; these will be familiar to most readers. The following code calculates the average of 3 and 5, leaving the result in the variable z:
  • 18.
    Strings • You canuse single quotes instead of double quotes. The following two lines do the same thing: • x = "Hello, World" • x = 'Hello, World'
  • 19.
    Numbers • Python offersfour kinds of numbers: integers, floats, complex numbers, and Booleans.
  • 20.
  • 21.
    Built-in numeric functions •Python provides the following number- related functions as part of its core: • abs, divmod, cmp, coerce, float, hex, int, long, max, min, oct, pow, round
  • 22.
    Getting input fromthe user • You can also use the input() function to get input from the user. Use the prompt string you want displayed to the user as input’s parameter:
  • 23.
    Lists • Lists arelike arrays • A list in Python is much the same thing as an array in Java or C or any other language. It’s an ordered collection of objects. You create a listd by enclosing a comma separated list of elements in square brackets, like so: • Example • x = [1, 2, 3]
  • 24.
    List indices Elements canbe extracted from a Python list using a notation like C’s array indexing. Like C and many other languages, Python starts counting from 0; asking for element 0 if indices are negative numbers, they indicate positions counting from the end of the list, with –1 being the last position in the list, –2 being the second-to-last position, and so forth.
  • 25.
    List indices • Inthelist ["first", "second", "third", "fourth"], you can think of the indices as pointing like this:
  • 26.
    Slicing in List •enter list[index1:index2] to extract all items including index1 and up to (but not including) index2 into a new list.
  • 27.
    Slicing in List •When slicing a list, it’s also possible to leave out index1 or index2. Leaving out index1 means “go from the beginning of the list,” and leaving out index2 means “go to the end of the list”:
  • 28.
    Slicing in List •Omitting both indices makes a new list that goes from the beginning to the end of the original list; that is, it copies the list. This is useful when you wish to make a copy that you can modify, without affecting the original list:
  • 29.
    Modifying lists • Youcan use list index notation to modify a list as well as to extract an element from it.
  • 30.
    Modifying lists • Slicenotation can be used here too. Saying something like lista[index1:index2] = listb causes all elements of lista between index1 and index2 to be replaced with the elements in listb. listb can have more or fewer elements than are removed from lista, in which case the length of lista will be altered. You can use slice assignment to do a number of different things, as shown here:
  • 31.
    Append, Extend • Appendinga single element to a list is such a common operation that there’s a special append method to do it: The extend method is like the append method, except that it allows you to add one list to another:
  • 32.
    Insert • insert isused as a method of lists and takes two additional arguments; the first is the index position in the list where the new element should be inserted, and the second is the new element itself:
  • 33.
    The del statement •The del statement is the preferred method of deleting list items or slices. It doesn’t do anything that can’t be done with slice assignment, but it’s usually easier to remember and easier to read:
  • 34.
    removes • remove looksfor the first instance of a given value in a list and removes that value from the list:
  • 35.
    Sorting lists • Listscan be sorted using the built-in Python sort method:
  • 36.
    List membership withthe in operator • It’s easy to test if a value is in a list using the in operator, which returns a Boolean value. You can also use the converse, the not in operator:
  • 37.
    + operator and* operator • To create a list by concatenating two existing lists, use the + (list concatenation) operator. This will leave the argument lists unchanged.
  • 38.
    Min/Max • You canuse min and max to find the smallest and largest elements in a list
  • 39.
    List search withindex • If you wish to find where in a list a value can be found (rather than wanting to know only if the value is in the list), use the index method.
  • 40.
    List matches withcount • count also searches through a list, looking for a given value, but it returns the number of times that value is found in the list rather than positional information:
  • 41.
    Summary of listoperations
  • 42.
    Summary of listoperations
  • 43.
    Nested lists • Listscan be nested. One application of this is to represent two-dimensional matrices. The members of these can be referred to using two-dimensional indices. Indices for these work as follows:
  • 44.
    Strings • strings canbe considered sequences of characters which means you can use index or slice notation:
  • 45.
  • 46.
    The split andjoin string methods • join takes a list of strings and puts them together to form a single string with the original string between each element.
  • 47.
    The split andjoin string methods • split returns a list of substrings in the string • By default, split splits on any whitespace, not just a single space character, but you can also tell it to split on a particular sequence by passing it an optional argument:
  • 48.
  • 49.
    Modifying strings withlist manipulations
  • 50.
    index • Returns thelocation of substring in text
  • 51.
    Excercise • Write aProgram that input a name and and print in abbreviated form – Eg. Kamrn Ahmed – K. Ahmed
  • 52.
    Replace • Replaces thefirst occurrence of substring with other one.
  • 53.
  • 54.
  • 55.
    Excercise • Write aProgram that input a name convert into capital, lower and upper Case. – Eg. Kamrn ahmed • Kamran Ahmed • KAMRAN AHMED • kamran ahmed
  • 56.
  • 57.
  • 58.
  • 59.
    Exercise • Write aprogram that print EVEN numbers (2-20)
  • 60.
    Home-Work • Write aprogram to generate Fibonacci series
  • 61.
  • 62.
  • 63.
    Exercise • Write aprogram to produce following output
  • 64.
  • 65.
  • 66.
    The for loopwith range function • Sometimes you need to loop with explicit indices (to use the position at which values occur in a list). You can use the range command together with the len command on lists to generate a sequence of indices for use by the for loop.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
    Today’s Class • Topic 1.Python Dictionary and Sets 2. Probabilistic Algorithms (GA) 3. Research Paper Titled “Genetic Algorithm Implementation in Python” • Assignments 1. Write code of basic Genetic Algorithm in Python with reference of above research paper. Last Date: Two Weeks 72
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
    Accessing Values inDictionary • Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. 81
  • 82.
    Updating Dictionary • Youcan update a dictionary by adding a new entry or a key-value pair, modifying an existing entry, or deleting an existing entry as shown below in the simple example 82
  • 83.
    Updating Dictionary • Whatabout concatenating dictionaries, like we did with lists? There is something similar for dictionaries: the update method update() merges the keys and values of one dictionary into another, overwriting values of the same key: 83
  • 84.
    Delete Dictionary Elements •you can either remove individual dictionary elements or clear the entire contents of a dictionary. You can also delete entire dictionary in a single operation. • To explicitly remove an entire dictionary, just use the del statement. Following is a simple example − 84
  • 85.
    Iterating over aDictionary 85
  • 86.
    Iterating over aDictionary 86
  • 87.
    Dictionaries from Lists •Now we will create a dictionary, which assigns a dish to a country, of course according to the common prejudices. For this purpose we need the function zip(). The name zip was well chosen, because the two lists get combined like a zipper. 87
  • 88.
  • 89.
    Sets in Python 89 •The data tpye "set", which is a collection type, has been part of Python since version 2.4. A set contains an unordered collection of unique and immutable objects. The set data type is, as the name implies, a Python implementation of the sets as they are known from mathematics. This explains, why sets unlike lists or tuples can't have multiple occurrences of the same element.
  • 90.
  • 91.
    Set from List 91 Wecan pass a list to the built-in set function, as we can see in the following:
  • 92.
    Frozensets • Frozensets arelike sets except that they cannot be changed, i.e. they are immutable: 92
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
    Boa Constructor -wxPython GUI Builder
  • 115.
    Visual Python for3D graphics
  • 116.
  • 117.
  • 118.
  • 119.