Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon

Similar presentations


Presentation on theme: "Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon"— Presentation transcript:

1 Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Most of it based on a

2 Reference

3 Presentation Overview
Interpreter Dynamic Typing Data Types Functions Global & Local Variables

4 Python as a calculator, you might type
Assignment has no visible effect. Expression, interpreter evaluates it and displays the result Typing code into a script and run it, no output at all. In script mode an expression, all by itself, has no visible effect. Expression  combination of values, variables, and operators. Statement  unit of code that the Python interpreter can execute. The difference  expression has a value; a statement does not.

5 what's a variable? As the name implies, a variable is something which can change. A variable is a way of referring to a memory location used by a computer program. a variable is a symbolic name for this physical location. This memory location contains values, like numbers, text or more complicated types. We can use this variable to tell the computer to save some data in this location or to retrieve some data from this location

6 the way variables are implemented in C, C++ or Java.
Variable names have to be declared in these languages before they can be used.  int x; int y;  Such declarations make sure that the program reserves memory for two variables with the names x and y. The variable names stand for the memory location. x = 42; y = 42;  y = 78;

7 Variables Python variables follow a dynamic typing model
Are not declared, and are created by being assigned The variable is created the first time you assign it a value have object references as values Type information is with the object, not the variable Everything in Python is an object

8 id Function( ) >>> x = 42 >>> y = x
>>> id(x) >>> y = x >>> id(x), id(y) ( , ) >>> y = 78 >>> id(x), id(y) ( , ) >>>

9 temperature = 98.6 original = temperature original is temperature -> true float 100.6 temperature = temperature + 2 1 temperature float 98.6 original 1 2 1

10 C Python int x = 5; x x = 5; x 5 5 int y = x; y = x y 10 5 y 10 y = 10; y = 10

11 Lists: Modifying Content
x = [1,'hello', (3 + 2j)] y y = x x int string complex int 1 h e l l o 3 2 3 x[0] = 3 x[1][0] = ‘j’

12

13 Class Description Default constructor conversion bool int float list
Immutable bool Boolean value bool( ) -> false bool(0)-> false bool(-1)-> true bool(li) ->true nonempty str,list bool(li) ->false empty str,list int integer (arbitrary magnitude) int( )-> 0 int(−3.9) -> −3. int( 137 ) ->value 137 int( ‘7f’ , 16) -> 127. (base 16) float floating-point number float( )-> 0.0. float(‘ 3.14’ )->3.14 list mutable sequence of objects reference list( ) ->empty list list( ‘123’ )->[‘ 1’ ,’ 2’ ,’ 3’ ] list(iterable type) tuple immutable sequence of objects tupple( ) -> empty tuple tuple( ‘123’ )->(‘ 1’ ,’ 2’ ,’ 3’ ) tuple (iterable type) str character string str()->’’, empty str str(10.3)->’10.3’ set unordered set of distinct immutable objects set()->{}, empty set set(‘1233‘) -> {‘ 1’ ,’ 2’ ,’3’ } set([1,2,3,3]) -> { 1 , 2 ,3 } frozenset immutable form of set class dict associative mapping (aka dictionary) dict()->{}, empty dict pairs = [( 'ga' , 'Irish' ), ( 'de' , 'German' )] dict(pairs)-> {'ga': 'Irish', 'de': 'German'}

14 Data Type Summary Lists, Tuples, and Dictionaries can store any type (including other lists, tuples, and dictionaries!) Only lists and dictionaries are mutable All variables are references

15 Data Type Summary Integers: 2323, 3234L Floating Point: 32.3, 3.1E2
Complex: 3 + 2j, 1j String: s = ‘123’ Lists: l = [ 1,2,3] Tuples: t = (1,2,3) Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}

16

17

18

19

20

21

22

23  if Statements There can be zero or more elif parts, and the else part is optional. The keyword ‘elif’ is short for ‘else if’, and is useful to avoid excessive indentation. An if  elif  elif  sequence is a substitute for the switch or case statements found in other languages.

24 The Python version is more readable
The Python version is more readable. It can be read as "max shall be a if a is greater than b else b".  ternary if statement is an expression, can be used within another expression:

25 While Statements: condition-controlled loop.

26

27 for Statements: collection-controlled loop.
With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

28 range() Function

29 looping through a sequence, retrieved both position index and corresponding value using enumerate() function

30 break and continue Statements, and else Clauses on Loops
a loop’s else clause runs when no break occurs.

31 Continue statement, borrowed from C, continues with the next iteration of the loop:
use the sorted() function which returns a new sorted list while leaving the source unaltered

32 To loop over two or more sequences at the same time, the entries can be paired with the zip() function looping through dictionaries, the key and corresponding value can be retrieved at the same time using the items() method

33 Function Basics Dynamic typing parameter and return value
def max(x,y) : if x < y : return x else : return y def f(): return def ff(): i=5 >>> import functionbasics >>> max(3,5) 5 >>> max('hello', 'there') 'there' >>> max(3, 'hello') 'hello‘ >>>print(f(),ff()) (None, None) functionbasics.py

34 Parameter passing follows the semantics of standard assignment statement. def count(data, target): n = 0 for item in data: if item == target: # a match n += 1 return n ch = ‘A’ prizes = count(grades, ch ) data = grades target = ‘A’ ch target grades data List Str A reassigning a new value to parameter, setting data = [ ], breaks the alias.

35 Functions are first class objects
Can be assigned to a variable Can be passed as a parameter Can be returned from a function Functions are treated like any other variable in Python, the def statement simply assigns a function to a variable programming languages terminology, first-class objects : instances of a type that can be assigned to an identifier, passed as a parameter, or returned by a function.

36 Function names are like any variable
>>> x = 10 >>> x 10 >>> def x () : print 'hello' <function x at 0x619f0> >>> x() hello >>> x = 'blah' 'blah' Functions are objects The same reference rules hold for them as for other objects

37 Functions as Parameters
def foo(f, a) : return f(a) def bar(x) : return x * x >>> from funcasparam import * >>> foo(bar, 3) 9 funcasparam.py Note that the function foo takes two parameters and applies the first as a function with the second as its parameter

38 lambda operator or lambda function
way to create small anonymous functions (functions without a name.) are throw-away functions, (just needed where they have been created.) mainly used with the functions filter(), map() and reduce(). added to Python due to the demand from Lisp programmers. syntax of a lambda function lambda argument_list: expression

39 map() applies the function func to all the elements of the sequence seq.
map() used to return a list, With Python 3, map() returns an iterator. map() can be applied to more than one list. The lists must have the same length.

40 applies a bunch of functions to one Python object.
function can be simplified with the list comprehension technique,

41  filter out all the elements of a sequence "sequence", for which the function function returns True
Only if f returns True will the element be produced by the iterator, which is the return value of filter

42

43 List Comprehension (from Python 2.0).
Python's way of implementing a well-known notation for sets as used by mathematicians. In mathematics the square numbers of the natural numbers are for example created by { x2 | x ∈ ℕ } or the set of complex integers { (x,y) | x ∈ ℤ ∧ y ∈ ℤ }.

44 A Pythagorean triple consists of three integers a, b, and c, such that  a2 + b2 = c2. 
Let A and B be two sets, the cross product (or Cartesian product) of A and B, 

45 Generator comprehensions like a list comprehension but with ( ), returns a generator instead of a list. prime numbers between 1 and 100 using the sieve of Eratosthenes:

46 A set comprehension ,{}, is similar to a list comprehension, but returns a set and not a list.


Download ppt "Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon"

Similar presentations


Ads by Google