SlideShare ist ein Scribd-Unternehmen logo
1 von 41
Downloaden Sie, um offline zu lesen
Introduction to Python
Marian HackMan Marinov <mm@1h.com>
Chief System Architect of SiteGround.com
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Indentation rules
Use only single type of indentation: tabs or spaces
Indentation rules are applied per function, not per file :(
Python allows you to mix spaces and tabs in different functions
Never use different amount of spaces
Never mix tabs and spaces
PEP8 defines 4 spaces as the delimiter for Python
# this is a comment
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Documentation
"""
Module documentation
"""
import module_name
print(module_name.__doc__)
print(module_name.func.__doc__)
help(func)
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Data types
Numbers - 1234, 3.1415
Strings - ’spam’, "ham’s", b’ax01c’
Lists - [1, [2, ‘three’], 4]
Dicts - {‘food’: ‘jam’, ‘taste’: ‘yummy’}
Tuples - (1, ‘spam’, 4, ‘U’)
Sets - unordered list of unique items
Files - file = open(‘doors’, ‘r’)
Core - Booleans, types, None
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Variable assignments
a = b = 'info'
a, b, c = 42
[ a, b ] = [ "info", "data" ]
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Number definitions
a = 1234 a = -23 a = 0
a = 99999999L a = 42l a = 1.54
a = 3.14e-10 a = 4E210
a = .1 a = 1.
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Number operations
X << N, X >> N - bitwise left/right shift
~X - bitwise invert
X ** Y == pow(x,y)
int(X)
long(X)
float(X)
pow(x, y, [,z]) Return x to the power y; if z is present, return x
to the power y, modulo z
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Number short operators
+= -=
*= %=
etc.
Marian HackMan Marinov <mm@1h.com> Introduction to Python
String definitions
str = "I'm string"
str = 'my string'
str = """block
of long
text
"""
str = "Single" "string" "line"
str = u"unicode string"
str = b'ax01c'
Marian HackMan Marinov <mm@1h.com> Introduction to Python
String formating
print("my %s string" % name)
print("my {0} string".format(name))
str = '{0}, {1} and {2}'
str.format('beer', 'rakia', 'wiski')
jolt = """
Greetings %(name)s.
This is your %(count)d visit here.
"""
values = { 'name': 'Pesho', 'count': 13 }
print (jolt % values)
cmp(jolt, jil) # returns -1, 0, 1
Marian HackMan Marinov <mm@1h.com> Introduction to Python
String operations
>>> S = "abcd1234"
>>> for x in S: print(x) # char by char
>>> S[0], S[-2]
('a', 3)
>>> S[1:3], S[3:], S[:-2]
('bc', 'd1234', 'abcd12')
>>> len(S)
8
>>> G = "kompot"
>>> S + G # concatenation
'abcd1234kompot'
>>> "5" in S
False
>>> "3" in S
True
Marian HackMan Marinov <mm@1h.com> Introduction to Python
String operations
>>> B = list(S) # convert a string into list
>>> line = 'new thing here'
>>> cols = line.split()
['new', 'thing', 'here']
>>> new_line = "AA".join(cols)
'newAAthingAAhere'
>>> new_line.replace('AA', '__')
'new__thing__here'
Marian HackMan Marinov <mm@1h.com> Introduction to Python
List operations
>>> L = [ 12, 34, 51 ]
>>> len(L)
3
>>> L[2]
51
>>> L = [ 12, [ 32, 65, 41 ], 51 ]
>>> len(L)
3
>>> L[1][2]
41
>>> L[1:]
[[32, 65, 41], 51]
Marian HackMan Marinov <mm@1h.com> Introduction to Python
List operations
>>> L.append('55') # adds 55 to the end of the list
delete and return the last val of the list
>>> L.pop()
>>> L.extend([82, 92]) # add multiple items to the end
>>> A = [ 'for', 'not', 'bare' ]
>>> A.remove('not') # removes an entry from the list
>>> A.index('bare') # returns 2
>>> A.insert(1, 'com') # adds 1 to com
leave only the first val of the list
>>> del A[1:]
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Dictionary operations
D = {}
D = { "info": "nodata", "code": 23 }
D = { "info": "nodata", "code": { "num": 23, "text": "missi
D = dict(name="Bob", "age"=40)
D = dict.fromkeys(['a', 'b'])
D["info"]
D["code"]["num"]
"code" in D
D.keys()
D.values()
D.items
D.pop(key) eq del(D[key])
len(D)
D[key] = 42
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Tuple operations
() - empty tuple
>>> T = (0,)
>>> T = ( 12, "311", 5 )
>>> T = 12, "311", 5
>>> T = tuple('text')
('t', 'e', 'x', 't')
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Set operations
>>> basket = {'app', 'org', 'app', 'par', 'org', 'ban'}
>>> basket # show that duplicates have been removed
{'org', 'ban', 'par', 'app'}
>>> 'orange' in basket # fast membership testing
True
>>> 'crabgrass' in basket
False
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Set operations
Demonstrate set operations on unique letters from two words
>>> a = set('abracadabra')
>>> b = set('alacazam')
>>> a # unique letters in a
{'a', 'r', 'b', 'c', 'd'}
>>> a - b # letters in a but not in b
{'r', 'd', 'b'}
>>> a | b # letters in a or b or both
{'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'}
>>> a & b # letters in both a and b
{'a', 'c'}
>>> a ^ b # letters in a or b but not both
{'r', 'd', 'b', 'm', 'z', 'l'}
Marian HackMan Marinov <mm@1h.com> Introduction to Python
File operations
output = open('file1', 'w')
input = open('file1', 'r')
input = open('file1', 'rb') # read binary
input = open('file1') # same as above
str = input.read() # reads entire file
str = input.read(N) # read next N chars
str = input.readline() # read a single line
lines = input.readlines() #read entire file into list
output.write(str)
output.writelines(lines)
fh.seek(N) # seek to offset N
fh.close() # close a file handler
for line in open('data'): print line
open('f.txt', encoding='utf-8')
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Program units
Functions
Modules
Classes
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Control structures
if-elif-else
while-else
for-else
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Control structures - if-elif-else
if <test>:
code
elif <test>:
code
elif <test>:
code
else:
code
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Control structures - if-elif-else
if 1: code
A = Y if X else Z
A = [Z, Y][bool(X)]
>>> branch = {'spam': 5, 'ham': 3, 'other': 1.15}
>>> print(branch.get('spam', 'bad value')
5
>>> print(branch.get('spam', 'bad value')
'bad value'
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Control structures - while-else
while <test>:
code
else:
code
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Control structures - for-else
for <statements>:
code
else:
code
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Control structures - nestead list
list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]]
for list in list_of_lists:
for x in list:
print x
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Controlling loops
break
continue
pass
the else block
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Controlling loops - break
while <test>:
code
if <test>:
break
else:
code
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Controlling loops - continue
while <test>:
code
if <test>:
continue
else:
code
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Controlling loops - pass
while 1: pass
def func1(name):
pass
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Controlling loops - else
while <test>:
code
if <test>:
continue
else:
code
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Breaking nestead loops
for x in range(10):
for y in range(10):
print(x*y)
if x*y > 50:
break
else:
continue # executed if the loop ended normally (
break # executed if 'continue' was skipped (break)
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Breaking nestead loops
for x in range(10):
for y in range(10):
for z in range(10):
print(x,y,z)
if x*y*z == 30:
break
else:
continue
break
else:
continue
break
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Breaking nestead loops
def your_outer_func():
...
def inner_func():
for x in range(10):
for y in range(10):
print(x*y)
if x*y > 50:
return
inner_func()
...
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Functions
def name(VARIABLES)
yield vs return
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Calling functions
func(value)
# Keyword argument - matched by name
func(name=value)
# Pass all objects in sequence as individual arguments
func(*sequence)
# Pass all key/value pairs in dict as individual keyword ar
func(**dict)
x = print
x('Indirect call of print')
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Function definitions
def func(name)
def func(name=value)
def func(*name) # args tuple/list
def func(**name) # dict
def func(*args, name)
def func(*, name=value)
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Difference between return and yield
return - returns one value and clear the state of the variables
yield - return a value and save the position
def gensquares(N):
for i in range(N):
yield i ** 2
for i in gensqares(5):
print(i, end=' : ')
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Working with modules
Import
From
Reload
Marian HackMan Marinov <mm@1h.com> Introduction to Python
Object Oriented Python
Marian HackMan Marinov <mm@1h.com> Introduction to Python
zip & map
map(func, *iterables)
zip
Marian HackMan Marinov <mm@1h.com> Introduction to Python

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Python Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and LoopsPython Programming Essentials - M16 - Control Flow Statements and Loops
Python Programming Essentials - M16 - Control Flow Statements and Loops
 
Python programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - KalamasseryPython programming Workshop SITTTR - Kalamassery
Python programming Workshop SITTTR - Kalamassery
 
Introduction to Python and TensorFlow
Introduction to Python and TensorFlowIntroduction to Python and TensorFlow
Introduction to Python and TensorFlow
 
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCEFUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
 
Programming Homework Help
Programming Homework Help Programming Homework Help
Programming Homework Help
 
Advanced Python, Part 2
Advanced Python, Part 2Advanced Python, Part 2
Advanced Python, Part 2
 
13. Java text processing
13.  Java text processing13.  Java text processing
13. Java text processing
 
Introduction to Recursion (Python)
Introduction to Recursion (Python)Introduction to Recursion (Python)
Introduction to Recursion (Python)
 
Python Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and FunctionsPython Unit 3 - Control Flow and Functions
Python Unit 3 - Control Flow and Functions
 
Day2
Day2Day2
Day2
 
13 Strings and Text Processing
13 Strings and Text Processing13 Strings and Text Processing
13 Strings and Text Processing
 
Python course Day 1
Python course Day 1Python course Day 1
Python course Day 1
 
Python for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.comPython for data science by www.dmdiploma.com
Python for data science by www.dmdiploma.com
 
Chapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQChapter 22. Lambda Expressions and LINQ
Chapter 22. Lambda Expressions and LINQ
 
Unit2 input output
Unit2 input outputUnit2 input output
Unit2 input output
 
Python Puzzlers - 2016 Edition
Python Puzzlers - 2016 EditionPython Puzzlers - 2016 Edition
Python Puzzlers - 2016 Edition
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
07. Java Array, Set and Maps
07.  Java Array, Set and Maps07.  Java Array, Set and Maps
07. Java Array, Set and Maps
 
Python numbers
Python numbersPython numbers
Python numbers
 
Python-02| Input, Output & Import
Python-02| Input, Output & ImportPython-02| Input, Output & Import
Python-02| Input, Output & Import
 

Andere mochten auch

Andere mochten auch (20)

Securing the network for VMs or Containers
Securing the network for VMs or ContainersSecuring the network for VMs or Containers
Securing the network for VMs or Containers
 
Gluster.community.day.2013
Gluster.community.day.2013Gluster.community.day.2013
Gluster.community.day.2013
 
Comparison of foss distributed storage
Comparison of foss distributed storageComparison of foss distributed storage
Comparison of foss distributed storage
 
Protecting your home and office in the era of IoT
Protecting your home and office in the era of IoTProtecting your home and office in the era of IoT
Protecting your home and office in the era of IoT
 
4 Sessions
4 Sessions4 Sessions
4 Sessions
 
Make your internship "worth it"
Make your internship "worth it"Make your internship "worth it"
Make your internship "worth it"
 
How penetration testing techniques can help you improve your qa skills
How penetration testing techniques can help you improve your qa skillsHow penetration testing techniques can help you improve your qa skills
How penetration testing techniques can help you improve your qa skills
 
How to setup your linux server
How to setup your linux serverHow to setup your linux server
How to setup your linux server
 
LUG-BG - Kostadin Slavkov - PostgreSQL 10
LUG-BG - Kostadin Slavkov - PostgreSQL 10LUG-BG - Kostadin Slavkov - PostgreSQL 10
LUG-BG - Kostadin Slavkov - PostgreSQL 10
 
Home assistant
Home assistantHome assistant
Home assistant
 
Lxd the proper way of runing containers
Lxd   the proper way of runing containersLxd   the proper way of runing containers
Lxd the proper way of runing containers
 
Practical my sql performance optimization
Practical my sql performance optimizationPractical my sql performance optimization
Practical my sql performance optimization
 
LUG-BG 2017 - Rangel Ivanov - Spread some butter - BTRFS
LUG-BG 2017 - Rangel Ivanov - Spread some butter - BTRFSLUG-BG 2017 - Rangel Ivanov - Spread some butter - BTRFS
LUG-BG 2017 - Rangel Ivanov - Spread some butter - BTRFS
 
Moving your router inside container
Moving your router inside container Moving your router inside container
Moving your router inside container
 
Why we are migrating to Slackware
Why we are migrating to SlackwareWhy we are migrating to Slackware
Why we are migrating to Slackware
 
Protecting your data when entering the US
Protecting your data when entering the USProtecting your data when entering the US
Protecting your data when entering the US
 
Computer vision for your projects
Computer vision for your projectsComputer vision for your projects
Computer vision for your projects
 
Io t introduction to electronics
Io t   introduction to electronicsIo t   introduction to electronics
Io t introduction to electronics
 
Performance comparison of Distributed File Systems on 1Gbit networks
Performance comparison of Distributed File Systems on 1Gbit networksPerformance comparison of Distributed File Systems on 1Gbit networks
Performance comparison of Distributed File Systems on 1Gbit networks
 
nftables - the evolution of Linux Firewall
nftables - the evolution of Linux Firewallnftables - the evolution of Linux Firewall
nftables - the evolution of Linux Firewall
 

Ähnlich wie Introduction to python

Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
g3_nittala
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
Ankur Gupta
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Yashpatel821746
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
bleis tift
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
UFPA
 

Ähnlich wie Introduction to python (20)

Python basic
Python basic Python basic
Python basic
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
Python Performance 101
Python Performance 101Python Performance 101
Python Performance 101
 
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
 
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
 
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
 
Python Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard WayPython Workshop - Learn Python the Hard Way
Python Workshop - Learn Python the Hard Way
 
Mcq cpup
Mcq cpupMcq cpup
Mcq cpup
 
Introduction to python programming 1
Introduction to python programming   1Introduction to python programming   1
Introduction to python programming 1
 
仕事で使うF#
仕事で使うF#仕事で使うF#
仕事で使うF#
 
Python 표준 라이브러리
Python 표준 라이브러리Python 표준 라이브러리
Python 표준 라이브러리
 
PYTHON
PYTHONPYTHON
PYTHON
 
Python Basics
Python BasicsPython Basics
Python Basics
 
Pythonppt28 11-18
Pythonppt28 11-18Pythonppt28 11-18
Pythonppt28 11-18
 
FUNDAMENTALS OF PYTHON LANGUAGE
 FUNDAMENTALS OF PYTHON LANGUAGE  FUNDAMENTALS OF PYTHON LANGUAGE
FUNDAMENTALS OF PYTHON LANGUAGE
 
pa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processingpa-pe-pi-po-pure Python Text Processing
pa-pe-pi-po-pure Python Text Processing
 
Python lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce functionPython lambda functions with filter, map & reduce function
Python lambda functions with filter, map & reduce function
 
Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?Porque aprender haskell me fez um programador python melhor?
Porque aprender haskell me fez um programador python melhor?
 
Python programming workshop session 3
Python programming workshop session 3Python programming workshop session 3
Python programming workshop session 3
 
Python-The programming Language
Python-The programming LanguagePython-The programming Language
Python-The programming Language
 

Mehr von Marian Marinov

Mehr von Marian Marinov (20)

Dev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & LoggingDev.bg DevOps March 2024 Monitoring & Logging
Dev.bg DevOps March 2024 Monitoring & Logging
 
Basic presentation of cryptography mechanisms
Basic presentation of cryptography mechanismsBasic presentation of cryptography mechanisms
Basic presentation of cryptography mechanisms
 
Microservices: Benefits, drawbacks and are they for me?
Microservices: Benefits, drawbacks and are they for me?Microservices: Benefits, drawbacks and are they for me?
Microservices: Benefits, drawbacks and are they for me?
 
Introduction and replication to DragonflyDB
Introduction and replication to DragonflyDBIntroduction and replication to DragonflyDB
Introduction and replication to DragonflyDB
 
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQMessage Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
 
How to successfully migrate to DevOps .pdf
How to successfully migrate to DevOps .pdfHow to successfully migrate to DevOps .pdf
How to successfully migrate to DevOps .pdf
 
How to survive in the work from home era
How to survive in the work from home eraHow to survive in the work from home era
How to survive in the work from home era
 
Managing sysadmins
Managing sysadminsManaging sysadmins
Managing sysadmins
 
Improve your storage with bcachefs
Improve your storage with bcachefsImprove your storage with bcachefs
Improve your storage with bcachefs
 
Control your service resources with systemd
 Control your service resources with systemd  Control your service resources with systemd
Control your service resources with systemd
 
Comparison of-foss-distributed-storage
Comparison of-foss-distributed-storageComparison of-foss-distributed-storage
Comparison of-foss-distributed-storage
 
Защо и как да обогатяваме знанията си?
Защо и как да обогатяваме знанията си?Защо и как да обогатяваме знанията си?
Защо и как да обогатяваме знанията си?
 
Securing your MySQL server
Securing your MySQL serverSecuring your MySQL server
Securing your MySQL server
 
Sysadmin vs. dev ops
Sysadmin vs. dev opsSysadmin vs. dev ops
Sysadmin vs. dev ops
 
DoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDKDoS and DDoS mitigations with eBPF, XDP and DPDK
DoS and DDoS mitigations with eBPF, XDP and DPDK
 
Challenges with high density networks
Challenges with high density networksChallenges with high density networks
Challenges with high density networks
 
SiteGround building automation
SiteGround building automationSiteGround building automation
SiteGround building automation
 
Preventing cpu side channel attacks with kernel tracking
Preventing cpu side channel attacks with kernel trackingPreventing cpu side channel attacks with kernel tracking
Preventing cpu side channel attacks with kernel tracking
 
Managing a lot of servers
Managing a lot of serversManaging a lot of servers
Managing a lot of servers
 
Let's Encrypt failures
Let's Encrypt failuresLet's Encrypt failures
Let's Encrypt failures
 

Kürzlich hochgeladen

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
dharasingh5698
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Christo Ananth
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
ankushspencer015
 

Kürzlich hochgeladen (20)

VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Palanpur 7001035870 Whatsapp Number, 24/07 Booking
 
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Wakad Call Me 7737669865 Budget Friendly No Advance Booking
 
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
Call Girls Pimpri Chinchwad Call Me 7737669865 Budget Friendly No Advance Boo...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
The Most Attractive Pune Call Girls Manchar 8250192130 Will You Miss This Cha...
 
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar  ≼🔝 Delhi door step de...
Call Now ≽ 9953056974 ≼🔝 Call Girls In New Ashok Nagar ≼🔝 Delhi door step de...
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
data_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdfdata_management_and _data_science_cheat_sheet.pdf
data_management_and _data_science_cheat_sheet.pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
(INDIRA) Call Girl Meerut Call Now 8617697112 Meerut Escorts 24x7
 
University management System project report..pdf
University management System project report..pdfUniversity management System project report..pdf
University management System project report..pdf
 
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank  Design by Working Stress - IS Method.pdfIntze Overhead Water Tank  Design by Working Stress - IS Method.pdf
Intze Overhead Water Tank Design by Working Stress - IS Method.pdf
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 

Introduction to python

  • 1. Introduction to Python Marian HackMan Marinov <mm@1h.com> Chief System Architect of SiteGround.com Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 2. Indentation rules Use only single type of indentation: tabs or spaces Indentation rules are applied per function, not per file :( Python allows you to mix spaces and tabs in different functions Never use different amount of spaces Never mix tabs and spaces PEP8 defines 4 spaces as the delimiter for Python # this is a comment Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 4. Data types Numbers - 1234, 3.1415 Strings - ’spam’, "ham’s", b’ax01c’ Lists - [1, [2, ‘three’], 4] Dicts - {‘food’: ‘jam’, ‘taste’: ‘yummy’} Tuples - (1, ‘spam’, 4, ‘U’) Sets - unordered list of unique items Files - file = open(‘doors’, ‘r’) Core - Booleans, types, None Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 5. Variable assignments a = b = 'info' a, b, c = 42 [ a, b ] = [ "info", "data" ] Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 6. Number definitions a = 1234 a = -23 a = 0 a = 99999999L a = 42l a = 1.54 a = 3.14e-10 a = 4E210 a = .1 a = 1. Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 7. Number operations X << N, X >> N - bitwise left/right shift ~X - bitwise invert X ** Y == pow(x,y) int(X) long(X) float(X) pow(x, y, [,z]) Return x to the power y; if z is present, return x to the power y, modulo z Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 8. Number short operators += -= *= %= etc. Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 9. String definitions str = "I'm string" str = 'my string' str = """block of long text """ str = "Single" "string" "line" str = u"unicode string" str = b'ax01c' Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 10. String formating print("my %s string" % name) print("my {0} string".format(name)) str = '{0}, {1} and {2}' str.format('beer', 'rakia', 'wiski') jolt = """ Greetings %(name)s. This is your %(count)d visit here. """ values = { 'name': 'Pesho', 'count': 13 } print (jolt % values) cmp(jolt, jil) # returns -1, 0, 1 Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 11. String operations >>> S = "abcd1234" >>> for x in S: print(x) # char by char >>> S[0], S[-2] ('a', 3) >>> S[1:3], S[3:], S[:-2] ('bc', 'd1234', 'abcd12') >>> len(S) 8 >>> G = "kompot" >>> S + G # concatenation 'abcd1234kompot' >>> "5" in S False >>> "3" in S True Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 12. String operations >>> B = list(S) # convert a string into list >>> line = 'new thing here' >>> cols = line.split() ['new', 'thing', 'here'] >>> new_line = "AA".join(cols) 'newAAthingAAhere' >>> new_line.replace('AA', '__') 'new__thing__here' Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 13. List operations >>> L = [ 12, 34, 51 ] >>> len(L) 3 >>> L[2] 51 >>> L = [ 12, [ 32, 65, 41 ], 51 ] >>> len(L) 3 >>> L[1][2] 41 >>> L[1:] [[32, 65, 41], 51] Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 14. List operations >>> L.append('55') # adds 55 to the end of the list delete and return the last val of the list >>> L.pop() >>> L.extend([82, 92]) # add multiple items to the end >>> A = [ 'for', 'not', 'bare' ] >>> A.remove('not') # removes an entry from the list >>> A.index('bare') # returns 2 >>> A.insert(1, 'com') # adds 1 to com leave only the first val of the list >>> del A[1:] Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 15. Dictionary operations D = {} D = { "info": "nodata", "code": 23 } D = { "info": "nodata", "code": { "num": 23, "text": "missi D = dict(name="Bob", "age"=40) D = dict.fromkeys(['a', 'b']) D["info"] D["code"]["num"] "code" in D D.keys() D.values() D.items D.pop(key) eq del(D[key]) len(D) D[key] = 42 Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 16. Tuple operations () - empty tuple >>> T = (0,) >>> T = ( 12, "311", 5 ) >>> T = 12, "311", 5 >>> T = tuple('text') ('t', 'e', 'x', 't') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 17. Set operations >>> basket = {'app', 'org', 'app', 'par', 'org', 'ban'} >>> basket # show that duplicates have been removed {'org', 'ban', 'par', 'app'} >>> 'orange' in basket # fast membership testing True >>> 'crabgrass' in basket False Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 18. Set operations Demonstrate set operations on unique letters from two words >>> a = set('abracadabra') >>> b = set('alacazam') >>> a # unique letters in a {'a', 'r', 'b', 'c', 'd'} >>> a - b # letters in a but not in b {'r', 'd', 'b'} >>> a | b # letters in a or b or both {'a', 'c', 'r', 'd', 'b', 'm', 'z', 'l'} >>> a & b # letters in both a and b {'a', 'c'} >>> a ^ b # letters in a or b but not both {'r', 'd', 'b', 'm', 'z', 'l'} Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 19. File operations output = open('file1', 'w') input = open('file1', 'r') input = open('file1', 'rb') # read binary input = open('file1') # same as above str = input.read() # reads entire file str = input.read(N) # read next N chars str = input.readline() # read a single line lines = input.readlines() #read entire file into list output.write(str) output.writelines(lines) fh.seek(N) # seek to offset N fh.close() # close a file handler for line in open('data'): print line open('f.txt', encoding='utf-8') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 20. Program units Functions Modules Classes Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 21. Control structures if-elif-else while-else for-else Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 22. Control structures - if-elif-else if <test>: code elif <test>: code elif <test>: code else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 23. Control structures - if-elif-else if 1: code A = Y if X else Z A = [Z, Y][bool(X)] >>> branch = {'spam': 5, 'ham': 3, 'other': 1.15} >>> print(branch.get('spam', 'bad value') 5 >>> print(branch.get('spam', 'bad value') 'bad value' Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 24. Control structures - while-else while <test>: code else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 25. Control structures - for-else for <statements>: code else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 26. Control structures - nestead list list_of_lists = [ [1, 2, 3], [4, 5, 6], [7, 8, 9]] for list in list_of_lists: for x in list: print x Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 27. Controlling loops break continue pass the else block Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 28. Controlling loops - break while <test>: code if <test>: break else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 29. Controlling loops - continue while <test>: code if <test>: continue else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 30. Controlling loops - pass while 1: pass def func1(name): pass Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 31. Controlling loops - else while <test>: code if <test>: continue else: code Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 32. Breaking nestead loops for x in range(10): for y in range(10): print(x*y) if x*y > 50: break else: continue # executed if the loop ended normally ( break # executed if 'continue' was skipped (break) Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 33. Breaking nestead loops for x in range(10): for y in range(10): for z in range(10): print(x,y,z) if x*y*z == 30: break else: continue break else: continue break Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 34. Breaking nestead loops def your_outer_func(): ... def inner_func(): for x in range(10): for y in range(10): print(x*y) if x*y > 50: return inner_func() ... Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 35. Functions def name(VARIABLES) yield vs return Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 36. Calling functions func(value) # Keyword argument - matched by name func(name=value) # Pass all objects in sequence as individual arguments func(*sequence) # Pass all key/value pairs in dict as individual keyword ar func(**dict) x = print x('Indirect call of print') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 37. Function definitions def func(name) def func(name=value) def func(*name) # args tuple/list def func(**name) # dict def func(*args, name) def func(*, name=value) Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 38. Difference between return and yield return - returns one value and clear the state of the variables yield - return a value and save the position def gensquares(N): for i in range(N): yield i ** 2 for i in gensqares(5): print(i, end=' : ') Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 39. Working with modules Import From Reload Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 40. Object Oriented Python Marian HackMan Marinov <mm@1h.com> Introduction to Python
  • 41. zip & map map(func, *iterables) zip Marian HackMan Marinov <mm@1h.com> Introduction to Python