Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Python Overview
Installation, Data types, Control flow structures,
Loops, Functions, Strings, OOP, Data Structures,
Tuples, Destructuring Assignments
Python Overview
Telerik Academy Plus
http://academy.telerik.com
Table of Contents
Python Overview
Installing Python
Python IDEs
Data types
Control flow structures
Loops
Data Structures and comprehensions
Lists, sets, dictionaries and tuples
Destructuring assignments
Table of Contents
Functions
Lambda functions
Modules
Object-oriented programming
Creating classes
Properties, instance and class methods
Inheritance
Best Practices
The Zen of Python
Python Overview
What is Python? What can be used for?
Python Overview
Python is a widely used general-purpose, high-
level programming language
Its design philosophy emphasizes code
readability
Its syntax allows programmers to express
concepts in fewer lines of code
The language provides constructs intended to
enable clear programs on both a small and large
scale
Python Overview
Python supports multiple programming
paradigms, including
Object-oriented
Imperative and functional programming
It features a dynamic type system and automatic
memory management
Python is widely used for:
Web applications development: Django, Pyramid
Games with PyGame
Automations scripts, Sikuli
And more
Installing Python
On MAC, Linux and Windows
Installing Python
On MAC
Homebrew can be used
$ brew install python
On Linux
Part of Linux is built with Python, so it comes outof-the-box
On Windows
Download the installer from https://www.python.org/
Add the installation path to System Variables $PATH
Installing Python on
Windows and MAC
Live Demo
Running Python in REPL
Open the CMD/Terminal and run:
You can run python code:
Print the numbers from 0 to 4
for i in range(5):
print(i)
Sum the numbers from 5 to 9
sum = 0
for i in range(5, 10):
sum += i
print(sum)
$ python
Running Python
Open the CMD/Terminal and run:
You can run python code:
Print the numbers from 0 to 4
for i in range(5):
print(i)
Sum the numbers from 5 to 9
sum = 0
for i in range(5, 10):
sum += i
print(sum)
Significant whitespace
matters a lot
$ python
Significant Whitespace
Significant whitespace is a way to write code in
python
This is actually the indentation
Significant whitespace creates blocks in
python code
It is the equivalent of curly brackets ({}) in
other languages
Good practices say "Use four spaces for indent"
Python IDEs
Sublime Text, PyCharm, REPL
Python IDEs
Python is quite popular and there are my IDEs:
PyCharm
Commercial and Community editions
Ready-to-use
Sublime Text
Free, open-source
Needs plugins and some setup to work properly
LiClipse
Free, based on Eclipse
Ready-to-use
Python IDEs
Live Demo
Data types in Python
int, float, etc
Data types in Python
Python supports all the primary
data types:
int – integer numbers
int(intAsString) parses a string to int
float – floating-point numbers
float(floatAsString) parses a string to float
None – like null
bool – Boolean values (True and False)
str – string values (sequence of characters)
Data Types
Live Demo
Control Flow Structures
If-elif-else
Control Flow Structures
Python supports conditionals:
if conditionOne:
# run code if conditionOne is True
elif conditionTwo:
# run code if conditionOne is False
#
but conditionTwo is True
else
# run code if conditionOne and
#
conditionTwo are False
The conditions are True-like and False-like
""(empty string), 0, None are evaluated to False
Non-empty strings, any number or object are
evaluated to True
Conditional Statements
Live Demo
Loops
for and while
Loops
There are two types of loops in Python
for loop
for i in range(5):
# run code with values of i: 0, 1, 2, 3 and 4
names = ['Doncho', 'Asya', 'Evlogi', 'Nikolay', 'Ivaylo']
for i in range(len(names)):
print('Hi! I am %s!'%names[i]);
while loop
number = 1024
binNumber = '';
while number >= 1:
binNumber += '%i'%(number%2)
number /= 2
print(binNumber[::-1])
Loops
Live Demo
Data Structures
Lists, Dictionaries, Sets
Data Structures in Python
Python has three primary data structures
List
Keep a collection of objects
Objects can be accessed and changed by index
Objects can be appended/removed dynamically
Dictionary
Keep a collection of key-value pairs
Values are accessed by key
The key can be of any type
Sets
Keep a collection of unique objects
Lists in Python
Collections of objects
Lists in Python
Lists are created using square brackets
('[' and ']'):
numbers = [1, 2, 3, 4, 5, 6, 7]
names = ["Doncho", "Niki", "Ivo", "Evlogi"]
Print a list of items:
Object by object
for name in names:
print(name)
Or by index:
for index in len(names):
print(names[index])
Add new object to the list:
names.append("Asya")
Lists in Python
Live Demo
List Comprehensions
List comprehensions are a easier way
to create
lists with values
They use the square brackets ('[' and ']') and
an expression inside
even = [number for number in numbers if not number % 2]
longerNames = [name for name in names if len(name) > 6]
kNames = [name for name in names if name.startswith("K")]
[eat(food) for food in foods if food is not "banana"]
List Comprehensions
Live Demo
Sets in Python
Collections of unique values
Sets in Python
Sets are created like lists,
but using curly
brackets instead of square
They contain unique values
i.e. each value can be contained only once
__eq__(other) methods is called for each object
names = {"Doncho", "Nikolay"}
names.add("Ivaylo")
names.add("Evlogi")
names.add("Doncho")
print(names)
# the result is {'Nikolay', 'Ivaylo', 'Evlogi', 'Doncho'}
# 'Doncho' is contained only once
Sets in Python
Live Demo
Set Comprehensions
Set comprehensions are exactly like list
comprehensions
But contain only unique values
sentence = "Hello! My name is Doncho Minkov and …"
parts = re.split("[,!. ]", sentence)
words = {word.lower() for word in parts if word is not ""}
Set Comprehensions
Live Demo
Dictionaries in Python
Key-value pairs
Dictionaries in Python
Dictionary is a collection of key-value pairs
The key can be of any type
For custom types, the methods __hash__() and
__eq__(other) must be overloaded
Values can be of any type
Even other dictionaries or lists
musicPreferences = {
"Rock": ["Peter", "Georgi"],
"Pop Folk": ["Maria", "Teodor"],
"Blues and Jazz": ["Alex", "Todor"],
"Pop": ["Nikolay", "Ivan", "Elena"]
}
Dictionaries in Python
Live Demo
Dictionary Comprehensions
Dictionary
comprehensions follow pretty much
the same structure as list comprehensions
Just use curly brackets {} instead of square []
Provide the pair in the format key: value
names = {trainer.name for trainer in trainers}
trainersSkills = { name: [] for name in names}
{trainersSkills[trainer.name].append(trainer.skill)
for trainer in trainers}
Dictionary Comprehensions
Live Demo
Tuples
Tuples in Python
A tuple is a sequence of immutable objects
Much like lists, but their values cannot be
changed
Use parenthesis instead of square brackets
languages = ("Python", "JavaScript", "Swift")
for lang in languages:
print(lang)
print("Number of languages: {0}".format(len(languages))
Tuples
Live Demo
Operations with Tuples
The following operations are supported for tuples:
Get the length of the tuple:
len((-1, 5, 11)) # returns 3
Concatenate tuples:
(1, 2) + (7, 8, 9) # returns (1, 2, 7, 8, 9)
Multiply by number:
(1,)*5 # returns (1, 1, 1, 1, 1)
Check for value:
3 in (1, 2, 3) # returns True
Operations with Tuples
Live Demo
Destructuring Assignments
Destructuring Assignments
Destructuring assignments (bind) allow
easier
extracting of values
With tuples
x, y = 1, 5 # equivalent to x = 1 and y = 5
x, y = y, x # swap the values
With arrays
numbers = [1, 2]
[one, two] = numbers
numbers = list(range(1, 10))
[first, *middle, last] = numbers
Destructuring Assignments
Live Demo
Functions in Python
Separate the code in smaller and reusable pieces
Functions in Python
Functions in Python:
Are defined using the keyword "def"
Have an identifier
A list of parameters
A return type
def toBin(number):
bin = ''
while number >= 1:
bin += '%i'%(number%2)
number /= 2
return bin[::-1]
Functions in Python
Live Demo
Anonymous Functions
Python allows
the creation of anonymous
functions (lambda functions)
Using the keyword lambda and a special syntax:
printMsg = lambda msg: print('Message: {0}'.format(msg))
Same as:
def printMsg2(msg):
print('Message: {0}'.format(msg))
Mostly used for data structures manipulation
evenNumbers = filter(lambda n: not n%2, numbers)
Lambda Functions
Live Demo
Modules in Python
How to separate the code in different modules
Modules in Python
Python applications are separated into modules
These module represent just a list of functions
and/or classes
To use all functions from a module numeralSystems:
import numeralSystems
print(numeralSystems.toBin(1023))
print(numeralSystems.toHex(1023))
A single function:
from numeralSystems import toBin as bin
Or some functions
from numeralSystems import toBin as bin, toHex as hex
Modules in Python
Live Demo
Object-oriented Programming
With Python
Object-oriented Programming
with Python
Python is an object-oriented language
Support for classes, inheritance, method
overloading, etc…
To create a class:
Use the keyword class
Give the class a name
Define __init__ method and other methods
Attributes (fields) are defined inside
the contructor (__init__) method
class Presentation:
def __init__(self, title, duration):
self.title = title
self.duration = duration
Creating Classes
with Python
Live Demo
Properties in Python
Python has a concept for providing properties for
class attributes
Properties are used for data hiding and validation
of the input values
class Presentation:
def __init__(self, title, duration):
self.title = title
self.duration = duration
@property
def duration(self):
return self._duration
@duration.setter
def duration(self, value):
if(0 < duration and duration <= 4):
self._duration = value
Classes with Properties
Live Demo
Instance methods
Instance methods are methods that are used
on a concrete instance of the class
To create an instance method, provide
self as
first parameter to the method:
class Trainer(Person):
# …
def deliver(self, presentation):
print("{0} is delivering presentation about {1}"
.format(self.name, presentation.title))
Instance methods
Instance methods are methods that are used
on a concrete instance of the class
To create an instance method, provide
self as
first parameter to the method:
class Trainer(Person):
# …
def deliver(self, presentation):
print("{0} is delivering presentation about {1}"
.format(self.name, presentation.title))
self is like this
for other languages
Instance Methods
Live Demo
Class Methods
Class
methods are shared between all
instances of the class, and other objects
They are used on the class, instead of on
concrete object
Defined as regular functions
But inside the class
Without self as parameter
class Person:
# …
def validate_person_age(age):
return 0 < age and age < 150
Class Methods
Live Demo
Class Inheritance in Python
Extend classes
Class Inheritance in Python
Class inheritance is the process of creating a class
that extends the state and behavior of other class
Functions and attributes are inherited
New functions and attributes can be added
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Trainer(Person):
def __init__(self, name, age, speciality):
super().__init__(name, age)
self.speciality = speciality
def deliver(self, presentation):
print("{0} is delivering presentation about {1}"
.format(self.name, presentation.title))
Class Inheritance in Python
Class inheritance is the process of creating a class
that extends the state and behavior of other class
Functions and attributes are inherited
New functions and attributes can be added
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
Trainer inherits Person
class Trainer(Person):
def __init__(self, name, age, speciality):
super().__init__(name, age)
self.speciality = speciality
def deliver(self, presentation):
print("{0} is delivering presentation about {1}"
.format(self.name, presentation.title))
Class Inheritance in Python
Class inheritance is the process of creating a class
that extends the state and behavior of other class
Functions and attributes are inherited
New functions and attributes can be added
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
class Trainer(Person):
def __init__(self, name, age, speciality):
super().__init__(name, age)
super() calls
self.speciality = speciality
the parent
def deliver(self, presentation):
print("{0} is delivering presentation about {1}"
.format(self.name, presentation.title))
Class Inheritance in Python
Live Demo
Best Practices
How to write readable Python code?
Best Practices
Use 4-space indentation, and no tabs
Wrap lines so that they don’t exceed 79 characters
Use blank lines to separate functions and classes
Use docstrings
Use spaces around operators and after commas
Name your classes and functions consistently
PascalCase for classes
lower_case_with_underscores for functions and
methods
The Zen of Python
Python Overview
курсове и уроци по програмиране, уеб дизайн – безплатно
курсове и уроци по програмиране – Телерик академия
уроци по програмиране и уеб дизайн за ученици
програмиране за деца – безплатни курсове и уроци
безплатен SEO курс - оптимизация за търсачки
курсове и уроци по програмиране, книги – безплатно от Наков
уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop
free C# book, безплатна книга C#, книга Java, книга C#
безплатен курс "Качествен програмен код"
безплатен курс "Разработка на софтуер в cloud среда"
BG Coder - онлайн състезателна система - online judge
форум програмиране, форум уеб дизайн
ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET
ASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC
алго академия – състезателно програмиране, състезания
курс мобилни приложения с iPhone, Android, WP7, PhoneGap
Дончо Минков - сайт за програмиране
Николай Костов - блог за програмиране
C# курс, програмиране, безплатно
http://academy.telerik.com