[PDF] Python Tutorial - unfedu



Previous PDF Next PDF
















[PDF] liste append

[PDF] append python

[PDF] parcourir une liste python

[PDF] tuple python

[PDF] liste de liste python

[PDF] instruction python

[PDF] album anglais maternelle

[PDF] découvrir l'anglais avec des albums de jeunesse cy

[PDF] album anglais cycle 3

[PDF] liste album anglais cycle 3

[PDF] album anglais ce2

[PDF] découvrir l'anglais avec des albums de jeunesse cy

[PDF] album jeunesse en anglais

[PDF] album anglais cycle 1

[PDF] expressions québécoises droles

Python Tutorial - unfedu

Python Tutorial

Dr. Xudong Liu

Assistant Professor

School of Computing

University of North Florida

Monday, 8/19/2019

Thanks to the MIT Python Course and the Python 3.6 Tutorial

1 / 56

Why Python?

Figure

T op10 Programming Languages b yIEEE Sp ectrum2018 Created by Dutch programmer Guido van Rossum in 1991, Python has long been one of the most popular programming languages among professionals.

What is Python? 2 / 56

Why Python?

1Python is arguably most popular in the general AI eld, especially in

machine learning.2Python is easy to experiment with new ideas using minimal syntax.

What is Python? 3 / 56

Why \Python"?

About the origin, van Rossum wrote in 1996

1: Over six years ago, in December 1989, I was looking for a \hobby" programming project that would keep me occupied during the week around Christmas. My oce would be closed, but I had a home computer, and not much else on my hands. I decided to write an interpreter for the new scripting language I had been thinking about lately: a descendant of ABC that would appeal to Unix/C hackers. I chose Python as a working title for the project, being in a slightly irreverent mood (and a big fan of

Monty Python's Flying Circus).1

https://en.wikipedia.org/wiki/Guido_van_RossumWhat is Python? 4 / 56

Python Basics

Python is a programming language that is1very high level: high-level structures (e.g., lists, tuples, and

dictionaries),2dynamic typing: types of variables are inferred by the interpreter at runtime,3both compiled and interpreted: source code (.py) compiled to

bytecode (.pyc) interpreted to machine code that runs, and4interactive: can be used interactively on command line.

What is Python? 5 / 56

The Python Interpreter

1Invoke from the Terminal/cmd the Python interpreter by executing

command:python2Make sure you are invoking Python 3.6. Check version bypython --versionIf your machine is installed multiple versions of Python, make sure you use version 3.6.3To exit from the interpreter, send a special signal called EOF to it:

Control-D (Linux/Mac) or Control-Z (Windows).

Ways of Python-ing 6 / 56

The Python Interpreter

Figure

Screen shot of Python Interp reter

Ways of Python-ing 7 / 56

Run Python Scripts from the Command Line

1Once you created a Python script (.py) using your favorite editor

(e.g., NotePad, vi, emacs, and IDE), you can run it on the command line simply bypython example.pyAgain, make sure you run the right version of Python.

Ways of Python-ing 8 / 56

IDE: PyCharm

1Download and install the latest version from

https://www.jetbrains.com/pycharm/.2When creating a new project, choose python3.6 as the base interpreter.

Ways of Python-ing 9 / 56

Quick Python Tutorial

I assume you know well one of C, C++ and Java.1Types

2Data structures

3Control and looping statements

4Functions and recursion

5Modules

6I/O

7Class and Inheritance

Ways of Python-ing 10 / 56

Python Programs

1A Python program is a sequence ofstatementsthat are executed

one after another by the Python interpreter.2A statement could be as simple as an assignment (taxRate=0.7)

and as complex as a denition of a function or a class.

Types 11 / 56

Data Objects and Their Types

1Python programs manipulate dataobjects.In fact everything in Python is an object!

22An object has atypethat denes what operations can be done on it.int: addition, subtraction, multiplication, etcstr: concatenation, slicing, searching, etc3Generally, there are two kinds of types:

Scalartypes: cannot be subdivided (e.g., int and

oat)Non-scalartypes: have internal structures (e.g., function and classobj)2

http://www.diveintopython.net/getting_to_know_python/everything_is_an_object.html(Read at your own risk)Types 12 / 56

Scalar Types

There are ve scalar types in Python:1int: the type of integer objects2float: real numbers3complex: complex numbers (e.g., 1 + 2j)4bool: Boolean valuesTrueandFalse5NoneType: special type and has only one valueNone6Can use built-in functiontypeto tell the type of a data object:

type(3.1415926).7Can cast types:int(6.78)gives 6 andfloat(4)gives 4.0.Types 13 / 56

Expressions

1Combine objects and operators to formexpressions.2Each expression isevaluatedto a value of some type.3Operations on int and

oat:

Result is int if both operands are int;

oat, otherwise.

4complex expressions are evaluated consideringprecedencesof

operators.5Can use parentheses too.

Types 14 / 56

Variables Binding Objects

1Anassignmentstatementbindsa data object or a variable to

another variable.pi = 3.14 l = [1,2,3] c = MyClass() d = c

2Assignment in Python is sort ofsneaky but importantto

understand:Data object: creates that object of some type and assigns a unique identity(like a reference or address) to the left handside. Can use

built-in functionidto see the identity of an objectid(pi).Variable: simply assigns the identity of the right to the left.

3To retrieve values binded with variables, simply use the variable name.

4Re-binding: assign new objects to existing variables.

l =f4,5,6,7gNowtype(l)should sayLike Java, Python automatically collects garbage objects when no

references to it.

Types 15 / 56

Built-in Data Structures

1Strings

2Lists

3Tuples

4Sets

5Dictionaries

Data Structures 16 / 56

Strings

1Astringis a sequence of characters enclosed by quotations.2Can compare using relational operators (==, >=, >, etc)In Java you can't.

3Built-in functionlentells the length of a string.4Use brackets to access characters in a string.Twoways to index:0;1;2;:::;n1n;n+ 1;n+ 2;:::;15Use built-in functionstrto cast other types to string:str(1.234)Strings 17 / 56

Strings Quotations

Python provides four dierent types of quotations to enclose a string:1Singles:"Hello, world!"Have to escape single quotes:"I donn"t know!"2Doubles:"Hello, world!"Have to escape double quotes:"n"Yes,n" she said."3Triple-singles:"""Hello, world!"""Do not need to escape single quotes

4Triple-doubles:"""Hello, world!"""Do not need to escape double quotes

Can make strings spanning multiple lines

By PEP-8 convention, we are suggested to use triple-doubles to make docstrings.Strings 18 / 56

More on Strings Quotations

1If a letterris prepended to a string with whatever quotations, it

denes arawstring that ignores all escaped codes.r"nnpythonnn"will be printed exactly those 10 characters.2Triple-single and triple-double quotes can make strings spanning

multiple lines.3By PEP-8 convention, we are suggested to use triple-doubles to make docstrings.Strings 19 / 56

Manipulating Strings

1String variables:s1 = "Hello, "2Concatenation:s2 = s1 + "world!"3Indexing:print (s2[7]+s2[8]+s2[9]+s2[-2])4Slicing:print (s2[1:5], s2[7:], s2[:])5Built-in methods

3:s1=s1.replace("ll", "LL"): What has changed fors1?data=s2.split(" ")

3 https://docs.python.org/2/library/string.htmlStrings 20 / 56

Mutability

1String objects areimmutable, cannot be changed.Similar to strings specied withfinalin Java orconstin C/C++.Strings 21 / 56

Lists

1A list is anordered4sequence of data, possibly of dierent types.2A list can be written as a list of comma-separated objects between

square brackets.To create an empty list:emptyList = []Can be heterogeneous:l = [3, 3.14, "pi"](Not common)Can be nested:L = [["Allice", "Bob", True],

["Alice", "Joe", False]]3As with strings, elements in a list can be accessed by their indices.

4Lists aremutableso elements can be changed.L[0][0] = "Alice"

4 in the sense that itcan beordered and elements can be indexed by their positions.Strings 22 / 56

Operations on Lists

1Append elements to end of lists:l.append(newElem)2Concatenate two lists using+3Extend lists:l.extend(anotherList)4Delete element at an index:del l[2]5Remove element at end of list:l.pop()6Search and remove element:l.remove(targetElem)7Reverse a list:l.reverse()8Sort a list:

sorted(l): returns sorted list and doesn't mutatel.l.sort(): mutatesl.Strings 23 / 56

Tuples

1Like a list, atupleis an ordered sequence of elements, possibly of

dierent types.2Atupleis written as elements separated by commas with or without parentheses enclosing the values.A good practice is to have parentheses. emptyTuple = () t = (2,3,4)

T = (("01202018", True), ("02042018", False))

(Nested tuple)3As with strings and lists, elements in a list can be accessed by their indices.4Unlike lists, tuples areimmutable.Sot[0] += 1gives an error.Tuples 24 / 56

Operations on Tuples

1Get number of elements:len(t)2Concatenate two tuples using+3Sort a list:sorted(t)t.sort(): can't.4Swap variable values:(x,y)=(y,x)5Unpacking:x,y,z = tTuples 25 / 56

Sets

1Asetis an unordered collection ofuniqueelements, possibly of

dierent types.2Asetis written as elements separated by commas with braces enclosing the values.emptySet = set(),fggives empty dictionary.s1 =f2,3,4gs2 =f3,45gCan't be nested.

3Elements in a list cannot be accessed by indices.

Because unordered. But can be access iteratively.

4Like lists, sets aremutable.Sets 26 / 56

Operations on Sets

1Get number of elements:len(s1)2Add elements:s1.add(34)3Remove elements:s1.remove(2)4Check membership:4 in s1gives True5Dierence:s1 -= s2,s3 = s1 - s26Intersection:s3 = s1 & s27Union:s4 = s1 | s2Sets 27 / 56

Dictionaries

1Adictionaryis an unordered collection ofkey-valuepairs2Adictionaryis written askey:valuepairs separated by commas with

braces enclosing these pairs.Keys must be unique andimmutableSo far immutables: int, oat, complex, bool, str and tuple. (This is why there is no++or--in Python.)emptyDict =fg.tel =f"Alice": 4098, "Bob": 4139gprint (tel["Bob"]) movieRatings =f"Alice":f"Batman":4.5g, "Bob":f"Batman":2.5ggprint (movieRatings["Alice"]["Batman"])

3Elements in a dictionary cannot be accessed by indices.

Because unordered. But can be access iteratively.

4Dictionaries aremutable.Dictionaries 28 / 56

Operations on Dictionaries

1Get number of pairs:len(tel)2Add elements:tel["Phil"]=39003Remove elements:del tel["Bob"]orname =

tel.pop("Bob")4Check membership:"Alice" in telgives True5Get list of keys:keysList = movieRatings.keys()Dictionaries 29 / 56

Python Tutorial

1Types

2Data structures

3Control and looping statements

quotesdbs_dbs2.pdfusesText_2