Download presentation
Presentation is loading. Please wait.
Published byLily Mason Modified over 9 years ago
1
Installation, Data types, Control flow structures, Loops, Functions, Strings, OOP, Data Structures, Tuples, Destructuring Assignments Telerik Academy Plus http://academy.telerik.com Python Overview
2
Python Overview Installing Python Python IDEs Data types Control flow structures Loops Data Structures and comprehensions Lists, sets, dictionaries and tuples Destructuring assignments
3
Functions Lambda functions Modules Object-oriented programming Creating classes Properties, instance and class methods Inheritance Best Practices The Zen of Python
4
What is Python? What can be used for?
5
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
6
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
7
On MAC, Linux and Windows
8
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/ https://www.python.org/ Add the installation path to System Variables $PATH
9
Live Demo
10
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) print(i) sum = 0 for i in range(5, 10): sum += i sum += iprint(sum) Sum the numbers from 5 to 9
11
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) print(i) sum = 0 for i in range(5, 10): sum += i sum += iprint(sum) Sum the numbers from 5 to 9 Significant whitespace matters a lot
12
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"
13
Sublime Text, PyCharm, REPL
14
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 proper ly LiClipse Free, based on Eclipse Ready-to-use
15
Live Demo
16
int, float, etc
17
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)
18
Live Demo
19
If-elif-else
20
Python supports conditionals: if conditionOne: # run code if conditionOne is True # run code if conditionOne is True elif conditionTwo: # run code if conditionOne is False # run code if conditionOne is False # but conditionTwo is True # 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
21
Live Demo
22
for and while
23
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 # 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]); print('Hi! I am %s!'%names[i]); while loop number = 1024 binNumber = ''; while number >= 1: binNumber += '%i'%(number%2) binNumber += '%i'%(number%2) number /= 2 number /= 2print(binNumber[::-1])
24
Live Demo
25
Lists, Dictionaries, Sets
26
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
27
Collections of objects
28
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) print(name) Add new object to the list: names.append("Asya") Or by index: for index in len(names): print(names[index]) print(names[index])
29
Live Demo
30
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"]
31
Live Demo
32
Collections of unique values
33
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
34
Live Demo
35
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 ""}
36
Live Demo
37
Key-value pairs
38
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"], "Rock": ["Peter", "Georgi"], "Pop Folk": ["Maria", "Teodor"], "Pop Folk": ["Maria", "Teodor"], "Blues and Jazz": ["Alex", "Todor"], "Blues and Jazz": ["Alex", "Todor"], "Pop": ["Nikolay", "Ivan", "Elena"] "Pop": ["Nikolay", "Ivan", "Elena"]}
39
Live Demo
40
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} for trainer in trainers}
41
Live Demo
43
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(lang) print("Number of languages: {0}".format(len(languages))
44
Live Demo
45
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
46
Live Demo
48
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
49
Live Demo
50
Separate the code in smaller and reusable pieces
51
Functions in Python: Are defined using the keyword "def" Have an identifier A list of parameters A return type def toBin(number): bin = '' bin = '' while number >= 1: while number >= 1: bin += '%i'%(number%2) bin += '%i'%(number%2) number /= 2 number /= 2 return bin[::-1] return bin[::-1]
52
Live Demo
53
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)) print('Message: {0}'.format(msg)) Mostly used for data structures manipulation evenNumbers = filter(lambda n: not n%2, numbers)
54
Live Demo
55
How to separate the code in different modules
56
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)) from numeralSystems import toBin as bin A single function: Or some functions from numeralSystems import toBin as bin, toHex as hex
57
Live Demo
58
With Python
59
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): def __init__(self, title, duration): self.title = title self.title = title self.duration = duration self.duration = duration
60
Live Demo
61
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): def __init__(self, title, duration): self.title = title self.title = title self.duration = duration self.duration = duration @property @property def duration(self): def duration(self): return self._duration return self._duration @duration.setter @duration.setter def duration(self, value): def duration(self, value): if(0 < duration and duration <= 4): if(0 < duration and duration <= 4): self._duration = value self._duration = value
62
Live Demo
63
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): def deliver(self, presentation): print("{0} is delivering presentation about {1}" print("{0} is delivering presentation about {1}".format(self.name, presentation.title)).format(self.name, presentation.title))
64
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): def deliver(self, presentation): print("{0} is delivering presentation about {1}" print("{0} is delivering presentation about {1}".format(self.name, presentation.title)).format(self.name, presentation.title)) self is like this for other languages
65
Live Demo
66
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): def validate_person_age(age): return 0 < age and age < 150 return 0 < age and age < 150
67
Live Demo
68
Extend classes
69
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): def __init__(self, name, age): self.name = name self.name = name self.age = age self.age = age class Trainer(Person): def __init__(self, name, age, speciality): def __init__(self, name, age, speciality): super().__init__(name, age) super().__init__(name, age) self.speciality = speciality self.speciality = speciality def deliver(self, presentation): def deliver(self, presentation): print("{0} is delivering presentation about {1}" print("{0} is delivering presentation about {1}".format(self.name, presentation.title)).format(self.name, presentation.title))
70
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): def __init__(self, name, age): self.name = name self.name = name self.age = age self.age = age class Trainer(Person): def __init__(self, name, age, speciality): def __init__(self, name, age, speciality): super().__init__(name, age) super().__init__(name, age) self.speciality = speciality self.speciality = speciality def deliver(self, presentation): def deliver(self, presentation): print("{0} is delivering presentation about {1}" print("{0} is delivering presentation about {1}".format(self.name, presentation.title)).format(self.name, presentation.title)) Trainer inherits Person
71
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): def __init__(self, name, age): self.name = name self.name = name self.age = age self.age = age class Trainer(Person): def __init__(self, name, age, speciality): def __init__(self, name, age, speciality): super().__init__(name, age) super().__init__(name, age) self.speciality = speciality self.speciality = speciality def deliver(self, presentation): def deliver(self, presentation): print("{0} is delivering presentation about {1}" print("{0} is delivering presentation about {1}".format(self.name, presentation.title)).format(self.name, presentation.title)) super() calls the parent
72
Live Demo
73
How to write readable Python code?
74
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
76
форум програмиране, форум уеб дизайн курсове и уроци по програмиране, уеб дизайн – безплатно програмиране за деца – безплатни курсове и уроци безплатен 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# Николай Костов - блог за програмиране http://academy.telerik.com
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.