Вы находитесь на странице: 1из 74

Python Crash Course : Pre-Lunch Session

Introduction to Python
23rd January, 2016
Under the Skill Development Program in Physics (SDPP)
Department of Physics
Panjab University

Vipin Bhatnagar Abhimanyu Chawla


vipin@pu.ac.in chawla@pu.ac.in
Pre-Lunch Session Agenda
What is Python?
Why use Python?
Installation
Editors and IDEs
The Python Language
Hello World
Variables and Datatypes
Basic Operations
Sequences
Collections
Conditionals
Loops
Functions
Modules
File Handling

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 2
What is Python?
High-level programming language

Conceived in late 1980s by Guido van Rossum

Object-oriented

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 3
Why learn Python?
Extremely readable
Very efficient, extremely rich standard library
Cross-platform
Wide range of applications:

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 4
Python is everywhere!

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 5
The PyCloud
Set up by the EHEP Group of the Department of Physics
Cloud computing facility
would let you run Python and IPython Notebooks by using
just your web browser, on any device.
Connect to the wifi network:
SSID: PyCloud
Password:
Open your browser and go to:
http://xxx.xxx.xxx.xxx

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 6
Installation
Official Python website www.python.org has
packages for all the platforms.

Windows:
Simply download and run the installer
Linux:
Either use the package provided by your package
managaer or download and install from the official
website
Mac OS:
Use the package at the official website
23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 7
Installation in Windows OS
Download and execute the installer

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 8
Installation in Windows OS
Check Add Python 3.5 to PATH

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 9
Installation in Windows OS
Let the installer complete

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 10
Installation in Windows OS
You must see this screen after a successful install

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 11
The Version Conflict!
Should I use Python version 2 or 3?
Use v2 if:
You use a 3rd party Python code
You use a package or utility that doesn't yet have a
released version that is compatible with Python 3
Use v3 if:
You write your own code
You are new to Python

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 12
Hello World!
Open the Python IDLE editor (Interactive
DeveLopment Environment)
Enter a single line: print(Hello World!)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 13
Hello World!
What has happened behind the scenes is:
The built-in Python print( ) function fetched the text that
we passed in the brackets and did what it is supposed to
do print on the screen

This is the interactive way of writing Python code.

Using IDLE shell is a great way to learn Python.

But for more complicated code, we need a full fledged editor.

So that we write the entire code and execute it at once.

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 14
IDLE
IDLE offers an editor too!
For using that, we need to create a .py file.
In IDLE, go to File New File
This will create a new file with the .py
extension.
After the file creation you can write your code.

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 15
IDLE
Write the entire code and save the file

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 16
IDLE
Click Run Module or F5

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 17
IDLE
The output would be displayed in the shell.

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 18
Variables and Datatypes
Variable: storage location, symbolized with a
name given by you.
Datatype: The type of the data that is stored
in the variable
Datatypes in Python:
Integers, Floats, Strings
Lists, tuples, sets and dictionaries

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 19
Operations
Arithmetic

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 20
Operations
Comparison

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 21
Operations
Assignment

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 22
Sequences
Extremely useful Python datatype category
Includes:
Lists
Tuples
Strings
In this section:
Extraction
Access
Methods

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 23
Sequences
Strings:
st = January
An array of characters
Lists
ls = [Jan, Feb, Mar]
Tuples
tp= (Jan, Feb, Mar)
Lists and tuples are arrays of objects

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 24
Sequences Accessing elements
Access the elements using an index
Python offers an index notation that starts from 0
and increases by 1 from left to right.

So if we have a list:
ls = [Jan, Feb, Mar]
We can extract the second element by:
ls[1]

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 25
Sequences Splitting portions
seq[start:stop]
ls = [Jan, Feb, Mar, Apr, May, June]
ls[2:4] = [Mar, Apr]

Similarly for tuples


tp = (Jan, Feb, Mar, Apr, May, June)
tp[2:4] = (Mar, Apr)

And also for strings


st = January
st[2:4] = nu

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 26
Sequences Negative Indexing
To access items which are near the end of the
lists
Easy to count backwards
Indices start from -1 and decrease by one
from right to left

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 27
Sequences Shorthand Slicing
Use just one of the start:stop indices
Example, extract the first two elements:
ls = [Jan, Feb, Mar, Apr, May, June]
ls[:2] = [Jan, Feb]

Extract the last two elements:


ls = [Jan, Feb, Mar, Apr, May, June]
ls[-2:] = [May, June]

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 28
Sequences - Lists
Lists are mutable:
we can change them
we can add, remove or modify items of a list

List operations:
Use dot notation to call the method for the list
object
object.method(argument)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 29
Sequences - Lists
Remove an item
ls = [Jan, Feb, Mar, Apr, May,
June]
ls.remove(Apr)
print(ls)
Add an item
ls.append(Apr)
print(ls)
Get the index of an item
ls.index(Apr)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 30
Sequences - Lists
Add more than one item
ls = [Jan, Feb, Mar, Apr, May,
June]
ls.extend([July, August])
print(ls)
Count the occurrence of an item
ls.count(Apr)
Get the total number of items
len(ls)
Add an item at a given index
ls.insert(index,item)
ls.insert(3, Apr)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 31
Sequences - Strings
Methods to manipulate strings are different
from those of lists.
Count method and splitting works same as
lists
file=Filename.txt
file.count(t)
ext=file[-4:]

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 32
Sequences - Strings
Real Life Scenario
Database of names
Create email addresses from these
(name@example.com)
Use the format method
name=rahul
email={0}@{1}.org.format(name,
puhep)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 33
Hands-on Exercise 1
Consider the list:
ls = [Monday, Tuesday, Wednesday]

With a single line of Python code, get the


result:
Wed

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 34
Collections
Family of datatypes

Includes:
Sets
Dictionaries

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 35
Collections - Sets
Unordered collection of unique items
Can not contain duplicate items
No indexing
Example:
s1={"1A","1B","1C","1D"}
print(s1)
s2={"1A", "1D","1B","1C","1D"}
print(s2)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 36
Collections - Sets
Find common elements in two sets (intersection)
s1={"1A","1B","1C","1D"}
s2={"1D", "1E","1B","1F","1G"}
s1 & s2
Find elements in set 1 which are not in set 2 (subtraction)
s1 - s2
Union
s1 | s2
To add an element to a set
s1.add(1X)
To remove an element from a set
s1.remove(1X)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 37
Collections - Dictionaries
Sequences are indexed by pre-defined numbered indices

Dictionaries are indexed by values that are explicitly given by us.

Example:
table={1A: Abhimanyu, 1B: Ramanpreet,
1C: Priyanka}

Key-value pairs

Analogy with sequences:


Dictionary Keys Sequence Indices
Dictionary Values Sequence elements

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 38
Collections - Dictionaries
Accessing values refer by keys
table[1B]
Adding a new key-value pair
table[1D]=Rahul
Removing a key-value pair
del table[1D]
Accessing only the keys
table.keys()
Accessing only the values
table.values()

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 39
Quick Check
What would be the output of the following
Python code:

s1={3,4,5,6,7,5}
l1=list(s1)
l1.count(5)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 40
Hands-on Exercise 2
Consider this dictionary:
departments={Physics:10,
Chemistry:5, Mathematics:20}

Write a Python script that will output these


two lists:
[Mathematics, Chemistry, Physics]
[20,5,20]

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 41
Conditionals
Making your program execute an action
depending upon a condition being true or
false
In this section:
Alternative actions
Multiple conditions
Handle user input

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 42
Conditionals If statement
if 2>1:
print(indeed, 2 is greater than 1)

if 1>2:
print(indeed, 2 is greater than 1)

if 2>1:
print(indeed, 2 is greater than 1)

if 2>1:
print(indeed, 2 is greater than 1)
print(Always)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 43
Conditionals else statement
age = 13
if age>=18:
print("Qualifies to drive")
else:
print("Does not qualify to drive")
print("End of script")

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 44
Conditionals Getting user input
Use the input function to get input from user:

age=input("Enter your age: ")


if age >=18:
print("Qualifies to drive")
else:
print("Does not qualify to drive")
print("End of script")

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 45
Conditionals Multiple conditions

age=input("Enter your age: ")


if age < 14:
print(Too young for a drivers license")
elif age >=14 and age < 17:
print(Subject to your country of residence")
elif age >=17 and age < 18:
print(Qualifies for a drivers license in the USA ")
else:
print(Qualifies for a drivers license in any
country)
print(End of script)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 46
Conditionals Inline if
To quickly perform brief conditionals
That assign a value to a variable depending on
a condition

age = 21
license=Yes if age > 18 else No
print(license)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 47
Conditionals Usage in strings
email=input("Enter your email address: ")

if "gmail" in email:
print("You are a gmail user")
elif "yahoo" in email:
print("You are a yahoo user")
elif "hotmail" in email:
print("You are a hotmail user")
else:
print("Unknown user!")
print("End of script")

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 48
Homework Exercise
Let the user enter an email address. Check if
the email address is a valid email address or
not.

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 49
Loops The for loop
Lets get back to our list of months:
ls = [Jan, Feb, Mar, Apr, May,
June]
Suppose you have to print the months one after the
other
print(ls[0])
print(ls[1])
print(ls[2])
print(ls[3])
print(ls[4])
print(ls[5])

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 50
Loops The for loop
Is there an easy way out?

In plain English, our requirement is:


For each item of the list, print out the item

Python provides a for loop construct, which is very


close to plain English!
for item in ls:
print(item)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 51
Loops The for loop
Always start with the for keyword,

followed by the loop variable, which can have


any name that you want,

then the keyword in,

and finally the object that is to be iterated.

The line following the for loop must be indented.


23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 52
Loops The for loop
You can iterate over lists, tuples, strings, sets
and dictionaries.
For iterating over a list of progressing
numbers, use the range function:

for item in range(10,20,2):


print(item)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 53
Loops The for loop
One can embed if statements inside the for
loop:

ls = [1.txt, 2.txt, 3.doc, 4.doc]


for item in ls:
if doc in item:
print(item)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 54
Loops The while loop
Used to execute an action until a given
condition is met.

start=0
while start < 3:
print(start, is less than 3)
start=start+1

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 55
Loops The while loop
passwd=input(Enter the password: )
while passwd!=123:
print(Wrong password)
passwd=input(Enter the password: )
print(You have successfully logged in)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 56
Hands-on Exercise 3
Suppose you have a list of usernames. Derive
a list of email addresses from the usernames
list, given that each email account is at
puhep.org
usernames = [rahul, pooja]
Generate a list like:
emails =
[rahul@puhep.org,pooja@puhep.org]

Hint: Use placeholders to create email address {0}@{1}.

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 57
Functions
Built-in functions vs Custom functions

For custom functions, one must know


how to define the input parameters
how to define the algorithm of the function
how to return the calculated output

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 58
Functions
Calculate the area of a square:
def area(x):
a=x**2
return a
Use functions inside loops:

for side in [5,10,25]:


print(area(side))

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 59
Functions Multiple parameters
def rectangle(x,y):
area=x*y
return area

def email_generator(name,surname,domain):
email={0}.{1}@{2}.format(name, surname,
domain)
return email

Usage: email_generator(Rahul, Arora, gmail.com)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 60
Functions Default parameters
def
email_generator(name,surname,domain=gmai
l.com):
email={0}.{1}@{2}.format(name, surname,
domain)
return email

Usage:
email_generator(Rahul, Arora)
email_generator(Rahul, Arora, yahoo.com)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 61
Modules and Packages
Modules
A .py file containing classes, functions and
statements
We can import various modules to extend
functionality
Packages
Folders containing several modules or sub-
packages inside
Just like modules, these can also be imported
23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 62
Modules
For example, the datetime module
datetime is a module that contains classes and
functions for working with dates and times
To use its functionality, we need to import it:
import datetime
Now we can access the module features using
the dot notation.
datetime.datetime.now()

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 63
Modules
How to know the location of the imported
module?
Type the module name in the interactive session

For importing a single class:


from datetime import datetime

This imports the class datetime from the module


datetime

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 64
Packages
Import and use exactly like modules
First import the package, then use the dot
notation to use the functionality

import tkinter
tkinter.Tk()

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 65
Installing External Modules and Packages
Only a few modules and packages come along with the
original Python distribution

A lot of them need to be installed manually if you require


specific functionality

To install a module or package:


Open a command prompt
pip install modulename

Example:
pip install numpy

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 66
Modules and Packages
Get information about a package or module:
help(modulename)

Get list of features of a module


dir(modulename)

Go deeper in class hierarchy:


help(modulename.classname)
help(modulename.classname.functionname)

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 67
File Handling
General syntax to open a file:
file = open(filepath, mode)
Create a variable called file
This is where we will store our file object
Inside the open method we specify the filepath string and
the opening mode string

Next, if you want to access the content of the file you


would need to use the read method
content = file.read()

This saves the content of the file in the content variable

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 68
File Handling Reading a text file
file=open("Sample.txt",'r')
content=file.read()
print(content)
file.close()

file=open("Sample2.txt",'r')
content=file.readlines()
print(content)
file.close()

['This is the first line.\n', 'This is the second line']

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 69
File Handling Writing text files
file=open("Sample.txt",'a')
file.write("This is some more content\n")
file.close()

file=open("Sample.txt",'w')
file.write("This overwrites previous content\n")
file.close()

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 70
File Handling The with method
file=open(New.txt",'w')
file.write("This is new content\n")
file.close()
With the opened new.txt
file,
perform the following
action
with open(New.txt",'w') as file:

file.write(This is new content\n")

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 71
IDEs
Eclipse (eclipse.org)
For windows, linux and mac

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 72
IDEs
PyCharm (jetbrains.com/pycharm)
For windows, linux and mac

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 73
More in the post-lunch session!

23rd January, 2016 Python Crash Course Vipin Bhatnagar and Abhimanyu Chawla 74