Python

Python Course Content & Project Training

python-live-project-training-in-gandhinagar-ahmedabad

Python List

We provide best live project training in gandhinagar & ahmedabad.

Python has a great built-in list type named "list". List literals are written within square brackets [ ]. Lists work similarly to strings -- use the len() function and square brackets [ ] to access data, with the first element at index 0. (See the official python.org list docs.)

colors = ['red', 'blue', 'green']
print colors[ 0] ## red
print colors[ 2] ## green
print len(colors) ## 3

Assignment with an = on lists does not make a copy. Instead, assignment makes the two variables point to the one list in memory.

b = colors ## Does not copy the list

The "empty list" is just an empty pair of brackets [ ]. The '+' works to append two lists, so [1, 2] + [3, 4] yields [1, 2, 3, 4] (this is just like + with strings).

FOR and IN

Python's *for* and *in* constructs are extremely useful, and the first use of them we'll see is with lists. The *for* construct -- for var in list -- is an easy way to look at each element in a list (or other collection). Do not add or remove from the list during iteration.

squares = [1, 4, 9, 16]
sum = 0
for num in squares:
     sum += num
print sum ## 30

If you know what sort of thing is in the list, use a variable name in the loop that captures that information such as "num", or "name", or "url". Since python code does not have other syntax to remind you of types, your variable names are a key way for you to keep straight what is going on.

The *in* construct on its own is an easy way to test if an element appears in a list (or other collection) -- value incollection -- tests if the value is in the collection, returning True/False.

list = ['larry', 'curly', 'moe']
if 'curly'in list:
     print 'yay'

The for/in constructs are very commonly used in Python code and work on data types other than list, so you should just memorize their syntax. You may have habits from other languages where you start manually iterating over a collection, where in Python you should just use for/in.

You can also use for/in to work on a string. The string acts like a list of its chars, so for ch in s: print ch prints all the chars in a string.

Best Python – Python Training Provider in Gandhinagar and Ahmedabad.

python-live-project-training-in-gandhinagar-ahmedabad

String Methods

Here are some of the most common string methods. A method is like a function, but it runs "on" an object. If the variable s is a string, then the code s.lower() runs the lower() method on that string object and returns the result (this idea of a method running on an object is one of the basic ideas that make up Object Oriented Programming, OOP). Here are some of the most common string methods:

A google search for "python str" should lead you to the official python.org string methods which lists all the str methods.

Python does not have a separate character type. Instead an expression like s[8] returns a string-length-1 containing the character. With that string-length-1, the operators ==, <=, ... all work as you would expect, so mostly you don't need to know that Python does not have a separate scalar "char" type.

String Slices

The "slice" syntax is a handy way to refer to sub-parts of sequences -- typically strings and lists. The slice s[start:end] is the elements beginning at start and extending up to but not including end. Suppose we have s = "Hello"

python-live-project-training-in-gandhinagar-ahmedabad

Dict Formatting


The % operator works conveniently to substitute values from a dict into a string by name:




hash = {}
hash['word'] = 'garfield'
hash['count'] = 42
s = 'I want %(count)d copies of %(word)s' % hash # %d for int, %s for string # 'I want 42 copies of garfield'

Del

The "del" operator does deletions. In the simplest case, it can remove the definition of a variable, as if that variable had not been defined. Del can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary.

var =   6
del var # var no more!

list = [ 'a', 'b', 'c', 'd']
del list[0]     ## Delete first element
del list[-2:]     ## Delete last two elements
print list     ## ['b']

dict = {'a':1, 'b':2 ,'c':3}
del dict['b']     ## Delete 'b' entry
print dict    ## {'a':1, 'c':3}

Files

The open() function opens and returns a file handle that can be used to read or write a file in the usual way. The code f = open('name', 'r') opens the file into the variable f, ready for reading operations, and use f.close() when finished. Instead of 'r', use 'w' for writing, and 'a' for append. The special mode 'rU' is the "Universal" option for text files where it's smart about converting different line-endings so they always come through as a simple '\n'. The standard for-loop works for text files, iterating through the lines of the file (this works only for text files, not binary files). The for-loop technique is a simple and efficient way to look at all the lines in a text file:

# Echo the contents of a file
f = open('foo.txt', 'rU')
for line in f:     ## iterates over the lines of the file
    print line,     ## trailing , so print does not add an end-of-line char
                          ## since 'line' already includes the end-of line.
f.close()

Reading one line at a time has the nice quality that not all the file needs to fit in memory at one time -- handy if you want to look at every line in a 10 gigabyte file without using 10 gigabytes of memory. The f.readlines() method reads the whole file into memory and returns its contents as a list of its lines. The f.read() method reads the whole file into a single string, which can be a handy way to deal with the text all at once, such as with regular expressions we'll see later.

For writing, f.write(string) method is the easiest way to write data to an open output file. Or you can use "print" with an open file, but the syntax is nasty: "print >> f, string". In python 3000, the print syntax will be fixed to be a regular function call with a file= optional argument: "print(string, file=f)".