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.
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.
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:
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:
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:
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:
Excercise • Write aProgram that input a name convert into capital, lower and upper Case. – Eg. Kamrn ahmed • Kamran Ahmed • KAMRAN AHMED • kamran ahmed
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.
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
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
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
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.