Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon

Slides:



Advertisements
Similar presentations
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Advertisements

I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
JavaScript, Third Edition
2/28/2008. >>> Overview Arrays in Python – a.k.a. Lists Ranges are Lists Strings vs. Lists Tuples vs. Lists Map-Reduce Lambda Review: Printing to a file.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Python Control of Flow.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
A Tutorial on the Python Programming Language Moshe Goldstein Most of it based on a Python Presentation by Michael DiRamio
January 24, 2006And Now For Something Completely Different 1 “And Now For Something Completely Different” A Quick Tutorial of the Python Programming Language.
CIS Computer Programming Logic
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Chapter 7 Selection Dept of Computer Engineering Khon Kaen University.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
PROGRAMMING LANGUAGES: PROLOG, CLOJURE, F# Jared Wheeler.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Python Let’s get started!.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
LECTURE 2 Python Basics. MODULES So, we just put together our first real Python program. Let’s say we store this program in a file called fib.py. We have.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Functional Processing of Collections (Advanced) 6.0.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
Information and Computer Sciences University of Hawaii, Manoa
Lecture 2 Python Basics.
Python Let’s get started!.
CS-104 Final Exam Review Victor Norman.
Python Data Structures & Algorithms in Python
Debugging and Random Numbers
Lecture 10 Data Collections
Functional Processing of Collections (Advanced)
Chapter 4: Control Structures I (Selection)
Arithmetic operations, decisions and looping
Introduction to Python
Topics Introduction to File Input and Output
CS190/295 Programming in Python for Life Sciences: Lecture 6
CISC101 Reminders Assn 3 due tomorrow, 7pm.
CSC1018F: Intermediate Python
Chapter 6 Control Statements: Part 2
Ruth Anderson UW CSE 160 Winter 2017
Type & Typeclass Syntax in function
Python Primer 1: Types and Operators
A Tutorial on the Python Programming Language
(more) Python.
CISC101 Reminders Assignment 2 due today.
CHAPTER 4: Lists, Tuples and Dictionaries
Compilers Principles, Techniques, & Tools Taught by Jing Zhang
Python Review
Ruth Anderson UW CSE 160 Spring 2018
Chap 7. Advanced Control Statements in Java
General Computer Science for Engineers CISC 106 Lecture 03
Topics Introduction to File Input and Output
Learning Python 5th Edition
Introduction to Computer Science
Ruth Anderson UW CSE 160 Winter 2016
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon Most of it based on a http://www.python-course.eu/python3_course.php

Reference https://interactivepython.org/runestone/static/pythonds/index.html http://www.python-course.eu/python3_course.php https://docs.python.org/3/tutorial/index.html https://www.python.org/

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

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.

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

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;

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

id Function( ) >>> x = 42 >>> y = x >>> id(x) 10107136 >>> y = x >>> id(x), id(y) (10107136, 10107136) >>> y = 78 >>> id(x), id(y) (10107136, 10108288) >>>

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

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

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’

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'}

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

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}

 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.

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:

While Statements: condition-controlled loop.

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.

range() Function

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

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

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

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

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

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.

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.

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

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

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

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.

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

 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

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 ∈ ℤ }.

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, 

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:

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