Introduction to Python




Contributors




Ratnadeep Debnath 
@rtnpro

WHAT IS PYTHON?

  • A dynamic, interpreted, high-level language
  • Does not require declaring the types of variables or parameters or methods
  • Extremely readable
  • Used for solving a really wide range of problems
  • Object-oriented
  • Does not force Object-orientation
  • Has and requires common sense

Who all are using Python?

 

and the list goes on...

Why Python?

  • Used by many companies across the world including Google, Rackspace, Industrial Light and Magic, Flickr and many others.
  • A thriving community of developers and contributors and third party application developers.
  • PyPI (Python Package Index) lists about 33500 third-party software projects*... You name an area, there must be a Python package in it and mostly opensource and free!
  • Interpreted, dynamically typed, clean syntax, very easy to learn.
  • Learn Python in an Afternoon ;) - http://docs.python.org/2/tutorial/

Hello, world

How it's done with Java and C++


public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
} 

#include 
main()
{
    cout << "Hello World!";
    return 0;
} 
 
Requires a LOT more than just common sense.

The Pythonic way

Common sense: When you want to print a string, just print it.

In Python interpreter
 >>> print "Hello, world."

As a script
Open your favorite editor and type
#! /usr/bin/env python
print "Hello, world."
and save it as hello.py. And then execute it from command line as below
$ python hello.py

Assignments

In Python, we don't declare what kind of data we want to put in a variable.
 >>> a = 12
>>> b = 23 >>> a + b >>> 35

Examples
Multiple assignments

>>> a, b  = 10, 12>>> print a10>>> print b12

Python is fun

Let's try to swap 2 numbers
# The usual way>>> a = 10>>> b = 20>>> c = b>>> b = a>>> a = c>>> print a, b20 10
# The Pythonic way>>> a, b = 10, 20>>> a, b = b, a>>> print a, b20 10

DATATYPES

# Integer>>> a = 10# Float>>> b = 2.35# String>>> c = "Hello"# List>>> d = [1, 2, 'blah', 3.2]# Dictionary>>> f = {'a': 1, 'b': 2.3, 'c': "foo"}>>> f['b']2.3

Arithmetic operators


>>> 2 + 3
5
>>> 23 - 3
20
>>> 22.0 / 12
1.8333333333333333>>> 14 % 32>>> 4.0 // 3
1.0
>>> 4.0 / 3
1.3333333333333333

Logical operators

To do logical AND , OR we use and ,*or* keywords. x and y returns False if x is False else it returns evaluation of y. If x is True, it returns True.

>>> 1 and 4
4
>>> 1 or 4
1
>>> -1 or 4
-1
>>> 0 or 4
4 

Shorthand Operators

x op = expression is the syntax for shorthand operators. It will be evaluated like x = x op expression , Few examples are

>>> a = 12
>>> a += 13
>>> a
25
>>> a /= 3
>>> a
8
>>> a += (26 * 32)
>>> a
840 

Type Conversions


  • float(string) -> float value
  • int(string) -> integer value
  • str(integer) or str(float) -> string representation

>>> a = 8.126768
>>> str(a)
'8.126768' 

If-else , the control flow

if expr1:
    do this
elif expr2:
    do that
...
...
...
else:
   do whatever 
Truth value testing
DO
if x:
    pass 
DON'T
if x == True:
    pass


Try out!



1 . Write a program to find greatest of two numbers.

2. Write program which takes a number as input and if number is divisible by 3, 5 print Fizz, Buzz, FizzBuzz respectively

Functions


Defining a function




def functionname(params):
    statement1
    statement2 


Sum of 2 integers



>>> def sum(a, b):
...     return a + b
>>> res = sum(234234, 34453546464)
>>> res
34453780698L

Default argument value


>>> def test(a , b=-99):
...     print a
... print b

>>> test(12, 23)
1223
>>> test(12)
12-99

Keyword arguments


>>> def func(a, b=5, c=10):
...     print 'a is', a, 'and b is', b, 'and c is', c
...
>>> func(12, 24)
a is 12 and b is 24 and c is 10
>>> func(12, c = 24)
a is 12 and b is 5 and c is 24
>>> func(b=12, c = 24, a = -1)
a is -1 and b is 12 and c is 24






Lists


>>> a = [23, 45, 1, -3434, 43624356, 234] 
# Append
>>> a.append(45)
>>> a
[23, 45, 1, -3434, 43624356, 234, 45] 
# Insert
>>> a.insert(0, 1) # 1 added at the 0th position of the list
>>> a
[1, 23, 45, 1, -3434, 43624356, 234, 45] 
>>> a.insert(0, 111)
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 234, 45]
# Count the length of the list
>>> a.count(45)
2 

# Remove a element from the list
>>> a.remove(234) 
>>> a
[111, 1, 23, 45, 1, -3434, 43624356, 45] 
# Reverse a list
>>> a.reverse() 
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111] 
# Append a list into another list
>>> b = [45, 56, 90]
>>> a.append(b) 
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90]]
>>> a[-1]
[45, 56, 90] 
# Extend a into b
>>> a.extend(b) #To add the values of b not the b itself
>>> a
[45, 43624356, -3434, 1, 45, 23, 1, 111, [45, 56, 90], 45, 56, 90]
>>> a[-1]
90 

# Sort a list
>>> a.sort()
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356, [45, 56, 90]] 
# Delete a element in list
>>> del a[-1]
>>> a
[-3434, 1, 1, 23, 45, 45, 45, 56, 90, 111, 43624356] 
# Basic Data Structure
>>> a = [1, 2, 3, 4, 5]
>>> a.append(1)
>>> a
[1, 2, 3, 4, 5, 1]
>>> a.pop(0)
1
>>> a.pop(0)
2
>>> a
[3, 4, 5, 1] 

>>> l = [1, 2, 3, 4, 5, 6, 7] [1, 2, 3, 4, 5, 6, 7]
>>> l[:2] #first two elements
[1, 2] 
>>> l[2:] #exclude first two elements
[3, 4, 5, 6, 7]
>>> l[::2] #every second element[1, 3, 5, 7]
>>> l[::1] #every element[1, 2, 3, 4, 5, 6, 7]
>>> l[::3] #every third element
[1, 4, 7] 
>>> l[::10] #every tenth element
[1] 
>>> l[::-1]
[7, 6, 5, 4, 3, 2, 1]

Try Out!

>>> l[1:7:2] 
>>> [][:2] 
>>> [1][:2] 

List Comprehensions


# List Comprehensions 
>>> a = [1, 2, 3]
>>> [x ** 2 for x in a]
[1, 4, 9]
>>> z = [x + 1 for x in [x ** 2 for x in a]]
>>> z
[2, 5, 10]



Looping

While Loop

while condition:
    statement1
    statement2 
>>> n = 0>>> while n < 11:
...     print n
...     n += 1
...
0
1
2
3
4
5
6
7
8
9
10 

For Loop

>>> a = ['Python', 'is', 'powerful'] 

>>> for x in a:
...     print x,
...
Python is powerful 

>>> range(1, 5)
[1, 2, 3, 4]
>>> range(1, 15, 3)
[1, 4, 7, 10, 13]
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(10, 1, -2)
[10, 8, 6, 4, 2]

For...else...


>>> for i in range(0, 5):
...     print i
... else:
...     print "Bye bye"
...
0
1
2
3
4
Bye bye

Try Out!



1. A program to print the even numbers between 1-100



Sets


# Set: Another data-structure with no duplicate items
>>> a = set('abcthabcjwethddda')
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 't', 'w']) 
# Set Operations
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a                                  # unique letters in a
set(['a', 'r', 'b', 'c', 'd'])
>>> a - b                              # letters in a but not in b
set(['r', 'd', 'b'])
>>> a | b                              # letters in either a or b
set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'])
>>> a & b                              # letters in both a and b
set(['a', 'c']) 
>>> a ^ b                              # letters in a or b but not both
set(['r', 'd', 'b', 'm', 'z', 'l']) 
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 't', 'w'])
>>> a.add('p')
>>> a
set(['a', 'c', 'b', 'e', 'd', 'h', 'j', 'q', 'p', 't', 'w']) 





Strings

>>> s = "I am Indian"
>>> s
'I am Indian'
>>> s = 'I am Indian'
>>> s = "Here is a line \
... splitted in two lines"
>>> s
'Here is a line split in two lines'
>>> s = "Here is a line \n split in two lines"
>>> s
'Here is a line \n split in two lines'
>>> print s
Here is a line
split in two lines 
>>> s = """ This is a
... multiline string, so you can
... write many lines"""
>>> print s
This is a
multiline string, so you can
write many lines 

# String Methods
>>> s = "We all love Python" 
>>> s.split(" ")
['We', 'all', 'love', 'Python']
>>> x = "Nishant:is:waiting"
>>> x.split(':')
['Nishant', 'is', 'waiting']
>>> "-".join("GNU/Linux is great".split(" "))
'GNU/Linux-is-great' 
>>> s = "  abc\n "        #Strips whitespaces and newlines
>>> s.strip()
'abc' 
>>> s = "faulty for a reason"
>>> s.find("for")
7
>>> s.find("fora")
-1 

>>> s.startswith("fa") #To check if the string startswith fa or not True>>> s.endswith("reason") # True 
>>> s = "sayan chowdhury"
>>> s.title()
'Sayan Chowdhury' 
>>> z = s.upper()
>>> z
'SAYAN CHOWDHURY'
>>> z.lower()
'sayan chowdhury'
>>> s = "I am A pRoGraMMer"
>> s.swapcase()
'i AM a PrOgRAmmER'






Dictionaries

>>> data = {'kushal':'Fedora', 'kart_':'Debian', 'Jace':'Mac'}
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian'}
>>> data['kart_']
'Debian'

To add more data to it by simply

>>> data['parthan'] = 'Ubuntu'
>>> data
{'kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}

To delete any particular key:value pair

>>> del data['kushal']
>>> data
{'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'

To check if any key is there in the dictionary or not you can use 'in' keyword.

>>> 'Soumya' in data
False

If you want to loop through a dict use iteritems() method.


    >>> data
{'Kushal': 'Fedora', 'Jace': 'Mac', 'kart_': 'Debian', 'parthan': 'Ubuntu'}
>>> for x, y in data.iteritems():
...     print "%s uses %s" % (x, y)
...
Kushal uses Fedora
Jace uses Mac
kart_ uses Debian
parthan uses Ubuntu

>>> data['foo']
Traceback (most recent call last):
File "", line 1, in 
KeyError: 'foo'
>>> data.get('foo', None)
None 

Fun exercise

Let's find all Pycon US 2013 videos' download links :)

Are you ready for the challenge?

Solution


from BeautifulSoup import BeautifulSoup 
import requests 
 
url = 'http://pyvideo.org/category/33/pycon-us-2013/files' 
req = requests.get(url) 
data = req.text 
soup = BeautifulSoup(data) 
 
for link in soup.findAll('a', href=True): 
    # if link['href'].startswith(
	#'http://s3.us.archive.org/nextdayvideo/psf/pycon2013/'):
    if link.get('href', '').startswith(
            'http://s3.us.archive.org/nextdayvideo/psf/pycon2013/'): 
        #print link.get('href') 
        print link.get('href').split('?Signature')[0]

Links you can use

  • http://pypi.python.org - Python Package Index
  • http://docs.python.org/2/tutorial/ - The “official” Python tutorial
  • http://wiki.python.org/moin/MostPopularPythonProjects - 
  • http://www.python.org/community/workshops/ - Python 
  • http://wiki.python.org/moin/ - The Python “MoinMoin” Wiki
  • http://docs.python.org/devguide/ - All about developing Python
  • http://mail.python.org/mailman/listinfo - A list of all Python
  • http://pymbook.readthedocs.org/en/latest/ - Python for you & me
  • http://pythonbooks.revolunet.com/
  • http://git.io/7W2LkQ - Kracekumar

Introduction to Python

By Ratnadeep Debnath

Introduction to Python

  • 4,260
Loading comments...

More from Ratnadeep Debnath