Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Hands on Session on Python
1. A hands on session on Python
SNAKES ON THE WEB:- Python
Sumit Raj
2. Contents
●
What is Python ???
●
Why Python ???
●
Who uses Python ???
●
Running Python
●
Syntax Walkthroughs
●
Strings and its operations
●
Loops and Decision Making
●
List, Tuple and Dictionary
●
Functions, I/O, Date & Time
●
Modules , File I/O
●
Sending a mail using Python
●
Coding Mantras
3. What is Python ???
General purpose, object-oriented, high level
programming language
Widely used in the industry
Used in web programming and in standalone
applications
4. History
●
Created by Guido von Rossum in 1990 (BDFL)
●
Named after Monty Python's Flying Circus
●
http://www.python.org/~guido/
●
Blog http://neopythonic.blogspot.com/
●
Now works for Dropbox
5. Why Python ???
●
Readability, maintainability, very clear readable syntax
●
Fast development and all just works the first time...
●
very high level dynamic data types
●
Automatic memory management
●
Free and open source
●
●
●
Implemented under an open source license. Freely usable and
distributable, even for commercial use.
Simplicity, Availability (cross-platform), Interactivity (interpreted
language)
Get a good salaried Job
6. Batteries Included
●
The Python standard library is very extensive
●
regular expressions, codecs
●
date and time, collections, theads and mutexs
●
OS and shell level functions (mv, rm, ls)
●
Support for SQLite and Berkley databases
●
zlib, gzip, bz2, tarfile, csv, xml, md5, sha
●
logging, subprocess, email, json
●
httplib, imaplib, nntplib, smtplib
●
and much, much more ...
8. Hello World
In addition to being a programming language, Python is also an
interpreter. The interpreter reads other Python programs and
commands, and executes them
Lets write our first Python Program
print “Hello World!”
9. Python is simple
print "Hello World!"
Python
#include <iostream.h>
int main()
{
cout << "Hello World!";
}
C++
public class helloWorld
{
public static void main(String [] args)
{
System.out.println("Hello World!");
}
}
Java
10. Let's dive into some code
Variables and types
>>> a = 'Hello world!'
>>> print a
'Hello world!'
>>> type(a)
<type 'str'>
•
•
•
•
•
# this is an assignment statement
# expression: outputs the value in interactive mode
Variables are created when they are assigned
No declaration required
The variable name is case sensitive: ‘val’ is not the same as ‘Val’
The type of the variable is determined by Python
A variable can be reassigned to whatever, whenever
>>> n = 12
>>> print n
12
>>> type(n)
<type 'int'>
>>> n = 12.0
>>> type(n)
<type 'float'>
>>> n = 'apa'
>>> print n
'apa'
>>> type(n)
<type 'str'>
11. Basic Operators
Operators
Description
Example
+
Addition
a + b will give 30
-
Subtraction
a - b will give -10
*
Multiplication
a * b will give 200
/
Division
b / a will give 2
%
Modulus
b % a will give 0
**
Exponent
a**b will give 10 to the
power 20
//
Floor Division
9//2 is equal to 4 and
9.0//2.0 is equal to 4.0
12. Strings: format()
>>>age = 22
>>>name = 'Sumit'
>>>len(name)
>>>print “I am %s and I have owned %d cars” %(“sumit”, 3)
I am sumit I have owned 3 cars
>>> name = name + ”Raj”
>>> 3*name
>>>name[:]
13. Do it !
Write a Python program to assign your USN
and Name to variables and print them.
Print your name and house number using
print formatting string “I am %s, and my
house address number is %d” and a tuple
15. Do it...
1) Create a variable that has your first and last name
2) Print out the first letter of your first name
3) Using splicing, extract your last name from the variable and
assign it to another
4) Try to set the first letter of your name to lowercase - what
happens? Why?
5) Have Python print out the length of your name string, hint
use len()
16. Indentation
●
Python uses whitespace to determine blocks of code
def greet(person):
if person == “Tim”:
print (“Hello Master”)
else:
print (“Hello {name}”.format(name=person))
17. Control Flow
if guess == number:
#do something
elif guess < number:
#do something else
while True:
#do something
#break when done
break
else:
#do something when the loop ends
else:
#do something else
for i in range(1, 5):
print(i)
else:
print('The for loop is over')
#1,2,3,4
for i in range(1, 5,2):
print(i)
else:
print('The for loop is over')
#1,3
18. Data Structures
●
List
●
●
[1, 2, 4, “Hello”, False]
●
●
Mutable data type, array-like
list.sort() ,list.append() ,len(list), list[i]
Tuple
●
●
●
Immutable data type, faster than lists
(1, 2, 3, “Hello”, False)
Dictionary
●
{42: “The answer”, “key”: “value”}
20. Functions
def printMax(x, y):
'''Prints the maximum of two numbers.
The two values must be integers.'''
x = int(x) # convert to integers, if possible
y = int(y)
if x > y:
return x
else:
return y
printMax(3, 5)
22. Date & Time
import time; # This is required to include time module.
getTheTime = time.time()
print "Number of ticks since 12:00am, January 1, 1970:",
ticks
time.ctime()
import calendar
cal = calendar.month(2008, 1)
print "Here is the calendar:"
print cal;
23. Modules
●
A module allows you to logically organize your Python code.
Grouping related code into a module makes the code easier
to understand and use.
●
#In calculate.py
def add( a, b ):
print "Addition ",a+b
# Import module calculate
import calculate
# Now we can call defined function of the module as:calculate.add(10, 20)
24. Files
myString = ”This is a test string”
f = open('test.txt', 'w') # open for 'w'riting
f.write(myString) # write text to file
f.close() # close the file
f = open('test.txt') #read mode
while True:
line = f.readline()
if len(line) == 0: # Zero length indicates EOF
break
print(line)
f.close() # close the file
26. A simple Python code to send a mail
try:
msg = MIMEText(content, text_subtype)
msg['Subject']= subject
msg['From'] = sender # some SMTP servers will do this
automatically, not all
conn = SMTP(SMTPserver)
conn.set_debuglevel(False)
conn.login(USERNAME, PASSWORD)
try:
conn.sendmail(sender, destination, msg.as_string())
finally:
conn.close()
except Exception, exc:
27. More Resources
●
●
●
http://www.python.org/doc/faq/
Google's Python Class
https://developers.google.com/edu/python/
An Introduction to Interactive Programming in Python
https://www.coursera.org/course/interactivepython
●
http://www.codecademy.com/tracks/python
●
http://codingbat.com/python
●
http://www.tutorialspoint.com/python/index.htm
●
●
How to Think Like a Computer Scientist, Learning with Python
Allen Downey, Jeffrey Elkner, Chris Meyers
Google