CSC1018F: Programming with Python James Gain Donald Cook

Slides:



Advertisements
Similar presentations
Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
Advertisements

CS324e - Elements of Graphics and Visualization A Little Java A Little Python.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
Your First Java Program: HelloWorld.java
Sequences The range function returns a sequence
Python By Steve Wright. What is Python? Simple, powerful, GP scripting language Simple, powerful, GP scripting language Object oriented Object oriented.
Introduction to Python. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
Java An introduction. Example 1 public class Example1 { public static void main (String [] args) { System.out.println (“This is the first example”); int.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Unit 2: Java Introduction to Programming 2.1 Initial Example.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Programming 101 with Python: an open-source, cross-platform, and fun language By J. Burton Browning, Ed.D. Copyright © J. Burton Browning All rights reserved.
Introduction to Python Dr. Bernard Chen Ph.D. University of Central Arkansas July 9 th 2012
V Avon High School Tech Club Agenda Old Business –Delete Files New Business –Week 18 Topics: Intro to HTML/CSS: Questions? Summer Work Letter.
Introduction to Python Guido van Rossum Director of PythonLabs at Zope Corporation
11 Getting Started with C# Chapter Objectives You will be able to: 1. Say in general terms how C# differs from C. 2. Create, compile, and run a.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Python 101 Dr. Bernard Chen University of Central Arkansas IT Academic.
CS 106 Introduction to Computer Science I 01 / 25 / 2010 Instructor: Michael Eckmann.
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.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
The Python Programming Language Jeff Myers Programming Language Concepts, 01/14/2002
CSC1018F: Introduction to Python (Tutorial) James Gain Donald Cook
Introduction to Python September 26, /10/ Bioinformatics Languages Low-level, compiled languages: C, C++, Java… Pros: performance Cons:
1 Module Objective & Outline Module Objective: After completing this Module, you will be able to, appreciate java as a programming language, write java.
Introduction to Python I CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Python Lists and Such CS 4320, SPRING List Functions len(s) is the length of list s s + t is the concatenation of lists s and t s.append(x) adds.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
JavaScript Syntax and Semantics. Slide 2 Lecture Overview Core JavaScript Syntax (I will not review every nuance of the language)
Built-in Data Structures in Python An Introduction.
CIT 590 Intro to Programming Lecture 5 – completing lists.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Python I Some material adapted from Upenn cmpe391 slides and other sources.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
PHP vs. Python. Similarities are interpreted, high level languages with dynamic typing are Open Source are supported by large developer communities are.
8 January 2016Birkbeck College, U. London1 Introduction to Programming Lecturer: Steve Maybank Department of Computer Science and Information Systems
CS 106 Introduction to Computer Science I 01 / 22 / 2007 Instructor: Michael Eckmann.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
Agenda Comments Identifiers Keywords Syntax and Symentics Indentation Variables Datatype Operator.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Computer Programming 2 Lab (1) I.Fatimah Alzahrani.
8/2/07. >>> About Me Scott Shawcroft * Junior * Computer Engineering * Third Quarter TA * Creative Commons Intern * Small-time Open Source Developer
Chapter 3 Introducing Java. Objectives and Goals 1. Define terminology associated with object- oriented programming. 2. Explain why Java is a widely used.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Introduction to Java Programming, 4E Y. Daniel Liang.
Computer Programming Your First Java Program: HelloWorld.java.
Containers and Lists CIS 40 – Introduction to Programming in Python
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
Data types: Complex types (Dictionaries)
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
CompSci 230 Software Construction
Statements, Comments & Simple Arithmetic
Introduction to Python
Bryan Burlingame Halloween 2018
CHAPTER THREE Sequences.
Introduction to Python
basic Python programs, defining functions
CS190/295 Programming in Python for Life Sciences: Lecture 6
Object Oriented Programming in java
CSC1018F: Intermediate Python
CS 1111 Introduction to Programming Fall 2018
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Anatomy of a Java Program
Bryan Burlingame Halloween 2018
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
Dictionary.
Learning Python 5th Edition
Presentation transcript:

CSC1018F: Programming with Python James Gain Donald Cook

A Brief History of Python Created by Guido van Rossum (a Monty Python’s Flying Circus enthusiast) in the early 1990’s Intellectual property now owned by the Python Software Foundation (PSF) Not a toy language. Used by: Industrial Light and Magic on the Star Wars movies NASA for their engineering repository

Characteristics of Python Interpreted, interactive, object-oriented programming language Powerful Batteries included (300+ libraries) Well supported OpenSource but copyrighted Portable because it exploits the underlying ‘c’ installation on most systems Easy to learn Borrows proven concepts from other languages Less scaffolding required Zen of Python: “simple is better” or “principle of least astonishment”

Hello World Java: C++: Python: // Hello World in Java class HelloWorld { static public void main(String args[]) { System.out.println(“Hello World!”); } // Hello World in C++ #include Main() { cout << “Hello World!” << endl; return 0; } # Hello World in Python print ‘Hello World!’

Course Structure Lectures: 4th period Mondays (Overview of Section) and Fridays (Mini-test and Tutorial) Afternoon Tutorial 2 hours on Monday or Tuesday Textbook Mark Pilgrim, “Dive into Python” Self Study hours work per day Do not merely read the textbook

Syllabus Week 1 Introduction to Python DIP Ch 2-3 Week 2 Intermediate Python DIP Ch 4 Week 3 Objects and Object Orientation DIP Ch 5 Week 4 Advanced Python DIP Ch Week 5 Functional Programming DIP Ch 16 Week 6 Visual Python - Remain- der Software Engineering & Battleship Project DIP Ch

Diving In Declaring Functions: def keyword, no return data type defined, arguments (with no pre-defined type) which are comma separated def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string.""" return ";".join(["%s=%s" % (k, v) for k, v in params.items()]) if __name__ == "__main__": myParams = {"server":"mpilgrim", \ "database":"master", \ "uid":"sa", \ "pwd":"secret" \ } print buildConnectionString(myParams)

Comparing Python Datatypes Languages can be classified as: Statically typed - types are fixed by declaration at compile time Dynamically typed - types are discovered at execution time Strongly typed - types are enforced and cannot be interchanged without conversion Weakly typed - types are freely ignored, no explicit conversion is necessary Python is dynamically and strongly typed

Documenting Functions Triple quotes (" " ") signify a multi-line comment Allows you to create a string containing single and double quotes Often used to define a doc string First thing defined in a function Available at run-time as an attribute of the function function.__doc__

Indenting Code Blocks of code are defined by indentation Indenting starts a block and unindenting ends it No need for explicit braces, brackets or keywords Whitespace is significant Code blocks are started by a ‘:’ def fib(n): print 'n =', n if n > 1: return n * fib(n - 1) else: print 'end of the line' return 1

Dictionaries eng2fr = {"one":"un", "two":"deux", "three":"trois"} An unordered set consisting of key-element pairs Retrieval: You can get keys (e.g., eng2fr["one"]) by value But not values by key (e.g., eng2fr["un"]) No duplicate keys Assigning values to an existing key will overwrite it Dictionary keys are case-sensitive Power! Values can mix and match any datatypes (even other dictionaries) Keys can combine immutable datatypes

Operating on Dictionaries Modifying a dictionary >>> eng2fr["four"] = "quatre" >>> eng2fr {"one":"un", "two":"deux", "three":"trois", "four":"quatre"} Deleting Items >>> del eng2fr["one"] >>> eng2fr {"two":"deux", "three":"trois","four":"quatre"} >>> eng2fr.clear() >>> eng2fr { }

Lists Horsemen = ["war", "famine", "pestilence", "death"] The Python Workhorse Much more than a java array Can grow dynamically Can include datatypes of any element Indexed by element number Lists are zero-based (first element is [0]) >>> horsemen[2] => 'famine' Allow negative indices which wrap the list >>> horsemen[-2] => 'pestilence'

Operating on Lists Slicing a List Subset specified by two indices. From 1st up to but not including 2nd >>> horsemen[1:3] => ['famine', 'pestilence'] Leaving out an index implies first or last Adding elements.append adds a single element to the end.insert places an element at a particular position.extend concatenates list onto end Deleting elements.remove deletes the first occurrence of a value from a list Searching a List.index finds first occurrence of a value and returns the index

More on Lists Mapping List comprehension allows a compact way of applying a function to every element of a list li2 = [elem*2 for elem in li] Same as: j = 1 while j < len(li): li2[j] = li[j] * 2 Joining Lists into Strings Join combines a list of strings into a single string print ";".join(["2b", "or", "not", "2b"]) => 2b;or;not;2b Split reverses join "2b;or;not;2b".split(";") => ['2b', 'or', 'not', '2b']

Tuples sins = ("pride", "anger", "gluttony", "envy", "lust", "avarice", "sloth") An immutable list. No changes allowed Similar to lists Defined order, negative indices, zero-based, slicing But no methods available (except ‘in’) So what is it good for Faster than an equivalent list Write-protects data Can serve as an immutable dictionary key

Formatting Strings Can create strings using a formatting (% placeholder) specifier Formatting borrowed from ‘c’ language Concatenation (+) only works when combining strings Examples >>> print "%s two %s" % ("joining", "strings") joining two strings >>> print "today is %d / %d / %d" % (20, 2, 2006) today is 20 / 2 / 2006

Conclusion Some details skipped over (import modules, __name__ for debugging) Homework: make sure you understand aliasing def buildConnectionString(params): """Build a connection string from a dictionary of parameters. Returns string.""" return ";".join(["%s=%s" % (k, v) for k, v in params.items()]) if __name__ == "__main__": myParams = {"server":"mpilgrim", \ "database":"master", \ "uid":"sa", \ "pwd":"secret" \ } print buildConnectionString(myParams)