A thorough introduction to Python. What is Python exactly? Python is a modern rapid development language. – Emphasizes single, intuitive approach to most.

Slides:



Advertisements
Similar presentations
JavaScript I. JavaScript is an object oriented programming language used to add interactivity to web pages. Different from Java, even though bears some.
Advertisements

Container Types in Python
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Fundamentals of Python: From First Programs Through Data Structures
Title An Introduction to Python. What is Python exactly? Python is a modern rapid development language. Code is very clean and easy to read. Emphasizes.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements II.
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Fundamentals of Python: From First Programs Through Data Structures
Fundamentals of Python: First Programs
Lists in Python.
Data Structures in Python By: Christopher Todd. Lists in Python A list is a group of comma-separated values between square brackets. A list is a group.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 More About Strings.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
XP Tutorial 10New Perspectives on Creating Web Pages with HTML, XHTML, and XML 1 Working with JavaScript Creating a Programmable Web Page for North Pole.
Input, Output, and Processing
>>> # Fibonacci series:... # the sum of two elements defines the next... a, b = 0, 1 >>> while b < 10:... print b... a, b = b, a+b WHILE.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Variables and ConstantstMyn1 Variables and Constants PHP stands for: ”PHP: Hypertext Preprocessor”, and it is a server-side programming language. Special.
CPS120: Introduction to Computer Science Decision Making in Programs.
Built-in Data Structures in Python An Introduction.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Python Functions.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
JavaScript Scripting language What is Scripting ? A scripting language, script language, or extension language is a programming language.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Copyright © 2015 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 9 Dictionaries and Sets.
I Power Higher Computing Software Development High Level Language Constructs.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Sections © Copyright by Pearson Education, Inc. All Rights Reserved.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Guide to Programming with Python Chapter Five Lists and dictionaries (data structure); The Hangman Game.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
XP Tutorial 10New Perspectives on HTML, XHTML, and DHTML, Comprehensive 1 Working with JavaScript Creating a Programmable Web Page for North Pole Novelties.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Internet & World Wide Web How to Program, 5/e © by Pearson Education, Inc. All Rights Reserved.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
String and Lists Dr. José M. Reyes Álamo.
Types CSCE 314 Spring 2016.
CS-104 Final Exam Review Victor Norman.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Arithmetic operations, decisions and looping
Introduction to Python
Topics Introduction to File Input and Output
Chapter 8 JavaScript: Control Statements, Part 2
CHAPTER THREE Sequences.
Introduction to Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
Coding Concepts (Sub- Programs)
T. Jumana Abu Shmais – AOU - Riyadh
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python Primer 1: Types and Operators
Introduction to Computer Science
Topics Introduction to File Input and Output
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

A thorough introduction to Python

What is Python exactly? Python is a modern rapid development language. – Emphasizes single, intuitive approach to most problems. – Code is very clean and easy to read. – Datatypes are both strong and dynamic (we’ll discuss this in a minute) – Highly object oriented – everything is an object, and all objects support introspection and modification at run time (we’ll discuss this more later)

When should you use Python? When the amount of time the program takes to write is more important than the amount of time it takes to run (this is usually the case!) When you expect to have to go back and look at the source code for some reason at some point in the future. When you want to spend more time thinking about the solution than the code to implement it.

Basic data types The basics Integer – These are equivalent to long in c/c++. Float – These are equivalent to doubles in c/c++. String – These behave like an ordered collection of characters. Complex – These are basically paired floats, representing the real and imaginary portions of the number. Boolean – Python’s boolean values are True and False. Null – python’s null type is referenced using the keyword None.

Collection types There are three main families of collection in Python: Sequence – ordered collection of elements – Lists are mutable, denoted by square brackets (e.g. [1, 2, 3]) – Tuples are immutable, denoted by parentheses (e.g. (1, 2, 3)) Set – collection of elements, none of which may be represented more than once. Mapping – collection of keys elements and their associated values elements. – Dictionary, denoted by curly braces (e.g. {“foo”:1, “bar”:2})

Other notable types Type – When you create a class, it is actually an instance of the Type type. Functions – Your standard discrete piece of code. Exceptions – When your program fails in a semi- predictable manner, it will use these to let you know. Modules – These represent a single namespace. Packages – These are collections that hold modules, and allow you to arrange namespaces hierarchically.

Basic language structure Python abandons many of the common language formatting idioms. Linefeed terminates a command – no semicolon required (there are a couple of easy ways to span multiple lines if you want to do so). No curly braces are required around subroutines – Simply use a consistent indent for the subroutine, and return to your previous indentation level when the subroutine is complete! “#” denotes the start of a single line comment.

Basic numerical operations “+”, “-”, “*”, “/”, “%” (modulo) and “**” (power-of) all behave roughly as expected. If you perform any of these operations on two different types of numbers (integer and float for example) the number with the less expressive type is cast to the more expressive type, and the result is also of that type. “=“ assigns the value on the right to the variable on the left. The “+=“, “-=“, “*=“, “/=“ and “**=“perform the indicated operation between the variable on the left and the value on the right, then assign the result to the variable on the left.

Basic condition tests “==“ tests to see if two things have the same value. “!=“ tests to see if two things have a different value. The “ ”, “ =“ all compare relative values. “is” tests to see if two things have the same identity. “in” tests element membership in a collection.

Basic flow control Python provides flow control using if, for and while statements. for and while loops support break and continue statements, which are identical to their c/java counterparts. Additionally, these statements support an optional else clause. The do … while syntax is not available in python.

if Statement Perhaps the most well-known statement type is the if statement. For example: There can be zero or more elif parts, and the else part is optional. The keyword ‘elif‘ is short for ‘else if’, and is useful to avoid excessive indentation. An if... elif... elif... sequence is a substitute for the switch or case statements found in other languages.

for Statement The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

break and continue Statements, and else Clauses on Loops The break statement, like in C, breaks out of the smallest enclosing for or while loop. The continue statement, also borrowed from C, continues with the next iteration of the loop. Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement. This is exemplified by the following loop, which searches for prime numbers:

Boolean operators Any value, other than None, False, 0, an empty string, or an empty collection evaluates to True in a boolean context. The boolean operators supported by python, in order of increasing precedence, are: “and” “or” “not” The boolean “and” and “or” operators in python have slightly unusual behavior. Roughly speaking, the boolean operator returns the value that causes the operator to succeed or fail. This behavior is powerful when understood. Note that this does not apply to “not” operator, which returns True or False.

More on boolean operators A quick example of Python’s unusual boolean behavior, assuming A evaluates to True, B evaluates to True and C evaluates to False. A and B returns B, and is True A and C returns C, and is False C and A returns C, and is False A and not C returns True, and is True A or B returns A, and is True B or A returns B, and is True C or A returns A, and is True not A or C returns C, and is False This lets do you useful things like this: “some_variable = user_input or default_value”

Defining Functions We can create a function that writes the Fibonacci series to an arbitrary boundary: The keyword def introduces a function definition. It is followed by the function name and the list of parameters. The statements that form the body of the function start at the next line, and must be indented. The first statement of the function body can optionally be a string; this string literal is the function’s documentation string, or docstring. The return statement returns with a value from a function. return without an expression argument returns None. Falling off the end of a function also returns None.

Default Argument Values It is also possible to define a function with default value for one or more arguments. This creates a function that can be called with fewer arguments than it is defined to allow. For example:

Keyword Arguments Functions can also be called using keyword arguments of the form keyword=value. For instance, the following function: could be called in any of the following ways:

Practice Intermission Try the following problems to help gauge your understanding: - creating a fuction, simple conditionals, boolean logic creating a function, simple conditionals, simple math on variables creating a function, slightly more complex conditionals

Strings and Things Strings in Python are created with paired single or double quotes (e.g. “This is a string”) and very easy to work with. Multi line strings can be created by enclosing them with three single or double quotes on each end (e.g. “””This could span several lines“””). Once created, strings are immutable – any ‘modifications’ to the string really just create a new string, and return a reference to it. The “+” and “*” operators are overloaded for strings, so you can do neat things like: Strings have far too many useful methods to list here. See the Python cheat sheet for more information.

String Formatting Operations String and Unicode objects provide formatting via the % operator (modulo). The effect is similar to the using sprintf() in the C language. If format requires a single argument, values may be a single non-tuple object. Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary). For example:

Another Short Practice Intermission Some more problems to try: - Try this one with both string formatting, and concatenation using operators See if you can find a string method that will make it trivial.

Meet the List As previously mentioned, lists are mutable, ordered collections of objects. Any type of object can be put in a list, and lists may contain more than one type of object at a time. In much the same manner as strings, the “+” and “*” operators are overloaded on lists.

Useful List Methods list.append(x) - Add an item to the end of the list. list.extend(L) - Extend the list by appending all the items in the given list. list.insert(position, x) - Insert an item at a given position. list.remove(x) - Remove the first item from the list whose value is x. It is an error if there is no such item. list.index(x) - Return the index in the list of the first item whose value is x. It is an error if there is no such item. list.count(x) - Return the number of times x appears in the list. list.sort() - Sort the items of the list, in place. list.reverse() - Reverse the elements of the list, in place.

List Comprehensions List comprehensions offer an elegant, compact way to work with lists. Specified in the form: [do something with item for item in original list] For example: An optional condition can be specified for list comprehensions as well: [do something with item for item in original list if condition]

Sequence subscripts In Python, all sequences (including strings, which can be thought of as sequences of characters) can be subscripted. Subscripting is very powerful since it allows you to view a portion of a sequence with relative constraints. Python subscripts may either be single elements, or slices. Subscripts are invoked using square brackets, and slices are designated using a colon. For example:

Subscripts, continued Subscripts can be bounded on only one end, for instance: Subscripts can also be negative, to indicate position relative to the end of the sequence:

Your Final Practice Session Take the time to work through these exercises: - There’s a list method that makes this easy Trivial if you understand subscripts. When you have some free time, take a look at some of the other exercises on this site.

Sets A set object is an unordered collection of distinct hashable objects. Common uses include membership testing, removing duplicates from a sequence, and computing mathematical operations such as intersection, union, difference, and symmetric difference. Like other collections, sets support x in set, len(set), and for x in set. Being an unordered collection, sets do not record element position or order of insertion. Accordingly, sets do not support indexing, slicing, or other sequence-like behavior.

Useful Set Methods set.isdisjoint(other) - Return True if the set has no elements in common with other. Sets are disjoint if and only if their intersection is the empty set. set.issubset(other) or set <= other - Test whether every element in the set is in other. set < other - Test whether the set is a true subset of other, that is, set <= other and set != other. set.issuperset(other) or set >= other - Test whether every element in other is in the set. set > other - Test whether the set is a true superset of other, that is, set >= other and set != other. set.union(other,...) or set | other |... - Return a new set with elements from the set and all others. set.intersection(other,...) or set & other &... - Return a new set with elements common to the set and all others. set.difference(other,...) or set - other Return a new set with elements in the set that are not in the others. set.symmetric_difference(other) or set ^ other - Return a new set with elements in either the set or other but not both.

Defining the Dictionary A dictionary maps key objects to to arbitrary value objects. – Values that are not hashable, that is, values containing lists, dictionaries or other mutable types may not be used as keys. – Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry.

Useful Dictionary Methods dict.get(key[, default]) - Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError. dict.items() - Return a copy of the dictionary’s list of (key, value) pairs. dict.keys() - Return a copy of the dictionary’s list of keys. dict.pop(key[, default]) - If key is in the dictionary, remove it and return its value, else return default. If default is not given and key is not in the dictionary, a KeyError is raised. dict.popitem() - Remove and return an arbitrary (key, value) pair from the dictionary. popitem() is useful to destructively iterate over a dictionary, as often used in set algorithms. If the dictionary is empty, calling popitem() raises a KeyError. dict.update([other]) - Update the dictionary with the key/value pairs from other, overwriting existing keys. Return None. update() accepts either another dictionary object or an iterable of key/value pairs (as tuples or other iterables of length two). If keyword arguments are specified, the dictionary is then updated with those key/value pairs: d.update(red=1, blue=2). dict.values() - Return a copy of the dictionary’s list of values.

Basic I/O File objects can be created with the built-in open() function. File objects are also returned by some other built-in functions and methods. – Temporary files can be created using the tempfile module – high-level file operations such as copying, moving, and deleting files and directories can be achieved with the shutil module.

Modules and Namespaces When first writing programs in Python, it is likely that all your code will go in a single file. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program. – To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module. Modules can be imported into other modules or into the main module. – A module is a file containing Python definitions and statements. The file name is the module name with the suffix.py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__.

Some Useful Modules os – operating system specific functionality. os.path – useful tools to navigate directory strutures, work with filenames and so forth. shutil – like os.path, but higher level and more powerful. re – Python’s regular expression module. Regular expression is a powerful (but cryptic) text parsing language. math – lots of common mathematical operations. itertools – lots of tools for replacing clunky nested for loops or other complex looping logic typically needed into other programming languages. datetime – lots of tools for working with dates and times (surprise!)