SlideShare a Scribd company logo
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

More Related Content

PPTX
Python programing
PPTX
PDF
Functions in python
PPTX
GE8151 Problem Solving and Python Programming
PDF
Python Functions (PyAtl Beginners Night)
DOCX
Python unit 3 and Unit 4
ODP
Python quickstart for programmers: Python Kung Fu
PPTX
Python programing
Functions in python
GE8151 Problem Solving and Python Programming
Python Functions (PyAtl Beginners Night)
Python unit 3 and Unit 4
Python quickstart for programmers: Python Kung Fu

What's hot (20)

PPTX
Python Programming Essentials - M16 - Control Flow Statements and Loops
PDF
Python programming Workshop SITTTR - Kalamassery
PPTX
Introduction to Python and TensorFlow
PPTX
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
PPTX
Programming Homework Help
PDF
Advanced Python, Part 2
PPTX
13. Java text processing
PDF
Introduction to Recursion (Python)
PDF
Python Unit 3 - Control Flow and Functions
ODP
PPTX
13 Strings and Text Processing
ODP
Python course Day 1
PDF
Python for data science by www.dmdiploma.com
PPTX
Chapter 22. Lambda Expressions and LINQ
PPTX
Unit2 input output
PDF
Python Puzzlers - 2016 Edition
PPTX
Python programming workshop session 1
PPTX
07. Java Array, Set and Maps
PDF
Python-02| Input, Output & Import
Python Programming Essentials - M16 - Control Flow Statements and Loops
Python programming Workshop SITTTR - Kalamassery
Introduction to Python and TensorFlow
FUNCTIONS IN PYTHON. CBSE +2 COMPUTER SCIENCE
Programming Homework Help
Advanced Python, Part 2
13. Java text processing
Introduction to Recursion (Python)
Python Unit 3 - Control Flow and Functions
13 Strings and Text Processing
Python course Day 1
Python for data science by www.dmdiploma.com
Chapter 22. Lambda Expressions and LINQ
Unit2 input output
Python Puzzlers - 2016 Edition
Python programming workshop session 1
07. Java Array, Set and Maps
Python-02| Input, Output & Import
Ad

Viewers also liked (20)

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

Similar to Introduction to python (20)

PPTX
Python basic
PDF
cel shading as PDF and Python description
PPT
Profiling and optimization
PDF
Python Performance 101
PDF
8799.pdfOr else the work is fine only. Lot to learn buddy.... Improve your ba...
PDF
Or else the work is fine only. Lot to learn buddy.... Improve your basics in ...
PDF
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
PPTX
Python Workshop - Learn Python the Hard Way
DOCX
Mcq cpup
PPTX
Introduction to python programming 1
PDF
仕事で使うF#
PPTX
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
PPTX
美洲杯买球-美洲杯买球怎么押注-美洲杯买球押注怎么玩|【​网址​🎉ac99.net🎉​】
PPTX
欧洲杯足彩-欧洲杯足彩线上体育买球-欧洲杯足彩买球推荐网站|【​网址​🎉ac55.net🎉​】
PPTX
欧洲杯下注-欧洲杯下注买球网-欧洲杯下注买球网站|【​网址​🎉ac10.net🎉​】
PPTX
世预赛买球-世预赛买球比赛投注-世预赛买球比赛投注官网|【​网址​🎉ac10.net🎉​】
PPTX
世预赛投注-世预赛投注投注官网app-世预赛投注官网app下载|【​网址​🎉ac123.net🎉​】
PPTX
欧洲杯体彩-欧洲杯体彩比赛投注-欧洲杯体彩比赛投注官网|【​网址​🎉ac99.net🎉​】
PPTX
欧洲杯买球-欧洲杯买球投注网-欧洲杯买球投注网站|【​网址​🎉ac44.net🎉​】
PPTX
Python 표준 라이브러리
Python basic
cel shading as PDF and Python description
Profiling and optimization
Python Performance 101
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 ...
PYTHONOr else the work is fine only. Lot to learn buddy.... Improve your basi...
Python Workshop - Learn Python the Hard Way
Mcq cpup
Introduction to python programming 1
仕事で使うF#
世预赛买球-世预赛买球竞彩平台-世预赛买球竞猜平台|【​网址​🎉ac123.net🎉​】
美洲杯买球-美洲杯买球怎么押注-美洲杯买球押注怎么玩|【​网址​🎉ac99.net🎉​】
欧洲杯足彩-欧洲杯足彩线上体育买球-欧洲杯足彩买球推荐网站|【​网址​🎉ac55.net🎉​】
欧洲杯下注-欧洲杯下注买球网-欧洲杯下注买球网站|【​网址​🎉ac10.net🎉​】
世预赛买球-世预赛买球比赛投注-世预赛买球比赛投注官网|【​网址​🎉ac10.net🎉​】
世预赛投注-世预赛投注投注官网app-世预赛投注官网app下载|【​网址​🎉ac123.net🎉​】
欧洲杯体彩-欧洲杯体彩比赛投注-欧洲杯体彩比赛投注官网|【​网址​🎉ac99.net🎉​】
欧洲杯买球-欧洲杯买球投注网-欧洲杯买球投注网站|【​网址​🎉ac44.net🎉​】
Python 표준 라이브러리

More from Marian Marinov (20)

PDF
How to start and then move forward in IT
PDF
Thinking about highly-available systems and their setup
PDF
Understanding your memory usage under Linux
PDF
How to implement PassKeys in your application
PDF
Dev.bg DevOps March 2024 Monitoring & Logging
PDF
Basic presentation of cryptography mechanisms
PDF
Microservices: Benefits, drawbacks and are they for me?
PDF
Introduction and replication to DragonflyDB
PDF
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
PDF
How to successfully migrate to DevOps .pdf
PDF
How to survive in the work from home era
PDF
Managing sysadmins
PDF
Improve your storage with bcachefs
PDF
Control your service resources with systemd
PDF
Comparison of-foss-distributed-storage
PDF
Защо и как да обогатяваме знанията си?
PDF
Securing your MySQL server
PDF
Sysadmin vs. dev ops
PDF
DoS and DDoS mitigations with eBPF, XDP and DPDK
PDF
Challenges with high density networks
How to start and then move forward in IT
Thinking about highly-available systems and their setup
Understanding your memory usage under Linux
How to implement PassKeys in your application
Dev.bg DevOps March 2024 Monitoring & Logging
Basic presentation of cryptography mechanisms
Microservices: Benefits, drawbacks and are they for me?
Introduction and replication to DragonflyDB
Message Queuing - Gearman, Mosquitto, Kafka and RabbitMQ
How to successfully migrate to DevOps .pdf
How to survive in the work from home era
Managing sysadmins
Improve your storage with bcachefs
Control your service resources with systemd
Comparison of-foss-distributed-storage
Защо и как да обогатяваме знанията си?
Securing your MySQL server
Sysadmin vs. dev ops
DoS and DDoS mitigations with eBPF, XDP and DPDK
Challenges with high density networks

Recently uploaded (20)

PDF
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
PDF
Top 10 read articles In Managing Information Technology.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
PDF
Structs to JSON How Go Powers REST APIs.pdf
PPTX
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
PPTX
TE-AI-Unit VI notes using planning model
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
Internship_Presentation_Final engineering.pptx
PPTX
anatomy of limbus and anterior chamber .pptx
PPT
Chapter 6 Design in software Engineeing.ppt
PPTX
Practice Questions on recent development part 1.pptx
PPTX
24AI201_AI_Unit_4 (1).pptx Artificial intelligence
PPTX
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
PPTX
Glazing at Facade, functions, types of glazing
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
436813905-LNG-Process-Overview-Short.pptx
Geotechnical Engineering, Soil mechanics- Soil Testing.pdf
Top 10 read articles In Managing Information Technology.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
SM_6th-Sem__Cse_Internet-of-Things.pdf IOT
Structs to JSON How Go Powers REST APIs.pdf
Unit 5 BSP.pptxytrrftyyydfyujfttyczcgvcd
TE-AI-Unit VI notes using planning model
Operating System & Kernel Study Guide-1 - converted.pdf
bas. eng. economics group 4 presentation 1.pptx
Internship_Presentation_Final engineering.pptx
anatomy of limbus and anterior chamber .pptx
Chapter 6 Design in software Engineeing.ppt
Practice Questions on recent development part 1.pptx
24AI201_AI_Unit_4 (1).pptx Artificial intelligence
MET 305 MODULE 1 KTU 2019 SCHEME 25.pptx
Glazing at Facade, functions, types of glazing
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
OOP with Java - Java Introduction (Basics)
436813905-LNG-Process-Overview-Short.pptx

Introduction to python