installation, data types, control flow structures, loops, functions, strings, oop, data structures,...

Post on 24-Dec-2015

230 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Python OverviewInstallation, Data types, Control flow structures,

Loops, Functions, Strings, OOP, Data Structures, Tuples, Destructuring Assignments

Telerik Academy Plushttp://academy.telerik.com

Python Overview

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 OverviewWhat 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 PythonOn 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 out-of-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

$ python

for i in range(5): print(i)

sum = 0for i in range(5, 10): sum += iprint(sum)

Sum the numbers from 5 to 9

Running Python Open the CMD/Terminal and run: You can run python code:

Print the numbers from 0 to 4

$ python

for i in range(5): print(i)

sum = 0for i in range(5, 10): sum += iprint(sum)

Sum the numbers from 5 to 9

Significant whitespace

matters a lot

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 IDEsSublime 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 IDEsLive Demo

Data types in Pythonint, 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 TypesLive Demo

Control Flow Structures

If-elif-else

Control Flow Structures Python supports conditionals:

if conditionOne: # run code if conditionOne is Trueelif conditionTwo: # run code if conditionOne is False # but conditionTwo is Trueelse # 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

Loopsfor and while

Loops There are two types of loops in Python for loopfor 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 loopnumber = 1024binNumber = '';while number >= 1: binNumber += '%i'%(number%2) number /= 2print(binNumber[::-1])

LoopsLive Demo

Data StructuresLists, 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 PythonCollections 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)

Add new object to the list:names.append("Asya")

Or by index:for index in len(names): print(names[index])

Lists in PythonLive Demo

List Comprehensions

List comprehensions are a easier way to create lists with values They use the square brackets ('['

and ']') and an expression insideeven = [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 ComprehensionsLive Demo

Sets in PythonCollections 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 PythonLive 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 ComprehensionsLive 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 PythonLive 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))

TuplesLive Demo

Operations with Tuples

The following operations are supported for tuples: Get the length of the tuple:len((-1, 5, 11)) # returns 3

(1, 2) + (7, 8, 9) # returns (1, 2, 7, 8, 9)

Concatenate tuples:

(1,)*5 # returns (1, 1, 1, 1, 1)

Multiply by number:

Check for value:3 in (1, 2, 3) # returns True

Operations with TuplesLive Demo

Destructuring Assignments

Destructuring Assignments

Destructuring assignments (bind) allow easier extracting of values With tuples

With arrays

x, y = 1, 5 # equivalent to x = 1 and y = 5 x, y = y, x # swap the values

numbers = [1, 2][one, two] = numbers

numbers = list(range(1, 10))[first, *middle, last] = numbers

Destructuring Assignments

Live Demo

Functions in PythonSeparate 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 PythonLive 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 manipulationevenNumbers = filter(lambda n: not n%2, numbers)

Lambda FunctionsLive Demo

Modules in PythonHow 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 numeralSystemsprint(numeralSystems.toBin(1023))print(numeralSystems.toHex(1023))

from numeralSystems import toBin as bin

A single function:

Or some functions

from numeralSystems import toBin as bin, toHex as hex

Modules in PythonLive 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__) methodclass 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 valuesclass 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 MethodsLive 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 parameterclass Person: # … def validate_person_age(age): return 0 < age and age < 150

Class MethodsLive 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

addedclass 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

addedclass 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))

Trainer inherits Person

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

addedclass 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))

super() calls the

parent

Class Inheritance in PythonLive Demo

Best PracticesHow 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

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезания

ASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NETкурсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGap

free C# book, безплатна книга C#, книга Java, книга C#Дончо Минков - сайт за програмиранеНиколай Костов - блог за програмиранеC# курс, програмиране, безплатно

?

? ? ??

?? ?

?

?

?

??

?

?

? ?

Questions?

?

Python Overview

http://academy.telerik.com

top related