0% found this document useful (0 votes)
44 views24 pages

Introduction To Python: 6th School On LHC Physics

The document provides an introduction and overview of the Python programming language. It discusses what Python is, its brief history as a language created in the 1990s, its built-in operators, comparisons to C++, and Python basics including for, if, and variables, lists, dictionaries, and functions. It also mentions classes and inheritance. The document is intended to introduce readers to Python and cover many of its fundamental aspects in a tutorial-style format.

Uploaded by

Manzoor ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views24 pages

Introduction To Python: 6th School On LHC Physics

The document provides an introduction and overview of the Python programming language. It discusses what Python is, its brief history as a language created in the 1990s, its built-in operators, comparisons to C++, and Python basics including for, if, and variables, lists, dictionaries, and functions. It also mentions classes and inheritance. The document is intended to introduce readers to Python and cover many of its fundamental aspects in a tutorial-style format.

Uploaded by

Manzoor ali
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

Introduction to Python

6th School on LHC Physics

Adeel-ur-Rehman
IT Department
National Center for Physics
Introduction & Outline
In this tutorial:

 What is Python and brief History

 Built-in Operators

 Comparison between python and C++

 Python Basics

 For, If and Variables

 Lists

 Dictionaries

 Functions

 Classes

 Inheritance
What is Python

• Python is a computer programming language


which is:
• General-purpose
• Open source
• Object-oriented
• Interpreted

• Used by hundred of thousands of developers


around the world in areas such as:
• Internet scripting
• System programming
• User interfaces
What is Python

• Combines remarkable power with very


clear syntax.
• Also usable as an extension language.
• Has portable implementation:
• Many brands of UNIX
• Windows
• OS/2
• Mac
• Amiga
Brief History

• Created in the early 1990s By Guido van Rossum.


• At Stichting Mathematisch Centrum in the Netherlands.
• As a successor of a language called ABC.
• Guido remains Python’s principal author.
• Includes many contributions from others.
• In 1995, Guido continued his work on Python.
• At the Corporation for National Research Initiatives.
• In Reston, Virginia.
• And released several versions of the software.
Brief History

• In October of the same year, the PythonLabs team moved


to Digital Creations (now Zope Corporation).
• In 2001, the Python Software Foundation (PSF) was
formed.
• Zope Corporation is a sponsoring member of the PSF.
• All Python releases are Open Source.
• Historically, most, but not all, Python releases have also
been GPL-compatible.
• The last versions released are 2.7.x and 3.6.x .
Operators (1/6)
Operators (2/6)
Operators (3/6)

Operators Description

^ Bitwise XOR

& Bitwise AND

<<, >> Shifts

+, - Addition and
Subtraction
Operators (4/6)

Operators Description

*, /, % Multiplication, Division
and Remainder
+x, -x Positive, Negative

~x Bitwise NOT

** Exponentiation
Operators (5/6)
Operators (6/6)
Comparison with C++

To print a statement… hello.cpp


Very simple in python… #include <iostream>
using namespace std;
void main()
hello.py
{
print “Hello World” cout << "Hello World" << endl;
user@host:~$ python hello.py }
Hello World
user@host:~$ g++ hello.cpp -o hello
user@host:~$ ./hello
Hello World
Revision for, if and Variables

Whitespace is important Variables have no type


In C++, { and } denote blocks – You don't need fixed declarations
Python uses indentation But you do need to keep track of
You can use spaces or tabs, and them
it doesn't matter how many, but be
consistent! a=5 #integer
b = 3.14 #floating point
for a in range(3): c = 1 + 1j #complex
print “spam ” d = “spam” #string
print “and eggs” e = True #boolean
spam spam spam and eggs
f = [1,2,3] #list
g = ('a','b','c') #tuple
if 1+1==2: h = {'a': 1, 'b': 2} #dictionary
print “True” i = MyClass() #object
else:
print “False”
True
Basics
Basic operations look the same as C++
a=3
b = 16
#while loop #get a string representation
c = a+b # *,/,etc while a<10: of anything
19 a+=1 str(a)
#if statement '3‘
c==19 # <=, >=, != etc
True if a>0 and b>0: str(range(5))
c=ba '[0,1,2,3,4]'
f=”hello” else:
g=”world” c=b*a
f+g
“helloworld” #for loop
total=0
a**2 for i in range(5):
9 total += i
h='33’ #string to number print total
int(h) #also float() etc 10
33
Lists
Almost everything involves working with lists
 – Lists can contain any type of object and objects can be mixed
#create a blank list
L = [] #remove an element #test for contents
L.remove('extra') if 'a' in L:
#create a list with mixed contents [1, 2, 'a', 'b', True] print “True”
L = [1, 2, 'a', 'b', True] True
#remove an index
#get one element #get list size
L[0] del L[4] len(L)
1 [1, 2, 'a', 'b'] 4
#get a range of elements #loop over a list #lists can be
L[1:3] for item in L: added
[2, 'a'] print item a+a
#add an element 1 [1,2,'a','b',1,2,'a','b']
L.append('extra') 2 (etc)
[1, 2, 'a', 'b', True, 'extra']
More on lists
There are lots of functions that work on lists to make your life
easier:
#enumerate a list(counting) #range with start,
for i,j in enumerate(['a','b','c']): finish, step
L = [10, 12, 3, 9, 0] print i,j range(5,0,1)
1a [5,4,3,2,1]
#minimum and maximum
min(L) 2b #make a list
0 3c [x*x for x in range(5)]
max(L) [0,1,4,9,16]
#get a range of numbers
12 (starts at 0) #filter a list
range(5) def f(x):
#get a sorted copy
[0,1,2,3,4] return x>0
sorted(L) #ascending filter(f,[1,0,1,2])
[0,3,9,10,12] #get a range with start [1,1,2]
#get a reversed copy and finish
#fill a list
reversed(L) range(3,5) L = [0]*5
[0,9,3,12,10] [3,4] [0,0,0,0,0]
Dictionaries
A dictionary is like a list, but uses arbitrary objects instead of
integers as the key:
#create a blank dictionary #delete an item #test if a key exists
d = {} del d['c'] if 'a' in d:
{'a':1, 'b':2} print “True”
#create a filled dictionary True
d = {'a':1, 'b':2} #loop over keys
#get an element for k in d:
d['a'] print k,”=”,d[k]
1 a=1
b=2
#set an element
d['c']=3 #loop over items
{'a':1, 'b':2, 'c':3} for k,v in d.items():
print k,”=”,v
#list the keys a=1
d.keys() b=2
['a', 'b', 'c']
Strings
The string type is somewhat like std::string in C++
#new string s.split(' ') #format a string
s = 'hello world‘ ['hello','world'] a=1
b=2
#length of string #get a character s = “%d+%d=%d” % (a,b,a+b)
len(s) s[0] '1+2=3'
11 ‘h’
#everything can be
#find a substring #get a substring using represented using %s
s.find('world') array notation #which means str(object)
6 s[1:5] #use %d, %f for special
#check beginning 'ello‘ number formats
(or end) #search and replace pi = 3.141592685
s.startswith('hello') s.replace('hello','hi') s = “pi=%s” % (pi)
True 'hi world‘ 'pi=3.141592685'
#split into a list when s = “pi=%.2f” % (pi)
a char is found 'pi=3.14'
Functions

Unlike C++, function names must be unique (no overloading)


#define a simple function #default arguments #use list of arguments
def topower(x,y=2): def addup(*numbers):
def helloworld(): return x**y total=0
print 'hello world' topower(16) for n in numbers:
helloworld() 256 total+=n
'hello world‘ topower(16,3) return total
4096 addup(1,2,3)
#a function that takes 6
an argument #return multiple arguments
def multi(): #anonymous function
def addone(x): return ('a', 1) (single expression)
x = x+1 multi() sqr = lambda x: x**2
return x ('a', 1) sqr(5)
addone(41) #use named arguments 25
42 def
knight(name,quest,favcolour):
...
knight(name='Lancelot',quest='
Grail',
favcolor=0x0000ff)
Classes
Classes in Python work roughly like C++, but have no concept
of variable privacy:
#make a new class #data isn't private class Petshop:
class Universe: #we can get the counter = 0
answer = 42 #answer directly def init (self,pets):
def deepthought(self): u.Answer self.pets = pets
print self.answer 42 def stock(self,pet): if
pet in self.pets:
#create a new instance #and change it
counter+=1
u = Universe() u.answer = 23
print counter
u.deepthought()
return True
#call the class method 23
else:
#note the 'self' in the #(you can use a class print counter
#argument list is not with no methods, return False
#needed when calling it #just variables like a
#make a new petshop p =
u.deepthought() struct in C++)
Petshop(['parrot'])
42 #class with a constructor
p.stock('parrot')
True
Inheritance
class SchoolMember:
class Teacher(SchoolMember):
'''Represents any school member.''' '''Represents a teacher.'''
def __init__(self, name, age): def __init__(self, name, age, salary):
self.name = name SchoolMember.__init__(self, name, age)
self.age = age self.salary = salary
print '(Initialized SchoolMember: %s)' print '(Initialized Teacher: %s)' %
% self.name self.name
def tell(self): def tell(self):
print 'Name:"%s" Age:"%s" ' % SchoolMember.tell(self)
print 'Salary:"%d"' % self.salary
(self.name, self.age)

class Student(SchoolMember):
t = Teacher('Mrs. Ibraheem', 40, 30000)
'''Represents a student.'''
def __init__(self, name, age, marks): s = Student(‘Ali', 21, 75)
SchoolMember.__init__(self, name, age) print # prints a blank line
self.marks = marks members = [t, s]
print '(Initialized Student: %s)' % for member in members:
self.name member.tell() # Works for instances of Student
def tell(self): as well as Teacher
SchoolMember.tell(self)
print 'Marks:"%d"' % self.marks
Modules

To do anything useful, you'll need to import modules from the


standard library or elsewhere:
●The libraries available with python or developed by users
are extensive – look before you write it yourself:

#import an entire module


import time
#call a member – note prefix
time.time()
#import a specific function or class from a module
from time import sleep
#call that function (without prefix)
sleep(5)
#import everything from MyFile.py
from MyFile import *
Good Luck

You might also like