CS代写 COMP3115 Exploratory Data Analysis and Visualization

COMP3115 Exploratory Data Analysis and Visualization
Lecture 2: Introduction to Python Programming
 Why Python?
 Python Installation

Copyright By PowCoder代写 加微信 powcoder

 Python Fundamentals  Case example

Why Python is called “Python”
The logo was designed by .
He discusses it: “…the logo is actually based on mayan representations of snakes which very often represent only the head and perhaps a short length of tail. The structure of the snake representations the natural coiling/nesting of a snake as seen side on..”

The father of Python
• Guido van Rossum, the author of Python Programming Language was reading the published scripts from “ ’s Flying Circus”, a BBC comedy series from the 1970s. thought he needed a name that was short, unique, and slightly mysterious, so he decided to call the language Python.

History of Python Python 1:

Philosophy of Python
>>>import this
The Zen of Python, by Beautiful is better than ugly.
Explicit is better than implicitly. Simple is better than complex. Complex is better than complicated. Flat is better than nested.
Sparse is better than dense.

“Hello World” in Java
public class HelloWorld {
public static void main (String[] args) {
System.out.println(“Hello World!”); }

“Hello World” in C++
#include
using namespace std;
int main() {
cout << "Hello World!” << endl; “Hello World” in Python print ("Hello World!”) Who use python? Python Installation Python Installation  Download and Install Anaconda – https://www.anaconda.com/products/individual Python Installation Follow the step guide to install anaconda. Launch Jupyter Notebook  Open Anaconda Navigator. Launch Jupyter Notebook Create your first notebook Create your first notebook We can start to write out python code now. Jupyter Notebook Demo Python Fundamentals Python fundamentals  Three important tips  Variables and Types in Python  Data Structures in Python  Python Functions  Control Flows Three important tips.... 1. Comments: Any text preceded by the sharp sign # is a comment, and will be ignored by the Python interpreter. So, the line of “#%%” is just a special comment. 2. Indentation: Python uses whitespaces to organize its codes. • A colon “:” denotes the start of an indented code block, after which all the statements must be indented by the same amount until the end of the code block. • In practice, we recommend 4 whitespaces or a tab space as the indentation. Three important tips.... 3. Function: A function is a block of statements that perform a particular action. Once you define a function, you can reuse it by calling the function name. Python supports built-in functions and user-defined functions. Constants and Variables Constants: cannot be changed (or immutable). Literal Constants in Python include: numbers and strings Variables: used to store such mutable information A variable is identified by an identifier (e.g. A=3) 1. Case-sensitive 2. Begin with a letter or “_” 3. Canincludedigits Variables and Types  Variable – Specific, case-sensitive name – Call up value through variable name  In Python, we did not need to pre-define the variable (e.g., ‘dog_name’) in any way.  Python automatically detects the type of a variable. Python Types  The type of a variable can be queried by using the built-in function type.  The type of a variable is not fixed. Basic data types in Python  Basic data types – int (integers) – float (floating-point number) – str (string) – bool (boolean: True or False) –...  The name of types act as conversion operators between types Arithmetic Operations in Python String Operations in Python  Create a string – A string is a sequence of characters. – The characters are specified either between single (‘) or double (“) quotes – E.g.,a = “abc” or a = ‘abc’  Concatenate strings – ‘+’ operator String Operations in Python  Repeat a string  Tokenize a string  Replace Data Structures In Python  Dictionaries  Sets  Probably the most fundamental data structure in Python.  A list contains arbitrary number of elements that stored in sequential order.  The elements are separated by commas and written between square brackets.  Indexing begins from 0  The elements don’t need to be of the same type.  List is mutable. Common Operations on List  Get or set the i-th element in a list by indexing with square brackets  Get or set elements in a list by slicing with square brackets – General format for slicing: a[first:last:step] not inclusive Common Operations on List  Sorting sequences – sort: it modifies the original list – sorted: it returns a new sorted list and leaves the original list unchanged. – Theparameterreverse=True(bothto sort and sorted) can be given to get descending order of elements Common Operations on List  Concatenate lists – extend: modify a list in place. – +: return a new list. The original list is unchanged – append: add a single element to the end of a list If append another list onto a list, it will treat the another list as a single object  Tuples are lists’ immutable cousins.  Pretty much anything you can do to a list that doesn’t involve modifying it, you can do to a tuple.  Tuples are defined by using parentheses (or nothing) instead of square brackets.  Tuples are a convenient way to return multiple values from functions Dictionaries  Dictionary associates values with keys.  Dictionary can be created by listing the comma separated key-value pairs in curly brackets. Keys and values are separated by a colon.  Dictionary allows to quickly retrieve the value corresponding to a given key using square brackets.  Set represents a collection of unique elements.  Set can be created by listing its elements between curly brackets.  Set can also be created by using set() itself  Sets are used for two main reasons: – Very fast membership checking (in is a very fast operation on – Find the unique items in a collections  Sets are used less frequently than lists and dictionaries Data Structures In Python Description Can we change the content within this collection? Are the items in the collection ordered stored? Range: an immutable, ordered collection No – immutable Yes – ordered List: a mutable, ordered collection Yes – mutable Yes – ordered Tuple: an immutable, ordered collection No – immutable Yes – ordered Set: Unordered collection of unique values Yes – mutable No – unordered {'a':1, 'b':2, 'c':3} Dictionary: Unordered (key, value) mapping Yes – mutable No – unordered In-class Exercise on Python Basics  Will the following python code run successfully? If yes, write down the output. If no, justify your answer. Python Functions  A function is a rule for taking zero or more inputs and returning a corresponding output by performing a sequence of operations.  When you define a function, you specify the name and the sequence of operations.  Later, you can “call” the function by name.  In Python, a function is defined with def statement. Python Functions function name input parameter docstring documents the purpose of the function def statement return statement return value Python Functions  Function parameter can also be given default values. Python Functions  In addition to positional arguments we have seen so far, a function call can also have named arguments.  Note that the named arguments didn’t need to be in the same order as in the function definition. The named arguments must come after the positional arguments. Control Flows in Python  With control flow, you can execute certain code blocks conditionally and/or repeatedly: these basic building blocks can be combined to create sophisticated programs.  Three different categories for control flows – Loopsforrepetitivetasks(while,for) – Decisionmakingwiththeif-elsestatement – Exception-Handling (break, continue, try-except) Loops for repetitive tasks  In Python we have two kinds of loops: while and for  While loop is used to execute a block of statements repeatedly until a given condition is satisfied. Loops for repetitive tasks  For loop are used for sequential traversal.  At each iteration, the variable i refers to another value (index) from the list in order. Decision making with the if statement  The if-else statement is used to decide whether a certain statement or block of statements will be executed or not. – if a certain condition is true then a block of statement is executed otherwise not. General form of an if-else statements Exception handling  Sometimes, you will find that you will need to handle for exceptions.  The exceptions could be invalid operations (e.g., divide by 0 or compute the square root of a negative number) or a class of values that you simply are not interested in.  To handle these exceptions, you can use – Break – Continue – Try-except  break statement is only allowed inside a loop body.  When break executes, the loop terminates.  In practical use, a break statement is usually used with if statement to break a loop conditionally.  Breaking the loop, when the wanted element is found  continue statement is only allowed inside a loop body.  When continue executes, the current iteration of the loop terminates, and the execution continues with next iteration of the loop.  In practical use, a continue statement is usually used with if statement to executes conditionally.  Stopping current iteration and continuing to the next one (do not break the loop). Try-except  Unhandled exceptions will cause your program to crash. You can handle them using try and except statement  If the code in the try block works, the except block is skipped.  If the code in the try block fails, it jumps to the except section. Without the try block, the program will crash and raise an error. Try-except In-class Exercise on Python Basics  Write a function to sum all negative numbers in a list. Python fundamentals  Variables and Types in Python  Data Structures in Python – Range, Lists, Tuples, Dictionaries, Sets  Python Functions – A function is a rule for taking zero or more inputs and returning a corresponding out by performing a sequence of operations. – Function is defined with def statement in Python  Control Flows – Loopsforrepetitivetasks(while,for);Decisionmakingwiththeif-elsestatement; Exception-Handling (break, continue, try-except) 程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com