Python Bootcamp · Run the Python interpreter interactively, so you can type code right at it........

95
Yanqiao ZHU https://sxkdz.org Tongji Apple Club School of Software Engineering, Tongji University . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Python Bootcamp Apple Workshop (Spring 2018)

Transcript of Python Bootcamp · Run the Python interpreter interactively, so you can type code right at it........

Page 1: Python Bootcamp · 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

Yanqiao ZHUhttps://sxkdz.orgTongji Apple ClubSchool of Software Engineering, Tongji University

. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .. .

Python BootcampApple Workshop

(Spring 2018)

Page 2: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Outline

1 Getting StartedSetting Up EnvironmentEditing Python

2 Introduction to PythonLanguage IntroductionFeatures

3 Basic SyntaxFirst Python ProgramPython IdentifiersLines and IndentationCommentsCommand-Line ArgumentsCode Checked at Runtime

4 Data Types and OperatorsVariablesBuilt-in TypesBasic Operators

5 Control StatementsBranchesLoops

6 Functions7 Modules8 Exceptions9 Closing Up and Further More

Getting HelpBuilt-in Documentation

Page 3: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Getting Started

Python Set Up

Python is free and open source, available for all operating systemsfrom python.org. In particular we want a Python install where youcan do two things:▶ Run an existing python program, such as hello.py.▶ Run the Python interpreter interactively, so you can type code

right at it.

Page 4: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Getting Started

Python on Linux and macOS

Most operating systems other than Windows already have Pythoninstalled by default. To check that Python is installed, open theterminal and type python in the terminal to run the Pythoninterpreter interactively:

sxkdz:~$ pythonPython 3.6.5 (default, Mar 30 2018, 06:42:10)[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang

-900.0.39.2)] on darwinType "help", "copyright", "credits" or "license"

for more information.>>> print('Hello, world')Hello, world

Listing 1.1: First Run

Page 5: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Getting Started

Python on Windows

1. Go to the download page, select a version (the legacy versionis 2.x, the newest version is 3.6.5).

2. Run the Python installer, taking all the defaults. This willinstall Python in the root directory and set up some fileassociations.

To run the Python interpreter interactively, select the Run…command from the Start menu, and type python – this will launchPython interactively in its own window.

Page 6: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Getting Started

Exit Interactive-Mode Python

On Windows, use Ctrl + Z to represent EOF (End-of-File) andexit.

On all other operating systems, EOF is represented by + D orCtrl + D .

Page 7: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Getting Started

Editing Python

A Python program is just a text file that you edit directly. Asabove, you should have a command line open, where you can typepython hello.py Alice to run whatever you are working on. Atthe command line prompt, just hit the key to recall previouslytyped commands without retyping them.

You want a text editor with a little understanding of code andindentation. 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)

Page 8: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Introduction to Python

Language Introduction

Python is a clear and powerful object-oriented programminglanguage, 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 codethat does not make sense as it runs.

Page 9: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Introduction to Python

Notable Features

✓ Easy-to-learn: has an elegant syntax, few keywords andsomple structure.

✓ Easy-to-read: Python code is clearly defined and visible to theeyes.

✓ Ideal for prototype development and other ad-hocprogramming tasks, without compromising maintainability.

✓ A board standard library: supports many commonprogramming tasks such as connecting to web servers,searching text with regular expressions, reading and modifyingfiles.

✓ Extendable: can add new modules implemented in a compiledlanguage such as C or C++.

✓ Cross-platform compatible.

Page 10: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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.

Page 11: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Introduction to Python

Features at Programming-Language Level (cont.)

✓ Data types are strongly and dynamically typed. Mixingincompatible types (e.g. attempting to add a string and anumber) causes an exception to be raised, so errors arecaught sooner.

✓ Python contains advanced programming features such asgenerators and list comprehensions.

✓ Python’s automatic memory management frees you fromhaving to manually allocate and free memory in your code.

Page 12: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Introduction to Python

The Zen of Python

Python aficionados are often quick to point out how “intuitive”,“beautiful”, or “fun” Python is.

A nice little Easter egg exists in the Python interpreter–simplyclose your eyes, meditate for a few minutes, and run importthis, you will see the zen of Python, by Tim Peters.

Page 13: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

First Python Program

There’re two ways of programming in Python:

Interactive Mode ProgrammingInvoking the interpreter without passing a script file as a parameterbrings up the prompt like Listing 1.1.

Script Mode ProgrammingInvoking the interpreter with a script parameter begins executionof the script and continues until the script is finished. When thescript is finished, the interpreter is no longer active.

Page 14: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

First Python Program (cont.)

Let us write a simple Python program in a script. Python files haveextension .py. Type the following source code in a hello.py file:

1 #!/usr/bin/python323 print("Hello, Python!")

Listing 3.1: First Python Program

We assume that you have Python interpreter available in/usr/bin directory.

Page 15: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

First Python Program (cont.)

Now, try to run this program as follows:

$ chmod +x hello.py$ ./hello.py

Listing 3.2: Modify the Property of the Script and Run

This produces the following result:

Hello, Python!

Listing 3.3: Result of the Script

Page 16: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

First Python Program (cont.)

ShebangThe first line in Listing 3.1 is called Shebang.Under Unix-like operating systems, when a script with a shebang isrun as a program, the program loader parses the rest of the script’sinitial line as an interpreter directive; the specified interpreterprogram is run instead, passing to it as an argument the path thatwas 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 3.2 is to make the script file executable.

Page 17: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 toZ 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 programminglanguage. Thus, Foobar and foobar are two different identifiers inPython.

Page 18: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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.

Page 19: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Variable Names

Since Python variables don’t have any type spelled out in thesource code, it’s extra helpful to give meaningful names to yourvariables 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 guidesdevelopers to defer to camelCasing if integrating into existingPython code that already uses that style. Readability counts.

Page 20: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Reserved Words

Table 3.1 shows the Python keywords. These are reserved wordsand can’t be used as constant or variable or any other identifiernames. All the Python keywords contain lowercase letters only.

auto del for is raiseassert elif from lambda returnbreak else global not tryclass except if or while

continue exec import pass withdef finally in print yield

Table 3.1: Python Reserved Words

Page 21: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Lines and Indentation

Python provides no braces to indicate blocks of code for class andfunction definitions or flow control. Blocks of code are denoted byline indentation, which is rigidly enforced. A logical block ofstatements such as the ones that make up a function should allhave the same indentation, set in from the indentation of theirparent function or if or whatever. If one of the lines in a grouphas a different indentation, it is flagged as a syntax error.

Page 22: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Lines and Indentation (cont.)

Avoid using TAB s as they greatly complicate the indentationscheme.

A common question beginners ask is, “How many spaces should Iindent?” According to the official Python style guide (PEP 8), youshould indent with 4 spaces. (Fact: Google’s internal styleguideline dictates indenting by 2 spaces.)

Page 23: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 (\) todenote that the line should continue. For example:

1 foo = bar_one + \2 bar_two + \3 bar_three

Listing 3.4: A Multi-line Statement

Statements contained within the [], {}, or () brackets do notneed to use the line continuation character.

Page 24: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Using Blank Lines

A line containing only whitespace, possibly with a comment, isknown as a blank line and Python totally ignores it.

In an interactive interpreter session, you must enter an emptyphysical line to terminate a multi-line statement.

Page 25: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Multiple Statements on a Single Line

The semicolon (;) allows multiple statements on the single linegiven that neither statement starts a new code block. Here is asample snip using the semicolon:

1 import sys; x = 'foo'; sys.stdout.write(x + '\n')

Listing 3.5: Multiple Statements on a Single Line

Page 26: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 arepart of the comment and the Python interpreter ignores them.

1 #!/usr/bin/python323 # First comment4 print "Hello, Python!" # Second comment

Listing 3.6: Comments in Python

Page 27: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Command-Line Arguments

Here’s another simple hello.py program differed from Listing 3.1:

1 #!/usr/bin/python323 # import sys modules4 import sys5 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 itself9

10 # Standard boilerplate to call the main()11 # function to begin the program.12 if __name__ == '__main__':13 main()

Listing 3.7: Another hello.py

Page 28: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Command-Line Arguments (cont.)

Running this program from the command line looks like:

$ ./hello.py SXKDZHello there SXKDZ

Listing 3.8: Result of Another hello.py

The outermost statements in a Python file, or module, do itsone-time setup – those statements run from top to bottom thefirst time the module is imported somewhere, setting up itsvariables and functions. A Python module can be run directly – asabove python hello.py SXKDZ – or it can be imported and usedby some other module.

Page 29: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Command-Line Arguments (cont.)

When a Python file is run directly, the special variable __name__ isset to __main__. Therefore, it’s common to have the boilerplate if__name__ == … shown above to call a main() function when themodule is run directly, but not when the module is imported bysome other module.

In a standard Python program, the list sys.argv contains thecommand-line arguments in the standard way with sys.argv[0]being the program itself, sys.argv[1] the first argument, and soon. If you know about argc, or the number of arguments, you cansimply request this value with len(sys.argv). In general, len()can tell you how long a string is, the number of elements in listsand tuples, and the number of key-value pairs in a dictionary.

Page 30: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Code Checked at Runtime

Python does very little checking at compile time, deferring almostall 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 3.9: A Python Script with Obvious Errors

Page 31: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Basic Syntax

Code Checked at Runtime (cont.)

The if-statement in Listing 3.9 contains an obvious error, wherethe repeat() function is accidentally typed in as repeeeet().But this code compiles and runs fine so long as the name atruntime is not Guido. Only when a run actually tries to executethe repeeeet() will it notice that there is no such function andraise an error. This just means that when you first run a Pythonprogram, some of the first errors you see will be simple typos likethis.

Page 32: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Variables

Python variables do not need explicit declaration to reservememory space. The declaration happens automatically when youassign a value to a variable. The equal sign (=) is used to assignvalues to variables. For example:

1 counter = 100 # An integer assignment2 miles = 1000.0 # A floating point assignment3 name = "John" # A string assignment

Listing 4.1: Variable Assignments

Page 33: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Multiple Assignments

Python allows you to assign a single value or multiple values toseveral variables simultaneously. For example:

1 a, b, c = 12 d, e, f = 2, 3, "john"

Listing 4.2: Multiple Assignments

In Listing 4.2, an integer object is created with the value 1, and allthree variables a, b, c are assigned to the same memory location.Then, two integer objects with values 2 and 3 are assigned tovariables d and e respectively, and one string object with the value"john" is assigned to the variable f.

Page 34: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Built-in Types

The data stored in memory can be of many types. Python has fivebuilt-in data types:▶ number▶ string▶ list▶ tuple▶ dictionary

Page 35: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Numbers

Number data types store numeric values. Number objects arecreated 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 avoidconfusion with the number 1. Python displays long integerswith an uppercase L.

▶ float (floating point real values)▶ complex (complex numbers)

Page 36: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Strings

Python has a built-in string class named str with many handyfeatures. String literals can be enclosed by either double or singlequotes, although single quotes are more commonly used.Backslash escapes work the usual way within both single anddouble quoted literals.

The plus (+) sign is the string concatenation operator and theasterisk (*) is the repetition operator.

Python strings are immutable which means they cannot bechanged after they are created. Since strings can’t be changed, weconstruct new strings as we go to represent computed values. Sofor example the expression ('hello' + 'there') takes in the 2strings 'hello' and 'there' and builds a new string'hellothere'.

Page 37: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 anexpression like s[8] returns a string of length−1 containing thecharacter. With that string, the operators ==, <=, … all work asyou would expect, so mostly you don’t need to know that Pythondoes not have a separate scalar char type.

Page 38: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Strings (cont.)

The handy slice syntax also works to extract any substring from astring. The len(string) function returns the length of a string.The [ ] syntax and the len() function actually work on anysequence type – strings, lists, etc. Python tries to make itsoperations work consistently across different types.

Page 39: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Strings (cont.)

For example:

1 #!/usr/bin/python32 str = "Hello World!"3 print(str) # Prints complete string4 print(str[0]) # Prints first character of

the string5 print(str[2:5]) # Prints characters starting

from 3rd to 5th6 print(str[2:]) # Prints string starting

from 3rd character7 print(str * 2) # Prints string two times8 print(str + "TEST")# Prints concatenated string

Listing 4.3: String Representations

Page 40: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Strings (cont.)

Listing 4.3 produces the following result:

Hello World!Hllollo World!Hello World!Hello World!Hello World!TEST

Listing 4.4: Result of String Representations

Page 41: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Quotations

Python accepts single ('), double (") and triple (''' or """)quotes to denote string literals, as long as the same type of quotestarts and ends the string. The triple quotes are used to span thestring across multiple lines. For example:

1 word = 'word'2 sentence = "This is a sentence."3 paragraph = '''This is a paragraph. It is4 made up of multiple lines and sentences.'''

Listing 4.5: String Literals in Python

Page 42: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

String Methods

Here are some of the most common string methods. A method islike a function, but it runs on an object. If the variable s is astring, then the code s.lower() runs the lower() method onthat string object and returns the result.

Object-Oriented ProgrammingObject-oriented programming (OOP) is a programmingparadigm based on the concept of objects, which may containdata, in the form of fields, often known as attributes; and code, inthe form of procedures, often known as methods. A feature ofobjects is that an object’s procedures can access and often modifythe data fields of the object with which they are associated(objects have a notion of this or self).

Page 43: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

String Methods (cont.)

▶ s.lower(), s.upper() – returns the lowercase or uppercaseversion of the string.

▶ s.strip() – returns a string with whitespace removed fromthe start and end.

▶ s.isalpha()/s.isdigit()/s.isspace()… – tests if all thestring chars are in the various character classes.

▶ s.startswith('other'), s.endswith('other') – tests ifthe string starts or ends with the given other string.

▶ s.find('other') – searches for the given other string (not aregular expression) within s, and returns the first index whereit begins or -1 if not found.

Page 44: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

String Methods (cont.)

▶ s.replace('old', 'new') – returns a string where alloccurrences of 'old' have been replaced by 'new'.

▶ s.split('delim') – returns a list of substrings separated bythe 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 s.split()(with no arguments) splits on all whitespace chars.

▶ s.join(list) – opposite of split(), joins the elements inthe given list together using the string as the delimiter, e.g.'---'.join(['aaa', 'bbb', 'ccc']) ->aaa---bbb---ccc.

Page 45: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 theelements beginning at start and extending up to but not includingend. Suppose we have s = "Hello":

0 1 2 3 4–5 –4 –3 –2 –1

HelloFigure 4.1: Subscripts of String Slices

Page 46: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Slices (cont.)

The standard zero-based index numbers give easy access to charsnear the start of the string. As an alternative, Python uses negativenumbers to give easy access to the chars at the end of the stringas shown in Figure 4.1: 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 putanother way s[:n] and s[n:] always partition the string into twostring parts, conserving all the characters.

Page 47: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

String Formatting via the Modulo Operator

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 4.6: String Formatting via the Modulo Operator

Page 48: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

String Formatting via the format() Method

Substitute complex variable and format value in string via theformat() method (described in PEP 3101). Format stringscontain replacement fields surrounded by curly braces ({}1).With this style of formatting, it is possible to give placeholders anexplicit positional index. This allows for re-arranging the order ofdisplay without changing the arguments.

1 '{} {}'.format(1, 2) # 1 22 '{} {}'.format('one', 'two'). # one two3 '{1} {0}'.format('one', 'two') # two one4 '{:04d}'.format(42) # 00425 '{:f}'.format(3.14159265358) # 3.141593

Listing 4.7: String Formatting via the format() Method1Escaping by doubling ({{ and }}) to include a brace character in the literal

text.

Page 49: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

String Formatting via Literal String Interpolation

String interpolation is a process substituting values of variablesinto placeholders in a string.

Python 3.6 added new string interpolation method called literalstring interpolation and introduced a new literal prefix f.

1 a = 12, b = 32 f'12 * 3 = {a * b}' # 12 * 3 = 363 name = 'World', program = 'Python'4 f'Hello {name}! This is {program}.' # Hello

World! This is Python.

Listing 4.8: String Formatting via Literal String Interpolation

Page 50: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 withinsquare 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 types.The values stored in a list can be accessed using the slice operatoras well, with indexes starting at 0 in the beginning of the list andworking their way to end -1.

Page 51: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Lists (cont.)

For example:

1 #!/usr/bin/python32 list = ['abcd', 786 , 2.23, 'john', 70.2]3 tinylist = [123, 'john']4 print(list) # Prints complete list5 print(list[0]) # Prints first element of

the list6 print(list[1:3]) # Prints elements starting

from 2nd till 3rd7 print(list[2:]) # Prints elements starting

from 3rd element8 print(tinylist * 2) # Prints list two times9 print(list + tinylist)

10 # Prints concatenated lists

Listing 4.9: List Representation

Page 52: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Lists (cont.)

Listing 4.9 produces the following result:

['abcd', 786, 2.23, 'john', 70.2]abcd[786, 2.23][2.23, 'john', 70.2][123, 'john', 123, 'john']['abcd', 786, 2.23, 'john', 70.2, 123, 'john']

Listing 4.10: Result of List Representation

Page 53: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 inmemory.

1 colors = ['red', 'blue', 'green']2 b = colors ## Does not copy the list

Listing 4.11: Referencing Lists

colorsb

'red' 'blue' 'green'

Figure 4.2: Illustration of the Memory Space

Page 54: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

List Methods

Here are some common list methods:▶ list.append(elem) – adds a single element to the end of

the list. Common error: does not return the new list, justmodifies the original.

▶ list.insert(index, elem) – inserts the element at thegiven index, shifting elements to the right.

▶ list.extend(list2) adds the elements in list2 to the endof the list. Using + or += on a list is similar to usingextend().

▶ list.index(elem) – searches for the given element from thestart of the list and returns its index. Throws a ValueErrorif the element does not appear (use in to check without aValueError).

Page 55: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

List Methods (cont.)

▶ list.remove(elem) – searches for the first instance of thegiven element and removes it (throws ValueError if notpresent).

▶ list.sort() – sorts the list in place.▶ list.reverse() – reverses the list in place.▶ list.pop(index) – removes and returns the element at the

given index. Returns the rightmost element if index is omitted(roughly the opposite of append()).

Page 56: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 donot change size (tuples are not strictly immutable since one of thecontained elements could be mutable). Unlike lists, tuples areenclosed within parentheses.

Tuples play a sort of “struct” role in Python – a convenient way topass around a little logical, fixed size bundle of values. Forexample, if I wanted to have a list of 3-d coordinates, the naturalpython representation would be a list of tuples, where each tuple issize 3 holding one (x, y, z) group.

Page 57: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Tuples (cont.)

To create a size-1 tuple, the lone element must be followed by acomma:

1 tuple = ('hi',) ## size-1 tuple

Listing 4.12: A Size-1 Tuple

The comma is necessary to distinguish the tuple from the ordinarycase of putting an expression in parentheses. In some cases youcan omit the parenthesis and Python will see from the commasthat you intend a tuple.

Page 58: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Tuples (cont.)

The following code is invalid with tuple, because it is not allowedto update a tuple. Similar case is possible with lists:

1 #!/usr/bin/python323 tuple = ('abcd', 786, 2.23, 'john', 70.2)4 list = ['abcd', 786, 2.23, 'john', 70.2]5 tuple[2] = 1000 # Invalid syntax with tuple6 list[2] = 1000 # Valid syntax with list

Listing 4.13: Invalid Tuple Operations

Page 59: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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:valuepairs within braces { }, e.g., dict = {key1:value1,key2:value2, …}.

Looking up or setting a value in a dict uses square brackets, e.g.,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 andtuples work cleanly since they are immutable). Looking up a valuewhich is not in the dict throws a KeyError – use in to check ifthe key is in the dict, or use dict.get(key) which returns thevalue 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).

Page 60: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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

dict8 'a' in dict ## True9 ## print(dict['z']) ## Throws KeyError

10 if 'z' in dict:11 print(dict['z']) ## Avoid KeyError12 print(dict.get('z')) ## None (avoid KeyError)

Listing 4.14: An Example Using Dict

Page 61: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Dictionaries (cont.)

'foo1'

'foo2'

'foo3'

keys

dict

'bar1'

'bar2'

'bar3'

values

Figure 4.3: Illustration of the Dict Memory Space

Page 62: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Dictionaries (cont.)

The methods dict.keys() and dict.values() return lists ofthe keys or values explicitly. There’s also an items() whichreturns a list of (key, value) tuples, which is the most efficientway to examine all the key value data in the dictionary.

Strategy NoteFrom a performance point of view, the dictionary is one of yourgreatest tools, and you should use it where you can as an easy wayto organize data. For example, you might read a log file where eachline begins with an IP address, and store the data into a dict usingthe IP address as the key, and the list of lines where it appears asthe value. Once you’ve read in the whole file, you can look up anyIP address and instantly see its list of lines. The dictionary takes inscattered data and makes it into something coherent.

Page 63: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Dictionary Formatting

Both formatting styles support named placeholders to convenientlyto substitute values from a dict into a string by name:

1 d = {}2 d['word'] = 'garfield'3 d['cnt'] = 424 s = 'I want %(cnt)d copies of %(word)s' % d #

old style5 s = 'I want {cnt} copies of {word}'.format(**d)

# new style6 # 'I want 42 copies of garfield'

Listing 4.15: Dictionary Value Substitution

Page 64: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Data Type Conversion

Sometimes, you may need to perform conversions between thebuilt-in types. To convert between types, you simply use the typename as a function.

There are several built-in functions to perform conversion from onedata type to another. These functions return a new objectrepresenting the converted value.

Page 65: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Data Type Conversion (cont.)

Function Descriptionint(x [,base]) Converts x to an integer. base specifies the

base if x is a string.long(x [,base]) Converts x to a long integer. base specifies

the base if x is a string.float(x) Converts x to a floating-point number.str(x) Converts object x to a string representation.tuple(s) Converts s to a tuple.list(s) Converts s to a list.dict(d) Creates a dictionary. d must be a sequence

of (key,value) tuples.

Table 4.1: Some Useful Type Conversion Functions

Page 66: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Basic Operators

Operators are the constructs which can manipulate the value ofoperands.

Python language supports the following types of operators:▶ Arithmetic Operators▶ Comparison (Relational) Operators▶ Assignment Operators▶ Logical Operators▶ Bitwise Operators▶ Membership Operators▶ Identity Operators

Page 67: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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.

Page 68: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Arithmetic Operators (cont.)

▶ // (Floor Division) – The division of operands where theresult is the quotient in which the digits after the decimalpoint are removed. But if one of the operands is negative, theresult is floored, i.e., rounded away from zero (towardsnegative infinity):▶ 9//2 = 4▶ 9.0//2.0 = 4.0▶ −11//3 = −4▶ −11.0//3 = −4.0

Page 69: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Comparison Operators

These operators compare the values on either sides of them anddecide the relation among them. They are also called Relationaloperators.▶ == – 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.

Page 70: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Comparison Operators (cont.)

▶ > – If the value of left operand is greater than the value ofright operand, then condition becomes true.

▶ < – If the value of left operand is less than the value of rightoperand, then condition becomes true.

▶ >= – If the value of left operand is greater than or equal tothe value of right operand, then condition becomes true.

▶ <= – If the value of left operand is less than or equal to thevalue of right operand, then condition becomes true.

Page 71: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

Assignment Operators

Assignment operators are quite like C. Python supports = as thebasic assignment operator and also adding-assignment operator +=.Apparently, there’re 7 corresponding assignment operators alongwith 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.

Page 72: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 asfollows:

a = (0011 1100)2b = (0000 1101)2a&b = 0000 1100a|b = 0011 1101aˆb = 0011 0001˜a = 1100 0011

Page 73: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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

Evaluates to True if thevariables on either side of theoperator point to the sameobject and False otherwise.

x is y results inTrue if id(x)equals to id(y).

is not

Evaluates to False if thevariables on either side of theoperator point to the sameobject and True otherwise.

x is not yresults in True ifid(x) doesn’tequal to id(y).

Table 4.2: Identity Operators

Page 74: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Data Types and Operators

The Deleting Operator

The del operator does deletions. In the simplest case, it canremove the definition of a variable, as if that variable had not beendefined. It can also be used on list elements or slices to delete thatpart of the list and to delete entries from a dictionary.

1 var = 62 del var # var no more3 list = ['a', 'b', 'c', 'd']4 del list[0] ## Delete first element5 del list[-2:] ## Delete last two elements6 print(list) ## ['b']7 dict = {'a':1, 'b':2, 'c':3}8 del dict['b'] ## Delete 'b' entry9 print(dict) ## {'a':1, 'c':3}

Listing 4.16: An Example Using del

Page 75: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

if Statement

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

Page 76: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

if Statement (cont.)

Any value can be used as an if-test. The “zero” values all countas 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 withstrings. The boolean operators are the spelled out words and, or,not (Python does not use the C-style &&, ||, !).

Page 77: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

if Statement (cont.)

Here’s what the code might look like for a policeman pulling over aspeeder:

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 5.1: An Example Using if Statement

Page 78: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

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 5.2: A Shorter Example Using if Statement

Page 79: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

in Statement

The in construct on its own is an easy way to test if an elementappears 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 5.3: An Example Using in Statement

Page 80: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

Ranged Loops

Python’s for and in constructs are extremely useful. The forconstruct – for var in list – is an easy way to look at eachelement in a list (or other collection). Do not add or remove fromthe list during iteration. For example:

1 squares = [1, 4, 9, 16]2 sum = 03 for num in squares:4 sum += num5 print(sum) ## 30

Listing 5.4: Ranged Loops

Page 81: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

Range Generating

The range(n) function yields the numbers 0, 1, …, n−1, andrange(a, b) returns a, a+1, …, b−1 – up to but not includingthe last number. The combination of the for-loop and therange() function allow you to build a traditional numeric for loop:

1 # Generates the Numbers from 0 through 992 for i in range(100):3 print(i)

Listing 5.5: An Example of range() Function

There is a variant xrange() which avoids the cost of building thewhole list for performance sensitive cases.

Page 82: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Control Statements

while Loop

Python also has the standard while-loop, and the break andcontinue statements work as in C++ and Java, altering thecourse of the innermost loop. The above for/in loops solves thecommon case of iterating over every element in a list, but thewhile loop gives you total control over the index numbers. Here’s awhile loop which accesses every 3rd element in a list:

1 ## Access every 3rd element in a list2 i = 03 while i < len(a):4 print(a[i])5 i = i + 3

Listing 5.6: An Example of while Loop

Page 83: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Functions

Defining a Function

A function is a block of organized, reusable code that is used toperform a single, related action. Functions provide bettermodularity for your application and a high degree of code reusing.

The def keyword defines the function with its parameters withinparentheses and its code indented. The first line of a function canbe a documentation string (docstring) that describes what thefunction does. Variables defined in the function are local to thatfunction. The return statement can take an argument, in whichcase that is the value returned to the caller.

Page 84: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Functions

Defining a Function (cont.)

1 # Defines a "repeat" function that takes 2arguments.

2 def repeat(s, exclaim):3 """4 Returns the string 's' repeated 3 times.5 If exclaim is true, add exclamation marks.6 """78 result = s * 39 if exclaim:

10 result = result + '!!!'11 return result

Listing 6.1: Function Definitions

Page 85: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Modules

More on Modules and their Namespaces

Suppose you’ve got a module binky.py which contains a deffoo(). The fully qualified name of that foo function isbinky.foo. In this way, various Python modules can name theirfunctions and variables whatever they want, and the variable nameswon’t conflict – module1.foo is different from module2.foo.

In the Python vocabulary, we’d say that binky, module, andmodule2 each have their own namespaces, which as you canguess are variable name-to-object bindings.

Page 86: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Modules

More on Modules and their Namespaces (cont.)

For example, we have the standard sys module that contains somestandard system facilities, like the argv list, and exit() function.With the statement import sys you can then access thedefinitions in the sys module and make them available by theirfully-qualified name, e.g. sys.exit().

1 import sys23 # Now can refer to sys.xxx facilities4 sys.exit(0)

Listing 7.1: Importing sys Module

Page 87: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Modules

More on Modules and their Namespaces (cont.)

There is another import form that looks like this: from sysimport argv, exit. That makes argv and exit() available bytheir short names; however, we recommend the original form withthe fully-qualified names because it’s a lot easier to determinewhere a function or attribute came from.

There are many modules and packages which are bundled with astandard installation of the Python interpreter, so you don’t haveto do anything extra to use them. These are collectively known asthe Python Standard Library.

You can find the documentation of all the Standard Librarymodules and packages at https://docs.python.org/library.

Page 88: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Exceptions

Exceptions

An exception represents a runtime error that halts the normalexecution at a particular line and transfers control to error handlingcode. This section just introduces the most basic uses ofexceptions. For example a runtime error might be that a variableused in the program does not have a value (ValueError), or a fileopen operation error because that a does not exist (IOError) Seeexception docs for more useful information.

Page 89: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Exceptions

Exceptions (cont.)

Without any error handling code, a runtime exception just haltsthe program with an error message. That’s a good defaultbehavior, and you’ve seen it many times. You can add atry/except structure to your code to handle exceptions, like this:

1 try:2 f = open(filename , 'rU')3 text = f.read()4 f.close()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 8.1: An Example Handling Exceptions

Page 90: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Exceptions

Exceptions (cont.)

▶ The try: section includes the code which might throw anexception.

▶ The except: section holds the code to run if there is anexception.

▶ If there is no exception, the except: section is skipped (thatis, that code is for error handling only, not the “normal” casefor the code). You can get a pointer to the exception objectitself with syntax except IOError, e: … (e points to theexception object).

Page 91: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Closing Up and 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.

Page 92: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Closing Up and Further More

The help() and dir() Function

Inside the Python interpreter, the help() function pulls updocumentation strings for various modules, functions, andmethods. These doc strings are similar to Java’s javadoc. Thedir() function tells you what the attributes of an object are.Below are some ways to call help() and dir() from theinterpreter:▶ 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(sys.exit) – help string for the exit() function in the

sys module.

Page 93: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Closing Up and Further More

The help() and dir() Function (cont.)

▶ help('xyz'.split) – help string for the split() methodfor string objects. You can call help() with that object itselfor an example of that object, plus its attribute. For example,calling help('xyz'.split) is the same as callinghelp(str.split).

▶ help(list) – help string for list objects.▶ dir(list) – displays list object attributes, including its

methods.▶ help(list.append) – help string for the append() method

for list objects.

Page 94: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

References

References

▶ ’s Python Class by Nick Parlante▶ Python Official Beginners’ Guide▶ Massachusetts Institute of Technology 6.0001: Introduction to

Computer Science and Programming in Python

Page 95: Python Bootcamp · 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

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

...

.

Copyright Information

Copyright Information

Except as otherwise noted, the content is under the CreativeCommons Attribution-ShareAlike License 3.0 cba, and codesamples are licensed under the Apache 2.0 License.

Java is a registered trademark of Oracle and/or its affiliates.