COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

Similar documents
COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

2 nd Week Lecture Notes

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

COMP1730/COMP6730 Programming for Scientists. Data: Values, types and expressions.

Advanced Algorithms and Computational Models (module A)

COMP284 Scripting Languages Lecture 10: PHP (Part 2) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

The current topic: Python. Announcements. Python. Python

Chapter 6 Primitive types

Full file at

CIS192: Python Programming

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

COMP284 Scripting Languages Lecture 2: Perl (Part 1) Handouts

Variables, Constants, and Data Types

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Mobile Computing Professor Pushpendra Singh Indraprastha Institute of Information Technology Delhi Java Basics Lecture 02

Chapter 2 Working with Data Types and Operators

Introduction to Computer Programming CSCI-UA 2. Review Midterm Exam 1

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CMPT 125: Lecture 3 Data and Expressions

Welcome to Python 3. Some history

Basics of Java Programming

Visual C# Instructor s Manual Table of Contents

egrapher Language Reference Manual

Getting started with Java

UNIT- 3 Introduction to C++

Java Basic Datatypees

This is an introductory tutorial, which covers the basics of Jython and explains how to handle its various modules and sub-modules.

COMP284 Scripting Languages Lecture 9: PHP (Part 1) Handouts

A variable is a name for a location in memory A variable must be declared

Lexical Considerations

Java Notes. 10th ICSE. Saravanan Ganesh

4. Inputting data or messages to a function is called passing data to the function.

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Decaf Language Reference Manual

Introduction to Python

VLC : Language Reference Manual

Chapter 2: Data and Expressions

Chapter 2 Getting Started with Python

Work relative to other classes

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Programming to Python

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Lecture 2 Tao Wang 1

Script language: Python Data structures

LECTURE 02 INTRODUCTION TO C++

Language Reference Manual

Lecture 3. More About C

Chapter 2: Data and Expressions

BASIC COMPUTATION. public static void main(string [] args) Fundamentals of Computer Science I

Programming in Python 3

Lexical Considerations

1 Lexical Considerations

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

SOFT 161. Class Meeting 1.6

Data Handing in Python

Introduction to Programming (Java) 2/12

COMP Primitive and Class Types. Yi Hong May 14, 2015

"Hello" " This " + "is String " + "concatenation"

Language Fundamentals Summary

PYTHON- AN INNOVATION

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

Chapter 2: Using Data

Number Systems, Scalar Types, and Input and Output

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

4 Programming Fundamentals. Introduction to Programming 1 1

Chapter 2. Lexical Elements & Operators

Coral Programming Language Reference Manual

CS 115 Lecture 4. More Python; testing software. Neil Moore

Primitive Data Types: Intro

CSE 115. Introduction to Computer Science I

HUDSONVILLE HIGH SCHOOL COURSE FRAMEWORK

Introduction to Python for IBM i

Chapter 2: Data and Expressions

Some material adapted from Upenn cmpe391 slides and other sources

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Such JavaScript Very Wow

Built-in Types of Data

RTL Reference 1. JVM. 2. Lexical Conventions

BITG 1233: Introduction to C++

Python I. Some material adapted from Upenn cmpe391 slides and other sources

And Parallelism. Parallelism in Prolog. OR Parallelism

Declaration and Memory

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

IPCoreL. Phillip Duane Douglas, Jr. 11/3/2010

Overview: Programming Concepts. Programming Concepts. Names, Values, And Variables

Overview: Programming Concepts. Programming Concepts. Chapter 18: Get With the Program: Fundamental Concepts Expressed in JavaScript

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

Fundamental of Programming (C)

Computer Skills (2) for Science and Engineering Students

DAVE. Language Reference Manual. Hyun Seung Hong. October 26, 2015

Objectives. In this chapter, you will:

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Scripting Languages. Python basics

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Intro to Programming & C Why Program? 1.2 Computer Systems: Hardware and Software. Why Learn to Program?

Transcription:

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

Contents 1 Python Overview Example Basic Syntax Type System 2 Primitive Data Types Integers Floating-Point Numbers Complex Numbers Strings Booleans 3 Further Reading COMP519 Web Programming Lecture 17 Slide L17 1

Python Python: History Overview The implementation of Python was started in December 1989 by Guido van Rossum at CWI in the Netherlands The name Python is a reference to Monty Python s Flying Circus In 2001 the Python Software Foundation took over the development of Python; it maintans the CPython reference implementation of Python Python 2.0 was released in October 2000 Python 3.0 was released in October 2008 with major imcompatibilities to Python 2.0 Python 3.7, released 27 June 2018, is the current version Python is described as a multi-paradigm programming language, including support for functional programming, object-oriented programming, design by contract, and logic programming There exist interpreters as well as compilers for Python COMP519 Web Programming Lecture 17 Slide L17 2

Python Python: Hello World Example 1 #!/ usr / bin / python3 2 # HelloWorld. py 3 # Our first Python script 4 5 print (" Hello World ") On Unix/Linux systems, Python scripts begin with #! (called hash bang or she bang ) and the location of the Python interpreter/compiler If not intended to be web-accessible, the script can be stored anywhere, for example, in a file HellowWorld.py The script HellowWorld.py must be executable The script can then be executed using bash$./ HelloWorld. py assuming that the script is stored in the current working directory COMP519 Web Programming Lecture 17 Slide L17 3

Python Basic Python Syntax Basic Syntax A Python program/script consists of one or more statements and comments One-line comments start with # and run to the end of the line Multi-line comments simply consist of several one-line comments Statements are delimited by newlines except where a newline is escaped (by a backslash \) print \ (" Hello World ") COMP519 Web Programming Lecture 17 Slide L17 4

Python Basic Python Syntax Basic Syntax Blocks of statements, called suites are delimited with indentation each time the level of indentation is increased, a new block starts each time the level of indentation is decreased, a block has ended A colon : separates the header of block from the rest of the suite i = 0 while (i <3): i += 1 print ( i) # prints 1, 2, 3 ( on separate lines ) j = 0 while (j <3): j += 1 print ( j) # prints 3 k = 0 while (k <3): k += 1 print ( k) # IndentationError, # whole program does not run COMP519 Web Programming Lecture 17 Slide L17 5

Python Python: Type System Type System Python is both a dynamically typed language: a variable declaration does not include a type and a variable can hold values of different types over time x = " Hello " x = 42 is a valid sequence of statements a (mostly) strongly typed language: values are not automatically converted from unrelated types y = " Hello " + 42 will cause an error in Python However, quite a number of types are considered to be related z = 42 and True # z --> True will not cause an error in Python although a boolean operator is applied to a number COMP519 Web Programming Lecture 17 Slide L17 6

Python Types Type System Data Type / Datatype / Type A set of computer represented values together with a set of operations that can be performed on those values Python distinguished a lot more types than JavaScript, including int float complex str bool integers floating-point numbers complex numbers strings booleans list lists Types are classified into immutable mutable value is unchangeable once created value is changeable afer creation COMP519 Web Programming Lecture 17 Slide L17 7

Integers Integers The Python immutable datatype int covers the integers Positive integers can be written in various ways Decimal literals (base 10): A sequence of digits 0 9 not starting with 0 0 2012 40 1263978 Binary literals (base 2): A sequence of digits 0 1 prefixed by 0b or 0B 0b10 0b01 0b0 0b11011011 Octal literals (base 8): A sequence of digits 0 7 prefixed by 0o or 0O 0o10 0O20 0o40 0o1263978 Hexadecimal literals (base 16): A sequence of characters A F and digits 0 9 prefixed by 0x or 0X 0x10 0X20-0xFF -0x1236A7F Negative integers are obtained by applying the unary - operation to a positive integer COMP519 Web Programming Lecture 17 Slide L17 8

Integers Integers Python 2 distinguishes between int (32-bit integers) and long (arbitrary length) Elements of long are suffixed with the character l or L Python 3 only has the type int but it now stands for integers of arbitrary length (only limited by memory) there are elements of int that are bigger than any element of float Python 3.6 allows to separate groups of digits by an underscore _ to improve readability of long numbers 10 _000_000 0 xcafe_f00d 0 b_0011_1111_0100 1 _2_3_4_50 0 xc0_f_f_ee 0 b_00_11_1_0_01_0 Python has no auto-increment ++ nor auto-decrement -- operator COMP519 Web Programming Lecture 17 Slide L17 9

Floating-Point Numbers Floating-point Numbers and Arithmetic Operators The Python immutable datatype float covers (64-bit) floating-point numbers 1.25 256.0-12e19 2.4e-10 1.7976931348623157e+308 Python has no auto-increment ++ nor auto-decrement -- operator Python supports a wide range of arithmetic operators +, *, -, ** applied to two integers produce an int // (integer division) applied to a float produce a float % (modulo) / always produces a float round(number,prec) round fractions Peculiarities: round(2.5) returns 3 as int round(2.5,0) returns 3.0 as float round(-2.5) returns -2 as int COMP519 Web Programming Lecture 17 Slide L17 10

Modules Floating-Point Numbers A lot of functionality of Python is contained in modules The statement import module1 [, module2 [,... modulen ]] makes all functions from modules module1, module2 available, but all function names must be prefixed by the module name import math print math. factorial (5) The statement from module1 import fun1 [, fun2 [,... funn ]] imports the named functions from module module1 and makes them available without the need for a prefix from math import factorial print factorial (5) COMP519 Web Programming Lecture 17 Slide L17 11

Additional Arithmetic Operators Floating-Point Numbers Additional arithmetic operators are available from the math module: math.fabs(number) absolute value math.ceil(number) round fractions up math.floor(number) round fractions down math.log(number) natural logarithm math.sqrt(number) square root Interesting instances: math.sqrt(-1) returns ValueError: math domain error math.log(0) 1/0 0/0 returns ValueError: math domain error returns ZeroDivisionError: division by zero returns ZeroDivisionError: division by zero Random number operators are available from the random module random.uniform(low, high) random float between low and high random.randint(low, high) random int between low and high COMP519 Web Programming Lecture 17 Slide L17 12

Complex Numbers Complex Numbers The Python immutable datatype complex covers complex numbers of the form real + imagj where real and imag are floating-point numbers and J (or j) represents the square root of -1 The cmath module provides additional arithmetic operators including math.log(number) natural logarithm math.sqrt(number) square root Interesting instances: cmath.sqrt(-1) returns 1j cmath.log(0) returns ValueError: math domain error COMP519 Web Programming Lecture 17 Slide L17 13

Strings Strings String literals are elements of the immutable type str A string literal is a sequence of characters surrounded by single-quotes, double-quotes, or triple-quotes chars single-quoted string "chars" double-quoted string chars """chars""" triple-quoted string, can span several lines and contain single and double quotes, but not at the start or end This is a triple - quoted string containing " quotes " and spanning more than one line In all these forms \ acts as escape character Each character in a string has an (index) position given by the number of preceding characters " university " 0123456789 COMP519 Web Programming Lecture 17 Slide L17 14

Strings Strings Escape sequences have the same meaning as in JavaScript: \ (single quote) \" (double quote) \\ (backslash) \b (backspace) \f (form feed) \n (newline) \r (carriage return) \t (tab) Prefixing a string literal with the character r turns \ into an ordinary character "\" COMP519 \"" # " COMP519 " r "\" COMP519 \"" # \" COMP519 \" Python uses + for string concatenation " COMP " + 519 # returns " COMP519 " the + end # returns " the end " but does not automatically convert values of other types to strings " COMP " + 519 # results in TypeError : must be str, not int COMP519 Web Programming Lecture 17 Slide L17 15

Strings Strings There are a range of additional string operators, for example: len(string) Returns the length of a string as integer len("university") # returns 10 string.lower() Returns a copy of string with all characters lower-cased "abacus".lower() # returns "abacus" string.upper() Returns a copy of string with all characters upper-cased "abacus".upper() # returns "ABACUS" COMP519 Web Programming Lecture 17 Slide L17 16

Strings Strings There are a range of additional string operators, for example: string[start:after] Returns the substring of string starting at start and ending at after-1 "university"[3:5] # returns "ve" string.find(str, [start]) Returns the position at which str starts in string after start "university".find("i",3) # returns 7 (count starts at 0) "university".find("z",0) # returns -1 (not found) string.split(str) Split string along occurrences of str into a list of substrings "university".split("i") "university".split("a") "jabbaba".split("b") # returns ["un","vers","ty"] # returns ["university"] # returns ["ja","","a", "a"] COMP519 Web Programming Lecture 17 Slide L17 17

Booleans Booleans Python has an immutable datatype bool with constants True and False (case sensitive) Python offers the following short-circuit boolean operators: and (conjunction) or (disjunction) not (negation) The following objects are evaluated by Python as False: numerical zero values (0, 0.0, 0.0+0.0j) the Boolean value False empty strings (but not the string "0") empty lists, empty tuples, empty dictionaries, the special value None all other objects are evaluated as True (truth testing procedure) COMP519 Web Programming Lecture 17 Slide L17 18

Further Reading Revision and Further Reading Read Chapter 26: The Python Language: The History of Python to Chapter 26: The Python Language: Calculations and Operators of S. Schafer: Web Standards Programmer s Reference. Wiley Publishing, 2005. Harold Cohen Library 518.532.S29 or E-book http://library.liv.ac.uk/record=b2174141 COMP519 Web Programming Lecture 17 Slide L17 19