Programming in Python

Similar documents
Python - Variable Types. John R. Woodward

COLLEGE OF ENGINEERING, NASHIK-4

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

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

S206E Lecture 19, 5/24/2016, Python an overview

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Basic Syntax - First Program 1

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

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

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

Full file at

Here n is a variable name. The value of that variable is 176.

Language Basics. /* The NUMBER GAME - User tries to guess a number between 1 and 10 */ /* Generate a random number between 1 and 10 */

UNIVERSITÀ DI PADOVA. < 2014 March >

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

Babu Madhav Institute of Information Technology, UTU 2015

Python memento TI-Smart Grids

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

IT 374 C# and Applications/ IT695 C# Data Structures

Table of Contents EVALUATION COPY

Pace University. Fundamental Concepts of CS121 1

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Some material adapted from Upenn cmpe391 slides and other sources

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

And Parallelism. Parallelism in Prolog. OR Parallelism

Variable and Data Type I

Variable and Data Type I

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Lexical Considerations

Chapter 3 : Informatics Practices. Class XI ( As per CBSE Board) Python Fundamentals. Visit : python.mykvs.in for regular updates

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

UNIT- 3 Introduction to C++

Basic Concepts. Computer Science. Programming history Algorithms Pseudo code. Computer - Science Andrew Case 2

History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability

Python in 10 (50) minutes

ENGR 101 Engineering Design Workshop

Lecture 2 Tao Wang 1

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

(CC)A-NC 2.5 by Randall Munroe Python

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Fundamental of Programming (C)

Senthil Kumaran S

Introduction to Python Code Quality

Full file at C How to Program, 6/e Multiple Choice Test Bank

Variables, expressions and statements

Introduction to Python

MICROPROCESSOR SYSTEMS INTRODUCTION TO PYTHON

c) Comments do not cause any machine language object code to be generated. d) Lengthy comments can cause poor execution-time performance.

CS Summer 2013

Part III Appendices 165

LESSON 1. A C program is constructed as a sequence of characters. Among the characters that can be used in a program are:

What Version Number to Install

Language Reference Manual

Programming Fundamentals and Python

Intro. Scheme Basics. scm> 5 5. scm>

Key Differences Between Python and Java

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

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

CS2900 Introductory Programming with Python and C++ Kevin Squire LtCol Joel Young Fall 2007

There are two ways to use the python interpreter: interactive mode and script mode. (a) open a terminal shell (terminal emulator in Applications Menu)

Computer Components. Software{ User Programs. Operating System. Hardware

A Fast Review of C Essentials Part I

Accelerating Information Technology Innovation

Advanced Algorithms and Computational Models (module A)

1 Lexical Considerations

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

Objects and Types. COMS W1007 Introduction to Computer Science. Christopher Conway 29 May 2003

A Java program contains at least one class definition.

Learning Language. Reference Manual. George Liao (gkl2104) Joseanibal Colon Ramos (jc2373) Stephen Robinson (sar2120) Huabiao Xu(hx2104)

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Work relative to other classes

Programming to Python

ARG! Language Reference Manual

The current topic: Python. Announcements. Python. Python

Java Bytecode (binary file)

DaMPL. Language Reference Manual. Henrique Grando

Introduction to Python

Program Fundamentals

Chapter 2 Getting Started with Python

age = 23 age = age + 1 data types Integers Floating-point numbers Strings Booleans loosely typed age = In my 20s

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Python allows variables to hold string values, just like any other type (Boolean, int, float). So, the following assignment statements are valid:

Accelerating Information Technology Innovation

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

Variables and literals

Chapter 17. Fundamental Concepts Expressed in JavaScript

>>> * *(25**0.16) *10*(25**0.16)

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

Scripting Languages. Python basics

Objectives. In this chapter, you will:

The C++ Language. Arizona State University 1

Language Reference Manual

CPS122 Lecture: From Python to Java last revised January 4, Objectives:

CS112 Lecture: Primitive Types, Operators, Strings

Lexical Considerations

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Introduction to Python Part 1. Brian Gregor Research Computing Services Information Services & Technology

Computer Components. Software{ User Programs. Operating System. Hardware

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Transcription:

Programming in Python Project Future (Fall 2017) Yanqiao ZHU https://sxkdzorg Camp School of Software Engineering, Tongji University

Outline 1 Getting Started Setting Up Environment Editing Python 2 Introduction to Python Language Introduction Features 3 Basic Syntax First Python Program Python Identifiers Lines and Indentation Comments Command-Line Arguments Code Checked at Runtime 4 Data Types and Operators Variables Built-in Types Basic Operators 5 Control Statements Branches Loops 6 Functions 7 Modules 8 Exceptions 9 Further More Getting Help Built-in Documentation

Getting Started Python Set Up Python is free and open source, available for all operating systems from pythonorg In particular we want a Python install where you can do two things: Run an existing python program, such as hellopy Run the Python interpreter interactively, so you can type code right at it

Getting Started Python on Linux and macos Most operating systems other than Windows already have Python installed by default To check that Python is installed, open the terminal and type python in the terminal to run the Python interpreter interactively: sxkdz:~$ python Python 361 ( default, Mar 23 2017, 16: 49: 06) [ GCC 421 Compatible Apple LLVM 800 ( clang -8000421)] on darwin Type "help", "copyright", "credits" or "license" for more information >>> print(' Hello, world ') Hello, world Listing 11: First Run

Getting Started Python on Windows 1 Go to the download page, select a version (the legacy version is 2x, the newest version is 361) 2 Run the Python installer, taking all the defaults This will install Python in the root directory and set up some file associations To run the Python interpreter interactively, select the Run command from the Start menu, and type python this will launch Python interactively in its own window

Getting Started Exit Interactive-Mode Python On Windows, use Ctrl + Z to represent EOF (End-of-File) and exit On all other operating systems, EOF is represented by + D or Ctrl + D

Getting Started Editing Python A Python program is just a text file that you edit directly As above, you should have a command line open, where you can type python hellopy Alice to run whatever you are working on At the command line prompt, just hit the key to recall previously typed commands without retyping them You want a text editor with a little understanding of code and indentation There are many good free ones: 1 Notepad++ (free and open source, Windows only) 2 Visual Studio Code with Python or MagicPython extension (free and open source, cross platform) 3 PyCharm (professional, cross platform, free for students) 4 Thonny (official recommended, free, cross platform)

Introduction to Python Language Introduction Python is a clear and powerful object-oriented programming language, comparable to Perl, Ruby, Scheme, or Java Python is a dynamic, interpreted (bytecode-compiled) language There are no type declarations of variables, parameters, functions, or methods in source code This makes the code short and flexible, and you lose the compile-time type checking of the source code Python tracks the types of all values at runtime and flags code that does not make sense as it runs

Introduction to Python Notable Features Easy-to-learn: has an elegant syntax, few keywords and somple structure Easy-to-read: Python code is clearly defined and visible to the eyes Ideal for prototype development and other ad-hoc programming tasks, without compromising maintainability A board standard library: supports many common programming tasks such as connecting to web servers, searching text with regular expressions, reading and modifying files Extendable: can add new modules implemented in a compiled language such as C or C++ Cross-platform compatible

Introduction to Python Features at Programming-Language Level A variety of basic data types are available Python supports object-oriented programming with classes and multiple inheritance Code can be grouped into modules and packages The language supports raising and catching exceptions, resulting in cleaner error handling

Introduction to Python Features at Programming-Language Level (cont) Data types are strongly and dynamically typed Mixing incompatible types (eg attempting to add a string and a number) causes an exception to be raised, so errors are caught sooner Python contains advanced programming features such as generators and list comprehensions Python s automatic memory management frees you from having to manually allocate and free memory in your code

Basic Syntax First Python Program There re two ways of programming in Python: Interactive Mode Programming Invoking the interpreter without passing a script file as a parameter brings up the prompt like Listing 11 Script Mode Programming Invoking the interpreter with a script parameter begins execution of the script and continues until the script is finished When the script is finished, the interpreter is no longer active

Basic Syntax First Python Program (cont) Let us write a simple Python program in a script Python files have extension py Type the following source code in a hellopy file: 1 #!/usr/bin/python3 2 3 print(" Hello, Python!") Listing 31: First Python Program We assume that you have Python interpreter available in /usr/bin directory

Basic Syntax First Python Program (cont) Now, try to run this program as follows: $ chmod +x hello py $ / hello py Listing 32: Modify the Property of the Script and Run This produces the following result: Hello, Python! Listing 33: Result of the Script

Basic Syntax First Python Program (cont) Shebang The first line in Listing 31 is called Shebang Under Unix-like operating systems, when a script with a shebang is run as a program, the program loader parses the rest of the script s initial line as an interpreter directive; the specified interpreter program is run instead, passing to it as an argument the path that was initially used when attempting to run the script A valid shebang begins with number sign and exclamation mark (#!) and is at the beginning of a script chmod in Listing 32 is to make the script file executable

Basic Syntax Python Identifiers A Python identifier is a name used to identify a variable, function, class, module or other object An identifier starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores and digits (0 to 9) Python does not allow punctuation characters such as @, $, and % within identifiers Python is a case sensitive programming language Thus, Foobar and foobar are two different identifiers in Python

Basic Syntax Python Identifiers (cont) Here are naming conventions for Python identifiers: Class names start with an uppercase letter All other identifiers start with a lowercase letter Starting an identifier with a single leading underscore indicates that the identifier is private Starting an identifier with two leading underscores indicates a strongly private identifier If the identifier also ends with two trailing underscores, the identifier is a language-defined special name

Basic Syntax Variable Names Since Python variables don t have any type spelled out in the source code, it s extra helpful to give meaningful names to your variables to remind yourself of what s going on So use: name if it s a single name names if it s a list of names tuples if it s a list of tuples In general, Python prefers the underscore method but guides developers to defer to camelcasing if integrating into existing Python code that already uses that style Readability counts

Basic Syntax Reserved Words Table 31 shows the Python keywords These are reserved words and can t be used as constant or variable or any other identifier names All the Python keywords contain lowercase letters only auto del for is raise assert elif from lambda return break else global not try class except if or while continue exec import pass with def finally in print yield Table 31: Python Reserved Words

Basic Syntax Lines and Indentation Python provides no braces to indicate blocks of code for class and function definitions or flow control Blocks of code are denoted by line indentation, which is rigidly enforced A logical block of statements such as the ones that make up a function should all have the same indentation, set in from the indentation of their parent function or if or whatever If one of the lines in a group has a different indentation, it is flagged as a syntax error

Basic Syntax Lines and Indentation (cont) Avoid using TAB s as they greatly complicate the indentation scheme A common question beginners ask is, How many spaces should I indent? According to the official Python style guide (PEP 8), you should indent with 4 spaces (Fact: Google s internal style guideline dictates indenting by 2 spaces)

Basic Syntax Multi-Line Statements Statements in Python typically end with a new line Python does, however, allow the use of the line continuation character (\) to denote that the line should continue For example: 1 foo = bar_one + \ 2 bar_two + \ 3 bar_three Listing 34: A Multi-line Statement Statements contained within the [], {}, or () brackets do not need to use the line continuation character

Basic Syntax Using Blank Lines A line containing only whitespace, possibly with a comment, is known as a blank line and Python totally ignores it In an interactive interpreter session, you must enter an empty physical line to terminate a multi-line statement

Basic Syntax Multiple Statements on a Single Line The semicolon (;) allows multiple statements on the single line given that neither statement starts a new code block Here is a sample snip using the semicolon: 1 import sys; x = 'foo'; sys stdout write(x + '\n ') Listing 35: Multiple Statements on a Single Line

Basic Syntax Comments A hash sign (#) that is not inside a string literal begins a comment All characters after the # and up to the end of the physical line are part of the comment and the Python interpreter ignores them 1 #!/usr/bin/python3 2 3 # First comment 4 print " Hello, Python!" # Second comment Listing 36: Comments in Python

Basic Syntax Command-Line Arguments Here s another simple hellopy program differed from Listing 31: 1 #!/usr/bin/python3 2 3 # import sys modules 4 import sys 5 def main(): 6 print ' Hello there', sys argv[1] 7 # Command line args are in sys argv[1], 8 # sys argv[0] is the script name itself 9 10 # Standard boilerplate to call the main() 11 # function to begin the program 12 if name == ' main ': 13 main() Listing 37: Another hellopy

Basic Syntax Command-Line Arguments (cont) Running this program from the command line looks like: $ / hello py SXKDZ Hello there SXKDZ Listing 38: Result of Another hellopy The outermost statements in a Python file, or module, do its one-time setup those statements run from top to bottom the first time the module is imported somewhere, setting up its variables and functions A Python module can be run directly as above python hellopy SXKDZ or it can be imported and used by some other module

Basic Syntax Command-Line Arguments (cont) When a Python file is run directly, the special variable name is set to main Therefore, it s common to have the boilerplate if name == shown above to call a main() function when the module is run directly, but not when the module is imported by some other module In a standard Python program, the list sysargv contains the command-line arguments in the standard way with sysargv[0] being the program itself, sysargv[1] the first argument, and so on If you know about argc, or the number of arguments, you can simply request this value with len(sysargv) In general, len() can tell you how long a string is, the number of elements in lists and tuples, and the number of key-value pairs in a dictionary

Basic Syntax Code Checked at Runtime Python does very little checking at compile time, deferring almost all type, name, etc checks on each line until that line runs Suppose the above main() calls repeat() like this: 1 def main(): 2 if name == ' Guido': 3 print repeeeet(name) + '!!!' 4 else: 5 print repeat( name) Listing 39: A Python Script with Obvious Errors

Basic Syntax Code Checked at Runtime (cont) The if-statement in Listing 39 contains an obvious error, where the repeat() function is accidentally typed in as repeeeet() But this code compiles and runs fine so long as the name at runtime is not Guido Only when a run actually tries to execute the repeeeet() will it notice that there is no such function and raise an error This just means that when you first run a Python program, some of the first errors you see will be simple typos like this

Data Types and Operators Variables Python variables do not need explicit declaration to reserve memory space The declaration happens automatically when you assign a value to a variable The equal sign (=) is used to assign values to variables For example: 1 counter = 100 # An integer assignment 2 miles = 10000 # A floating point assignment 3 name = " John" # A string assignment Listing 41: Variable Assignments

Data Types and Operators Multiple Assignments Python allows you to assign a single value or multiple values to several variables simultaneously For example: 1 a, b, c = 1 2 d, e, f = 2, 3, " john" Listing 42: Multiple Assignments In Listing 42, an integer object is created with the value 1, and all three variables a, b, c are assigned to the same memory location Then, two integer objects with values 2 and 3 are assigned to variables d and e respectively, and one string object with the value "john" is assigned to the variable f

Data Types and Operators Built-in Types The data stored in memory can be of many types Python has five built-in data types: number string list tuple dictionary

Data Types and Operators Numbers Number data types store numeric values Number objects are created when you assign a value to them Python supports four different numerical types: int (signed integers) long (long integers, they can also be represented in octal and hexadecimal) Python allows you to use a lowercase l with long, but it is recommended that you use only an uppercase L to avoid confusion with the number 1 Python displays long integers with an uppercase L float (floating point real values) complex (complex numbers)

Data Types and Operators Strings Python has a built-in string class named str with many handy features String literals can be enclosed by either double or single quotes, although single quotes are more commonly used Backslash escapes work the usual way within both single and double quoted literals The plus (+) sign is the string concatenation operator and the asterisk (*) is the repetition operator Python strings are immutable which means they cannot be changed after they are created Since strings can t be changed, we construct new strings as we go to represent computed values So for example the expression ('hello' + 'there') takes in the 2 strings 'hello' and 'there' and builds a new string 'hellothere'

Data Types and Operators Strings (cont) Characters in a string can be accessed using the standard [ ] syntax, and Python uses zero-based indexing, so if str = 'hello' then str[1] = 'e' If the index is out of bounds for the string, Python raises an error Python does not have a separate character type Instead an expression like s[8] returns a string of length 1 containing the character With that string, the operators ==, <=, all work as you would expect, so mostly you don t need to know that Python does not have a separate scalar char type

Data Types and Operators Strings (cont) The handy slice syntax also works to extract any substring from a string The len(string) function returns the length of a string The [ ] syntax and the len() function actually work on any sequence type strings, lists, etc Python tries to make its operations work consistently across different types

Data Types and Operators Strings (cont) For example: 1 #!/usr/bin/python3 2 str = " Hello World!" 3 print( str) # Prints complete string 4 print( str[0]) # Prints first character of the string 5 print( str[2:5]) # Prints characters starting from 3rd to 5th 6 print( str[2:]) # Prints string starting from 3rd character 7 print( str * 2) # Prints string two times 8 print( str + " TEST")# Prints concatenated string Listing 43: String Representations

Data Types and Operators Strings (cont) Listing 43 produces the following result: Hello World! H llo llo World! Hello World! Hello World! Hello World! TEST Listing 44: Result of String Representations

Data Types and Operators Quotations Python accepts single ('), double (") and triple (''' or """) quotes to denote string literals, as long as the same type of quote starts and ends the string The triple quotes are used to span the string across multiple lines For example: 1 word = ' word' 2 sentence = " This is a sentence" 3 paragraph = ''' This is a paragraph It is 4 made up of multiple lines and sentences''' Listing 45: String Literals in Python

Data Types and Operators String Methods Here are some of the most common string methods A method is like a function, but it runs on an object If the variable s is a string, then the code slower() runs the lower() method on that string object and returns the result Object-Oriented Programming Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which may contain data, in the form of fields, often known as attributes; and code, in the form of procedures, often known as methods A feature of objects is that an object s procedures can access and often modify the data fields of the object with which they are associated (objects have a notion of this or self)

Data Types and Operators String Methods (cont) slower(), supper() returns the lowercase or uppercase version of the string sstrip() returns a string with whitespace removed from the start and end sisalpha()/sisdigit()/sisspace() tests if all the string chars are in the various character classes sstartswith('other'), sendswith('other') tests if the string starts or ends with the given other string sfind('other') searches for the given other string (not a regular expression) within s, and returns the first index where it begins or -1 if not found

Data Types and Operators String Methods (cont) sreplace('old', 'new') returns a string where all occurrences of 'old' have been replaced by 'new' ssplit('delim') returns a list of substrings separated by the given delimiter The delimiter is not a regular expression, it s just text 'aaa,bbb,ccc'split(',') -> ['aaa', 'bbb', 'ccc'] As a convenient special case ssplit() (with no arguments) splits on all whitespace chars sjoin(list) opposite of split(), joins the elements in the given list together using the string as the delimiter, eg '---'join(['aaa', 'bbb', 'ccc']) -> aaa---bbb---ccc

Data Types and Operators Slices The slice syntax is a handy way to refer to sub-parts of sequences typically strings and lists The slice s[start:end] is the elements beginning at start and extending up to but not including end Suppose we have s = "Hello": 0 1 2 3 4 5 4 3 2 1 Hello Figure 41: Subscripts of String Slices

Data Types and Operators Slices (cont) The standard zero-based index numbers give easy access to chars near the start of the string As an alternative, Python uses negative numbers to give easy access to the chars at the end of the string as shown in Figure 41: s[-1] = 'o', s[-2] = 'l', and so on Negative index numbers count back from the end of the string It is a neat truism of slices that for any index n, s[:n] + s[n:] == s This works even for n negative or out of bounds Or put another way s[:n] and s[n:] always partition the string into two string parts, conserving all the characters

Data Types and Operators String % Python has a printf()-like facility to put together a string The % operator takes a printf()-type format string on the left: %d int %s string %f/%g floating point and the matching values in a tuple on the right: 1 # add parens to make the long - line work: 2 text = ("%d little pigs come out or I'll %s and %s and %s" % 3 (3, 'huff', 'puff', 'blow down')) Listing 46: String %

Data Types and Operators Lists Lists are the most versatile of Python s compound data types A list contains items separated by commas and enclosed within square brackets ([]) To some extent, lists are similar to arrays in C One difference between them is that all the items belonging to a list can be of different data type The values stored in a list can be accessed using the slice operator as well, with indexes starting at 0 in the beginning of the list and working their way to end -1

Data Types and Operators Lists (cont) For example: 1 #!/usr/bin/python3 2 list = [' abcd', 786, 223, ' john', 702] 3 tinylist = [123, ' john'] 4 print( list) # Prints complete list 5 print( list[0]) # Prints first element of the list 6 print( list [1:3]) # Prints elements starting from 2nd till 3rd 7 print( list[2:]) # Prints elements starting from 3rd element 8 print( tinylist * 2) # Prints list two times 9 print( list + tinylist) 10 # Prints concatenated lists Listing 47: Lists Representations

Data Types and Operators Lists (cont) Listing 47 produces the following result: [' abcd ', 786, 223, 'john ', 702] abcd [786, 223] [223, 'john ', 702] [123, 'john ', 123, 'john '] [' abcd ', 786, 223, 'john ', 702, 123, 'john '] Listing 48: Result of Lists Representations

Data Types and Operators Lists (cont) Assignment with an = on lists does not make a copy Instead, assignment makes the two variables point to the one list in memory 1 colors = ['red', 'blue', 'green'] 2 b = colors ## Does not copy the list Listing 49: References of Lists colors b 'red' 'blue' 'green' Figure 42: Illustration of the Memory Space

Data Types and Operators List Methods Here are some common list methods: listappend(elem) adds a single element to the end of the list Common error: does not return the new list, just modifies the original listinsert(index, elem) inserts the element at the given index, shifting elements to the right listextend(list2) adds the elements in list2 to the end of the list Using + or += on a list is similar to using extend() listindex(elem) searches for the given element from the start of the list and returns its index Throws a ValueError if the element does not appear (use in to check without a ValueError)

Data Types and Operators List Methods (cont) listremove(elem) searches for the first instance of the given element and removes it (throws ValueError if not present) listsort() sorts the list in place listreverse() reverses the list in place listpop(index) removes and returns the element at the given index Returns the rightmost element if index is omitted (roughly the opposite of append())

Data Types and Operators Tuples A tuple is a fixed size grouping of elements, such as an (x, y) co-ordinate Tuples are like lists, except they are immutable and do not change size (tuples are not strictly immutable since one of the contained elements could be mutable) Unlike lists, tuples are enclosed within parentheses Tuples play a sort of struct role in Python a convenient way to pass around a little logical, fixed size bundle of values For example, if I wanted to have a list of 3-d coordinates, the natural python representation would be a list of tuples, where each tuple is size 3 holding one (x, y, z) group

Data Types and Operators Tuples (cont) To create a size-1 tuple, the lone element must be followed by a comma: 1 tuple = ('hi',) ## size -1 tuple Listing 410: A Size-1 Tuple The comma is necessary to distinguish the tuple from the ordinary case of putting an expression in parentheses In some cases you can omit the parenthesis and Python will see from the commas that you intend a tuple

Data Types and Operators Tuples (cont) The following code is invalid with tuple, because it is not allowed to update a tuple Similar case is possible with lists: 1 #!/usr/bin/python3 2 3 tuple = (' abcd', 786, 223, ' john', 702) 4 list = [' abcd', 786, 223, ' john', 702] 5 tuple[2] = 1000 # Invalid syntax with tuple 6 list[2] = 1000 # Valid syntax with list Listing 411: Invalid Tuple Operations

Data Types and Operators Dictionaries Python s efficient key/value hash table structure is called a dict The contents of a dict can be written as a series of key:value pairs within braces { }, eg, dict = {key1:value1, key2:value2, } Looking up or setting a value in a dict uses square brackets, eg, dict['foo'] looks up the value under the key 'foo' Strings, numbers, and tuples work as keys, and any type can be a value Other types may or may not work correctly as keys (strings and tuples work cleanly since they are immutable) Looking up a value which is not in the dict throws a KeyError use in to check if the key is in the dict, or use dictget(key) which returns the value or None if the key is not present (or get(key, not-found) allows you to specify what value to return in the not-found case)

Data Types and Operators Dictionaries (cont) For example: 1 dict = {} 2 dict['a'] = 'alpha' 3 dict['g'] = 'gamma' 4 print( dict) 5 ## {'a': 'alpha', 'o': 'omega', 'g': 'gamma '} 6 print(dict['a']) ## Simple lookup: 'alpha' 7 dict['a'] = 6 ## Put new key/ value into dict 8 'a' in dict ## True 9 ## print(dict['z ']) ## Throws KeyError 10 if 'z' in dict: 11 print( dict['z']) ## Avoid KeyError 12 print( dict get('z')) ## None ( avoid KeyError) Listing 412: An Example Using Dict

Data Types and Operators Dictionaries (cont) keys 'foo1' 'foo2' 'foo3' values 'bar1' 'bar2' 'bar3' dict Figure 43: Illustration of the Dict Memory Space

Data Types and Operators Dictionaries (cont) The methods dictkeys() and dictvalues() return lists of the keys or values explicitly There s also an items() which returns a list of (key, value) tuples, which is the most efficient way to examine all the key value data in the dictionary Strategy Note From a performance point of view, the dictionary is one of your greatest tools, and you should use it where you can as an easy way to organize data For example, you might read a log file where each line begins with an IP address, and store the data into a dict using the IP address as the key, and the list of lines where it appears as the value Once you ve read in the whole file, you can look up any IP address and instantly see its list of lines The dictionary takes in scattered data and makes it into something coherent

Data Types and Operators Dictionary Formatting The % operator works conveniently to substitute values from a dict into a string by name: 1 hash = {} 2 hash['word'] = 'garfield' 3 hash[' count'] = 42 4 s = 'I want %( count)d copies of %( word)s' % hash # %d for int, %s for string 5 # 'I want 42 copies of garfield' Listing 413: An Example of Dict Formatting

Data Types and Operators Data Type Conversion Sometimes, you may need to perform conversions between the built-in types To convert between types, you simply use the type name as a function There are several built-in functions to perform conversion from one data type to another These functions return a new object representing the converted value

Data Type Conversion (cont) Data Types and Operators Function int(x [,base]) long(x [,base]) float(x) str(x) tuple(s) list(s) dict(d) Description Converts x to an integer base specifies the base if x is a string Converts x to a long integer base specifies the base if x is a string Converts x to a floating-point number Converts object x to a string representation Converts s to a tuple Converts s to a list Creates a dictionary d must be a sequence of (key,value) tuples Table 41: Some Useful Type Conversion Functions

Data Types and Operators Basic Operators Operators are the constructs which can manipulate the value of operands Python language supports the following types of operators: Arithmetic Operators Comparison (Relational) Operators Assignment Operators Logical Operators Bitwise Operators Membership Operators Identity Operators

Data Types and Operators Arithmetic Operators Basic arithmetic operators are the following: + (Addition) Adds values on either side of the operator - (Subtraction) Subtracts right hand operand from left hand operand * (Multiplication) Multiplies values on either side of the operator / (Division) Divides left hand operand by right hand operand % (Modulus) Divides left hand operand by right hand operand and returns remainder ** (Exponent) Performs exponential (power) calculation on operators

Arithmetic Operators (cont) Data Types and Operators // (Floor Division) The division of operands where the result is the quotient in which the digits after the decimal point are removed But if one of the operands is negative, the result is floored, ie, rounded away from zero (towards negative infinity): 9//2 = 4 90//20 = 40 11//3 = 4 110//3 = 40

Data Types and Operators Comparison Operators These operators compare the values on either sides of them and decide the relation among them They are also called Relational operators == If the values of two operands are equal, then the condition becomes true!= If values of two operands are not equal, then condition becomes true <> If values of two operands are not equal, then condition becomes true This is similar to!= operator

Data Types and Operators Comparison Operators (cont) > If the value of left operand is greater than the value of right operand, then condition becomes true < If the value of left operand is less than the value of right operand, then condition becomes true >= If the value of left operand is greater than or equal to the value of right operand, then condition becomes true <= If the value of left operand is less than or equal to the value of right operand, then condition becomes true

Data Types and Operators Assignment Operators Assignment operators are quite like C Python supports = as the basic assignment operator and also adding-assignment operator += Apparently, there re 7 corresponding assignment operators along with their arithmetic operators Value stored in computer memory An assignment binds name to value Retrieve value associated with name or variable by invoking the name

Data Types and Operators Bitwise Operators Bitwise operator works on bits and performs bit by bit operation Assume if a = 60 and b = 13 Now in binary format they will be as follows: a = (0011 1100) 2 b = (0000 1101) 2 a&b = 0000 1100 a b = 0011 1101 aˆb = 0011 0001 a = 1100 0011

Data Types and Operators Identity Operators Identity operators compare the memory locations of two objects There are two Identity operators explained below: Operator Description Example is is not Evaluates to True if the variables on either side of the operator point to the same object and False otherwise Evaluates to False if the variables on either side of the operator point to the same object and True otherwise x is y results in True if id(x) equals to id(y) x is not y results in True if id(x) doesn t equal to id(y) Table 42: Identity Operators

Data Types and Operators The Deleting Operator The del operator does deletions In the simplest case, it can remove the definition of a variable, as if that variable had not been defined It can also be used on list elements or slices to delete that part of the list and to delete entries from a dictionary 1 var = 6 2 del var # var no more 3 list = ['a', 'b', 'c', 'd'] 4 del list[0] ## Delete first element 5 del list[-2:] ## Delete last two elements 6 print(list) ## ['b'] 7 dict = {'a':1, 'b':2, 'c':3} 8 del dict['b'] ## Delete 'b' entry 9 print(dict) ## {'a':1, 'c ':3} Listing 414: An Example Using del

Control Statements if Statement Python does not use {} to enclose blocks of code for branches, loops, functions, etc Instead, Python uses the colon (:) and indentation/whitespace to group statements The boolean test for an if does not need to be in parenthesis, and it can have elif and else clauses Mnemonic The word elif is the same length as the word else

Control Statements if Statement (cont) Any value can be used as an if-test The zero values all count as false: None, 0, empty string, empty list, empty dictionary There is also a Boolean type with two values: True and False (converted to an int, these are 1 and 0) Python has the usual comparison operations: ==,!=, <, <=, >, >= Unlike Java and C, == is overloaded to work correctly with strings The boolean operators are the spelled out words and, or, not (Python does not use the C-style &&,,!)

Control Statements if Statement (cont) Here s what the code might look like for a policeman pulling over a speeder: 1 if speed >= 80: 2 print(' License and registration please') 3 if mood == ' terrible' or speed >= 100: 4 print('you have the right to remain silent') 5 elif mood == 'bad' or speed >= 90: 6 print("i'm going to have to write you a ticket") 7 write_ticket() 8 else: 9 print(" Let's try to keep it under 80 ok?") Listing 51: An Example Using if Statement

Control Statements if Statement (cont) If the code is short, you can put the code on the same line after :, like this (this also applies to functions, loops, etc): 1 if speed >= 80: print('you are so busted') 2 else: print(' Have a nice day') Listing 52: A Shorter Example Using if Statement

Control Statements in Statement The in construct on its own is an easy way to test if an element appears in a list (or other collection) value in collection tests if the value is in the collection, returning True/False 1 list = ['larry', 'curly', 'moe'] 2 if ' curly' in list: 3 print('yay') Listing 53: An Example Using in Statement

Control Statements Ranged Loops Python s for and in constructs are extremely useful The for construct for var in list is an easy way to look at each element in a list (or other collection) Do not add or remove from the list during iteration For example: 1 squares = [1, 4, 9, 16] 2 sum = 0 3 for num in squares: 4 sum += num 5 print(sum) ## 30 Listing 54: Ranged Loops

Control Statements Range Generating The range(n) function yields the numbers 0, 1,, n 1, and range(a, b) returns a, a+1,, b 1 up to but not including the last number The combination of the for-loop and the range() function allow you to build a traditional numeric for loop: 1 # Generates the Numbers from 0 through 99 2 for i in range (100): 3 print(i) Listing 55: An Example of range() Function There is a variant xrange() which avoids the cost of building the whole list for performance sensitive cases

Control Statements while Loop Python also has the standard while-loop, and the break and continue statements work as in C++ and Java, altering the course of the innermost loop The above for/in loops solves the common case of iterating over every element in a list, but the while loop gives you total control over the index numbers Here s a while loop which accesses every 3rd element in a list: 1 ## Access every 3rd element in a list 2 i = 0 3 while i < len(a): 4 print(a[i]) 5 i = i + 3 Listing 56: An Example of while Loop

Functions Defining a Function A function is a block of organized, reusable code that is used to perform a single, related action Functions provide better modularity for your application and a high degree of code reusing The def keyword defines the function with its parameters within parentheses and its code indented The first line of a function can be a documentation string (docstring) that describes what the function does Variables defined in the function are local to that function The return statement can take an argument, in which case that is the value returned to the caller

Functions Defining a Function (cont) 1 # Defines a " repeat" function that takes 2 arguments 2 def repeat(s, exclaim): 3 """ 4 Returns the string 's' repeated 3 times 5 If exclaim is true, add exclamation marks 6 """ 7 8 result = s * 3 9 if exclaim: 10 result = result + '!!!' 11 return result Listing 61: Function Definitions

Modules More on Modules and their Namespaces Suppose you ve got a module binkypy which contains a def foo() The fully qualified name of that foo function is binkyfoo In this way, various Python modules can name their functions and variables whatever they want, and the variable names won t conflict module1foo is different from module2foo In the Python vocabulary, we d say that binky, module, and module2 each have their own namespaces, which as you can guess are variable name-to-object bindings

Modules More on Modules and their Namespaces (cont) For example, we have the standard sys module that contains some standard system facilities, like the argv list, and exit() function With the statement import sys you can then access the definitions in the sys module and make them available by their fully-qualified name, eg sysexit() 1 import sys 2 3 # Now can refer to sys xxx facilities 4 sys exit(0) Listing 71: Importing sys Module

Modules More on Modules and their Namespaces (cont) There is another import form that looks like this: from sys import argv, exit That makes argv and exit() available by their short names; however, we recommend the original form with the fully-qualified names because it s a lot easier to determine where a function or attribute came from There are many modules and packages which are bundled with a standard installation of the Python interpreter, so you don t have to do anything extra to use them These are collectively known as the Python Standard Library You can find the documentation of all the Standard Library modules and packages at https://docspythonorg/library

Exceptions Exceptions An exception represents a runtime error that halts the normal execution at a particular line and transfers control to error handling code This section just introduces the most basic uses of exceptions For example a runtime error might be that a variable used in the program does not have a value (ValueError), or a file open operation error because that a does not exist (IOError) See exception docs for more useful information

Exceptions Exceptions (cont) Without any error handling code, a runtime exception just halts the program with an error message That s a good default behavior, and you ve seen it many times You can add a try/except structure to your code to handle exceptions, like this: 1 try: 2 f = open( filename, 'ru') 3 text = f read() 4 fclose() 5 except IOError: 6 ## Control jumps directly to here if any of the above lines throws IOError 7 sys stderr write(' problem reading:' + filename) Listing 81: An Example Handling Exceptions

Exceptions Exceptions (cont) The try: section includes the code which might throw an exception The except: section holds the code to run if there is an exception If there is no exception, the except: section is skipped (that is, that code is for error handling only, not the normal case for the code) You can get a pointer to the exception object itself with syntax except IOError, e: (e points to the exception object)

Further More Getting Help There are a variety of ways to get help for Python The official Python docs site has high quality docs The official Tutor mailing list specifically designed for those who are new to Python and/or programming Many questions (and answers) can be found on StackOverflow and Quora Use the help() and dir() functions

Further More The help() and dir() Function Inside the Python interpreter, the help() function pulls up documentation strings for various modules, functions, and methods These doc strings are similar to Java s javadoc The dir() function tells you what the attributes of an object are Below are some ways to call help() and dir() from the interpreter: help(len) help string for the built-in len() function; note that it s len not len(), which is a call to the function dir(sys) dir() is like help() but just gives a quick list of its defined symbols, or attributes help(sysexit) help string for the exit() function in the sys module

The help() and dir() Function (cont) Further More help('xyz'split) help string for the split() method for string objects You can call help() with that object itself or an example of that object, plus its attribute For example, calling help('xyz'split) is the same as calling help(strsplit) help(list) help string for list objects dir(list) displays list object attributes, including its methods help(listappend) help string for the append() method for list objects

Credit and References Credit and References s Python Class by Nick Parlante Python Official Beginners Guide Massachusetts Institute of Technology 60001: Introduction to Computer Science and Programming in Python

Copyright Information Copyright Except as otherwise noted, the content is under the Creative Commons Attribution-ShareAlike License 30 cb a, and code samples are licensed under the Apache 20 License Java is a registered trademark of Oracle and/or its affiliates