Introduction to Python - University of OxfordIntroduction to Python University of Oxford Department...
Transcript of Introduction to Python - University of OxfordIntroduction to Python University of Oxford Department...
Introduction to PythonUniversity of Oxford
Department of Particle PhysicsOctober 2019 – Part 1
Vipul DavdaParticle Physics Systems Administrator
Room 661Telephone: x73389
Introduction to Python 1
Python is an interpreted, object-oriented, high-level programming language with dynamic semantics.
Some specific features of Python are:
An interpreted language
Can be used interactively
Free software released under an open-source license
Available for all major OS: Linux/Unix, MacOS X, Windows
Easy language to learn
Used for rapid development
Widely used in scientific and numeric computing
Introduction to Python 2
What is Python?
Books:
A Student’s Guide to Python for Physical Modelingby Jesse M. Kinder and Philip Nelson
Fluent Pythonby Luciano Ramalho
Introduction to Python 3
Python Books
Running Python
Run interactively using python shell, ipython
Type the code in a file using a text editor
Introduction to Python 5
Running Python
Introduction to Python 6
Keywords in Python
and del from not while
as elif global or with
assert else if pass yield
break except import print True
class exec in raise False
continue finally is return
def for lambda try
Introduction to Python 7
Built-in Functions
https://docs.python.org/2/library/functions.htmlhttps://docs.python.org/3/library/functions.html
abs() divmod() input() open() staticmethod()
all() enumerate() int() ord() str()
any() eval() isinstance() pow() sum()
basestring() execfile() issubclass() print() super()
bin() file() iter() property() tuple()
bool() filter() len() range() type()
bytearray() float() list() raw_input() unichr()
callable() format() locals() reduce() unicode()
chr() frozenset() long() reload() vars()
classmethod() getattr() map() repr() xrange()
cmp() globals() max() reversed() zip()
compile() hasattr() memoryview() round() __import__()
complex() hash() min() set()
delattr() help() next() setattr()
dict() hex() object() slice()
dir() id() oct() sorted()
Most useful commands are:? introduction and overview
%quickref quick reference
help Python’s help system
object? details about the ‘object’
ln [1] %run rounding_error.py run the script
ln [1] %run –d rounding_error.py run in debug mode
ln [1] ! run shell commandsln [1]!pwd
/home/davda/demo
ln [1] %edit using editor within shell
ln [1] %cd <dir>
ln [64] %save my_session.py 20-45, 56 saves lines 20-45 and 56 to file my_session.py
Introduction to Python 8
ipython basics
Introduction to Python 9
Basic Types
Integer1 + 1
2
a = 4
type(a)
int
floatsb = 4.2
type(b)
float
Complexc = 1.5+2.5j
type(c)
complex
c.real
1.5
c.imag
2.5
booleans4 > 5
False
val = (4>5)
val
False
type(val)
bool
Introduction to Python 10
Operators and comparisons
Arithmetic operators:
+
-
*
/
// (integer division)
'**' (power)
%
Comparison operators:
>
<
>= (greater or equal)
<= (less or equal)
==
x = -1
if x < 0:
x = 0
print ('Negative value, changed to zero‘)
elif x == 0:
print ('Zero‘)
elif x == 1:
print (‘One‘)
else:
print ('More‘)
Introduction to Python 11
If Statements
a = ['cat', ‘dog', ‘rabbit']
for v in a:
print (v, len(v))
b = “hello world”
for v in b:
print (v)
Introduction to Python 12
For Statements
r = []
a, b = 0, 1
while b <= 100:
r.append(b)
a, b = b, a+b
print (r)
Introduction to Python 13
While Statements
One should never use an if statement to test the equality of two floats.sum = 0.0
for i in range(10):
sum += 0.1
If sum == 1.0:
print(sum)
If you do have to compare two floats use abs function
epsilon = 1e-12
if abs(sum-1.0) < epsilon:
print(sum)
https://docs.python.org/2/tutorial/floatingpoint.html
Introduction to Python 14
Rounding Errors
For example,
𝒙 = 𝟏, 𝒚 = 𝟏 + 𝟏𝟎−𝟏𝟒 𝟐
𝟏𝟎𝟏𝟒 𝒚 − 𝒙 = 𝟐
Introduction to Python 15
Rounding Errors
from math import sqrt
x = 1.0
y = 1.0 + (1e-14)*sqrt(2)
print((1e14)*(y-x))
print(sqrt(2))
1.4210854715202004
1.4142135623730951
http://www-personal.umich.edu/~mejn/
Main types of containers in Python are:
List
Tuples
Dictionary
Introduction to Python 16
Containers
Introduction to Python 17
Lists
List is created by putting comma-separated values between square brackets“[]”
list1 = [ 1, 2, 3, 4, 5]
Elements within the list can be accessed by using the integer corresponding to that element's position in the list, starting from ‘0‘
list2 = [“mathematics”, “physics”, “chemistry”, 2017]
print list2[1]
physics
A list may contain mixed parameter types and may be nested. list3=[1, ['a', 'b', 'c' ] ]
print list3[1][1]
b
list.append(x) Add an item to the end of the list list.extend(L) Extend the list by appending all the items in the given list list.insert(i, x) Insert an item at a given position. list.remove(x) Remove the first item from the list whose value is x. list.pop([i]) Remove the item at the given position in the list, and return it. list.index(x) Return the index in the list of the first item whose value is x. list.count(x) Return the number of times x appears in the list. list.sort() Sort the items of the list . list.reverse() Reverse the elements of the list list.clear() Remove all items from the list. (python3) list.copy() Return a shallow copy of the list. (python3)
https://docs.python.org/2.7/tutorial/datastructures.htmlhttps://docs.python.org/3.4/tutorial/datastructures.html
Introduction to Python 18
Lists Methods
cmp(list1, list2) Compares elements of both lists.
len(list) Gives the total length of the list.
max(list) Returns item from the list with max value.
min(list) Returns item from the list with min value.
list(tuple1) Converts a tuple into list.
Introduction to Python 19
List Functions
list1 = [1,2,3,4,5,6,7,8,9,10]
s = 0
for n in list1:
s = s + n
print (s)
55
print sum(list1)
55
Introduction to Python 20
Iterate List
Tuple is created by putting comma-separated values between round brackets ()
tup1 = (1,2,3,4,5)
The difference between tuple and list is that the tuples cannot be changed. It is an immutable object.
Accessing tuplestup1 = (1,2,3,4,5,6,7)
print tup1[1:5]
(2,3,4,5)
Introduction to Python 21
Tuples
cmp(tuple1, tuple2) Compares elements of both tuples.
len(tuple) Gives the total length of the tuple.
max(tuple) Returns item from the tuple with max value.
min(tuple) Returns item from the tuple with min value.
tuple(list1) Converts a list into tuple.
Introduction to Python 22
Tuples Functions
A dictionary is an unordered table that maps keys to values.
Dictionary is created by putting comma-separated values between curly brackets {}
Each key is separated from its value by a “:” , the items are separated by commas.
Keys are unique within a dictionary.
The values of a dictionary can be of any type, but the keys must be of an immutable data type.
Introduction to Python 23
Dictionary
cmp(d1, d2) Compares elements of both d1 and d2.
len(d) Gives the total length of the dictionary.
str(d) Outputs a printable string representation of a dictionary
Introduction to Python 24
Dictionary Functions
dict.clear() Removes all elements of dictionary dict
dict.copy() Returns a shallow copy of dictionary dict
dict.fromkeys() Create a new dictionary with keys from seq and values set to value.
dict.get(key, default=None) For key key, returns value or default if key not in dictionary
dict.has_key(key) Returns true if key in dictionary dict, false otherwise
dict.items() Returns a list of dict's (key, value) tuple pairs
dict.keys()Returns list of dictionary dict's keys
dict.setdefault(key, default=None) Similar to get(), but will set dict[key]=default if key is not already in dict
dict.update(dict2) Adds dictionary dict2's key-values pairs to dict
dict.values() Returns list of dictionary dict's values
Introduction to Python 25
Dictionary Methods
- valid from python 2.7
squares = {x: x*x for x in range(1,10)}
print(squares)
for item in squares.items():
print (item)
for (key, value) in squares.items():
print (key, value)
Introduction to Python 26
Dictionary Example
Write a program to calculate the area and the surface volume of a sphere.
The volume inside a sphere V = 4/3*π*r3
The area of a sphere is A = 4*π*r2
Introduction to Python 27
Exercise 1
Write a script to find numbers between 100 and 300 that are divisible by 7 and multiple of 5.
Introduction to Python 28
Exercise 2
Write a script to print a list after removing the 0th, 4th and 5th
elements.
Numbers = [‘Zero’, ‘One’, ‘Two’, ‘Three’, ‘Four’, ‘Five’]
Hint: Use built-in function enumerate.
for counter, value in enumerate(some_list):
print(counter, value)
Introduction to Python 29
Exercise 3