First Tool: Python! Introduction to python programming - - PowerPoint PPT Presentation

first tool python
SMART_READER_LITE
LIVE PREVIEW

First Tool: Python! Introduction to python programming - - PowerPoint PPT Presentation

First Tool: Python! Introduction to python programming Gholamhossein Tavasoli @ ZNU First Tool: Python! Python Programming Language Python Programming Language Created in 1991 by Guido van Rossum Python Cro ross Platform Pro rogramming


slide-1
SLIDE 1

First Tool: Python!

Introduction to python programming Gholamhossein Tavasoli @ ZNU

slide-2
SLIDE 2

First Tool: Python!

slide-3
SLIDE 3

Python

Programming Language

slide-4
SLIDE 4

Python

Programming Language Created in 1991 by Guido van Rossum

slide-5
SLIDE 5

Python

Programming Language Created in 1991 by Guido van Rossum Cro ross Platform Pro rogramming Lan angua uage

slide-6
SLIDE 6

Python

Programming Language Created in 1991 by Guido van Rossum Cro ross Platform Pro rogramming Lan angua uage Freely Usable Even for Commercial Use

slide-7
SLIDE 7

6 Lessons from Dropbox

  • One Million Files Saved Every 15 minutes (2011)
  • Use Pyt

ython

  • 99.9 % of their code is in Python
  • server backend
  • desktop client
  • website controller logic
  • API backend
  • analytics
  • Can't use Python on the Android due to memory constraints
  • Runs on a single code base using Python. Dropbox runs on Win

indows, Mac, Lin inux using tools like PyObjs, WxPython, types, py2exe, py2app, PyWin32.

slide-8
SLIDE 8

6 Lessons from Dropbox

  • Pros
  • Developers talk to each other and express ideas in Python
  • Easy to learn, easy to read, easy to write, easy for new

people to pick up.

  • Cons
  • OK, it can use too much memory and be too slow.
  • Coding in a mixed environment of Python and C creates

problems

  • Memory fragmentation issues are reason why scripting

languages may not be a good idea for long running processes

slide-9
SLIDE 9

6 Lessons from Dropbox

  • Just W

Work Baby

  • Shouldn't matter what file system you are on, what

OS you are using, what applications you are using. The product should always just work.

  • Python helped them iterate fast through all the

different error cases they experienced on the wide variety of platforms they support.

slide-10
SLIDE 10

6 Lessons from Dropbox

  • Release Early
  • Code something in a day and release it. Python

makes that easy.

slide-11
SLIDE 11

6 Lessons from Dropbox

  • Use C f

for In Inner Loops - Optimizing CPU is easy

  • Poll - Polling 30

30 Milion Clients A All O Over the World Doesn't 't Scale

  • Custom Memory

ry Allocator - Optimizing Memory ry is Hard

slide-12
SLIDE 12

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

slide-13
SLIDE 13

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

slide-14
SLIDE 14

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } }

slide-15
SLIDE 15

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

public class Main { public static void main(String[] args) { System.out.println("Hello world!"); } } print("Hello world!")

slide-16
SLIDE 16

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

slide-17
SLIDE 17

Big names using Python

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

slide-18
SLIDE 18

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

https://opencv .org/ Image Processing using Python

slide-19
SLIDE 19

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

https://www.pygame.org Game Development using Python

slide-20
SLIDE 20

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

https://matplotlib.org/ Data Science using Python

slide-21
SLIDE 21

print("Python" + " is " + "cool!")

"Python is easy to use, powerful, and versatile, making it a great choice for beginners and experts alike." – codeschool.com

https://github.com/amueller/word_cloud Natural Language Processing (NLP) and T ext Mining using Python

slide-22
SLIDE 22

Python Setup

  • https://www.python.org/downloads/
slide-23
SLIDE 23

Python Setup

  • Pyt

ython(x,y ,y) ) - https://pyt ython-xy.github.i .io/

slide-24
SLIDE 24

Python Command Line

  • Using command line
  • Python script in file
  • comment
  • Environment variables (Windows)
  • modules
  • import sys
  • sys.argv
  • dir(sys)
  • help(sys)
  • help(sys.exit)
slide-25
SLIDE 25

Variables and Data Types

slide-26
SLIDE 26

Variables and Data Types

  • Variables store and give names to data values
  • Data values can be of various types:
  • int
  • 5, 0, 1000000
  • float
  • 2.0, 3.14159
  • bool

True, False

  • str

"Hello world!", "K3WL"

  • list

[1, 2, 3, 4], ["Hello", "world!"], [1, 2, "Hello"], [ ]

  • In Python, variables do not have types!
slide-27
SLIDE 27

Conditionals and Loops

27

slide-28
SLIDE 28

Conditionals and Loops

slide-29
SLIDE 29

Conditionals and Loops

  • Cores of programming!
  • Rely on boolean expressions which return either True or False
  • 1 < 2 : True
  • 1.5 >= 2.5 : Fals

lse

  • answer == "Computer Science" : can be True or Fals

lse depending on the value of variable answer

  • Boolean expressions can be combined with: and

and, or

  • r, not
  • 1 < 2 and 3 < 4 : True
  • 1.5 >= 2.5 or 2 == 2 : True
  • not 1.5 >= 2.5 : True
slide-30
SLIDE 30

Conditionals and Loops

if boolean-expression-1: code-block-1 elif boolean-expression-2: code-block-2 (as many elif's as you want) else: code-block-last

slide-31
SLIDE 31

Conditionals and Loops

grade = int(raw_input("Numeric grade: ")) if grade >= 80: print("A") elif grade >= 65: print("B") elif grade >= 55: print("C") else: print("E")

slide-32
SLIDE 32

Loops

  • Useful for repeating code!
  • Two variants:
slide-33
SLIDE 33

While Loops

slide-34
SLIDE 34

For Loops

  • So far, we have seen (briefly) two kinds of collections:

string and list

  • For loops can be used to visit e

each collection's 's element:

slide-35
SLIDE 35

Functions

35

slide-36
SLIDE 36
  • Functions encapsulate code blocks
  • Why functions? Modularization and reuse!
  • Y
  • u actually have seen examples of functions:
  • print()
  • raw_input()
  • Generic form:

def function-name(parameters): code-block return value

Functions

36

slide-37
SLIDE 37

def celsius_to_fahrenheit(celsius): fahrenheit = celsius * 1.8 + 32.0 return fahrenheit

def function-name(parameters): code-block return value

Functions: Celcius to Fahrenheit

slide-38
SLIDE 38

38

Functions: Default and Named Parameters

def hello(name_man="Bro", name_woman="Sis"): print("Hello, " + name_man + " & " + name_woman + "!") >>> hello() Hello, Bro & Sis! >>> hello(name_woman="Lady") Hello, Bro & Lady! >>> hello(name_woman="Mbakyu",name_man="Mas") Hello, Mas & Mbakyu!

slide-39
SLIDE 39

Imports

  • Code made by other people shall be reused!
  • Two ways of importing modules (= Python files):
  • Generic form: import module_name

import math print(math.sqrt(4))

  • Generic form: from module_name import function_name

from math import sqrt print(sqrt(4))

slide-40
SLIDE 40

Strings

40

slide-41
SLIDE 41

String

  • String is a sequence of characters, like "Python is cool"
  • Each character has an index
  • Accessing a character: string[index]

x = "Python is cool" print(x[10])

  • Accessing a substring via slicing: string[start:finish]

print(x[2:6])

P y t h

  • n

i s c

  • l

1 2 3 4 5 6 7 8 9 10 11 12 13

slide-42
SLIDE 42

42

>>> x = "Python is cool" >>> "cool" in x >>> len(x) >>> x + "?" >>> x.upper() # membership # length of string x # concatenation # to upper case >>> x.replace("c", "k") # replace characters in a string

String Operations

P y t h

  • n

i s c

  • l

1 2 3 4 5 6 7 8 9 10 11 12 13 >>> “Hi %s” % name # parameters in a string

slide-43
SLIDE 43

>>> x = "Python is cool"

String Operations: Split

x.split(" ")

>>> x.split(" ")

43

P y t h

  • n

i s c

  • l

1 2 3 4 5 6 7 8 9 10 11 12 13 P y t h

  • n

1 2 3 4 5 i s 1 c

  • l

1 2 3

slide-44
SLIDE 44

>>> x = "Python is cool" >>> y = x.split(" ")

String Operations: Join

",".join(y)

>>> ",".join(y)

40

P y t h

  • n

, i s , c

  • l

1 2 3 4 5 6 7 8 9 10 11 12 13 P y t h

  • n

1 2 3 4 5 i s 1 c

  • l

1 2 3

slide-45
SLIDE 45

Input/Output

45

slide-46
SLIDE 46
  • Working with data heavily involves reading and writing!
  • Data come in two types:
  • T

ext: Human readable, encoded in ASCII/UTF-8, example: .txt, .csv

  • Binary: Machine readable, application-specific encoding,

example: .mp3, .mp4, .jpg

Input/Output

46

slide-47
SLIDE 47

python is cool

Input

cool.txt

x = open("cool.txt", "r") # read mode y = x.read() # read the whole print(y) x.close()

47

slide-48
SLIDE 48

python is cool

cool.txt

x = open("cool.txt", "r")

44

Input

line = line.replace("\n","") print(line) x.close() # read line by line for line in x:

slide-49
SLIDE 49

python is cool

Input

cool.txt

x = open("C:\\Users\\Fariz\\cool.txt", "r") # absolute location for line in x: line = line.replace("\n","") print(line) x.close()

49

slide-50
SLIDE 50

Output

# write mode x = open("carpe-diem.txt", "w") x.write("carpe\ndiem\n") x.close() # append mode x = open("carpe-diem.txt", "a")

50

x.write("carpe\ndiem\n") x.close()

Write mode overwrites files, while append mode does not overwrite files but instead appends at the end of the files' content

slide-51
SLIDE 51

List

51

slide-52
SLIDE 52

52

  • If a string is a sequence of characters, then

a list is a sequence of items!

  • List is usually enclosed by square brackets [ ]
  • As opposed to strings where the object is fixed (= immutable),

we are free to modify lists (that is, lists are mutable).

x = [1, 2, 3, 4] x[0] = 4 x.append(5) print(x) # [4, 2, 3, 4, 5]

Lists

slide-53
SLIDE 53

50

List Operations

>>> x = [ 1, "Python", "is", "cool" ] >>> x.sort() >>> x[0:2] >>> len(x) >>> x + ["!"] >>> x[2] = "hot" # sort elements in x # slicing # length of string x # concatenation # replace element at index 0 with "hot" >>> x.remove("Python") # remove the first occurrence of "Python" >>> x.pop(0) # remove the element at index 0 >>> [1, 2, 3] + [4, 5] Mutable vs None-Mutable

slide-54
SLIDE 54

54

It is basically a cool way of generating a list

[expression for-clause condition] Example: [i*2 for i in [0,1,2,3,4] if i%2 == 0] [i.replace("o", "i") for i in ["Python", "is", "cool"] if len(i) >= 3]

List Comprehension

slide-55
SLIDE 55

55

  • Like a list, but you cannot modify it (= immutable)
  • Tuple is usually (but not necessarily) enclosed by parentheses ()
  • Everything that works with lists, works with tuples,

except functions modifying the tuples' content

  • Example:

x = (0,1,2) y = 0,1,2 # same as x x[0] = 2 # this gives an error

Tuples

slide-56
SLIDE 56

56

  • As opposed to lists, in sets duplicates are removed and

there is no order of elements!

  • Set is of the form { e1, e2, e3, ... }
  • Operations include: intersection, union, difference.
  • Example:

Sets

slide-57
SLIDE 57

Dictionary

57

slide-58
SLIDE 58

58

Dictionaries

  • Dictionaries map from keys to values!
  • Content in dictionaries is not ordered.
  • Dictionary is of the form { k1:v1, k2:v2, k3:v3, ... }
  • Example:

x = {"indonesia":"jakarta", "germany":"berlin","italy":"rome"} print(x["indonesia"]) # get value from key x["japan"] = "tokyo" # add a new key-value pair to dictionary print(x)

# {'italy': 'rome', 'indonesia': 'jakarta', 'germany': 'berlin', 'japan': 'tokyo'}

slide-59
SLIDE 59

Class

59

slide-60
SLIDE 60
  • While in functions we encapsulate a set of instructions,

in classes we encapsulate objects!

  • A class is a blueprint for objects, specifying:
  • Attributes for objects
  • Methods for objects
  • A class can use other classes as a base
  • Generic:

class class-name(base): attribute-code-block method-code-block

Classes

60

slide-61
SLIDE 61

class Person: def init (self, first, last): self.firstname = first self.lastname = last def describe(self): return self.firstname + " " + self.lastname guido = Person("Guido","Van Rossum") print(guido.describe())

Classes: Person

class class-name(base): attribute-code-block method-code-block

61

slide-62
SLIDE 62

59

Classes: Person & Employee

# first add code for class Person here

class class-name(base): attribute-code-block method-code-block

class Employee(Person): def init__(self, first, last, staffnum): Person. init__(self, first, last) self.staffnum = staffnum def describe(self): return self.lastname + ", " + str(self.staffnum) guido = Employee("Guido", "Van Rossum", 123456) print(guido.describe())