PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.

Slides:



Advertisements
Similar presentations
CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
Advertisements

CS 100: Roadmap to Computing Fall 2014 Lecture 0.
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.
I210 review Fall 2011, IUB. Python is High-level programming –High-level versus machine language Interpreted Language –Interpreted versus compiled 2.
What is a scripting language? What is Python?
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
JavaScript, Third Edition
Fundamentals of Python: From First Programs Through Data Structures
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Python.
Fundamentals of Python: First Programs
CIS Computer Programming Logic
 1 Week3: Files and Strings. List List is a sequence of data in any type. [ “Hello”, 1, 3.7, None, True, “You” ] Accessing a list is done by the bracket.
Introduction to Python
Python Programming Chapter 10: Dictionaries Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Created by, Author Name, School Name—State FLUENCY WITH INFORMATION TECNOLOGY Skills, Concepts, and Capabilities.
Introduction to Python John Reiser May 5 th, 2010.
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.
Python Control Flow statements There are three control flow statements in Python - if, for and while.
Python Programming Chapter 7: Strings Saad Bani Mohammad Department of Computer Science Al al-Bayt University 1 st 2011/2012.
Control Structures – Selection Chapter 4 2 Chapter Topics  Control Structures  Relational Operators  Logical (Boolean) Operators  Logical Expressions.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Programming in Python Part III Dr. Fatma Cemile Serçe Atılım University
Built-in Data Structures in Python An Introduction.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Math 15 Introduction to Scientific Data Analysis Lecture 8 Python Programming – Part 2 University of California, Merced.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
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.
Python Let’s get started!.
Python Mini-Course University of Oklahoma Department of Psychology Day 3 – Lesson 11 Using strings and sequences 5/02/09 Python Mini-Course: Day 3 – Lesson.
COMPE 111 Introduction to Computer Engineering Programming in Python Atılım University
Midterm Review Important control structures Functions Loops Conditionals Important things to review Binary Boolean operators (and, or, not) Libraries (import.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
Xi Wang Yang Zhang. 1. Easy to learn 2. Clean and readable codes 3. A lot of useful packages, especially for web scraping and text mining 4. Growing popularity.
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
Python Strings. String  A String is a sequence of characters  Access characters one at a time with a bracket operator and an offset index >>> fruit.
Python Arithmetic Operators OperatorOperationDescription +AdditionAdd values on either side of the operator -SubtractionSubtract right hand operand from.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Python Basics 본 자료는 다음의 웹 사이트를 정리 한 내용이니 참조 바랍니다. ythonBasics.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Dictionaries. The compound types you have learned about - - strings, lists, and tuples – use integers as indices. If you try to use any other type as.
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.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
Python Basics.
Chapter 2 Writing Simple Programs
String and Lists Dr. José M. Reyes Álamo.
G. Pullaiah College of Engineering and Technology
Fundamentals of Programming I Overview of Programming
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
CSc 120 Introduction to Computer Programing II Adapted from slides by
Introduction to Python
Module 4 String and list – String traversal and comparison with examples, List operation with example, Tuples and Dictionaries-Operations and examples.
Intro To Pete Alonzi University of Virginia Library
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Engineering Innovation Center
CHAPTER 7 STRINGS.
Python Primer 2: Functions and Control Flow
CHAPTER THREE Sequences.
© 2016 Pearson Education, Inc., Hoboken, NJ. All rights reserved.
CS190/295 Programming in Python for Life Sciences: Lecture 6
Data types Numeric types Sequence types float int bool list str
T. Jumana Abu Shmais – AOU - Riyadh
String and Lists Dr. José M. Reyes Álamo.
Python Primer 1: Types and Operators
COMPUTER PROGRAMMING SKILLS
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

PYTHON PROGRAMMING

WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library is large  Has many useful modules (math, image, GUI, etc)

WHY PYTHON  Easy to learn  Excellent for beginners and experts  Scripting language designed to automate the execution of tasks.  Suitable for projects, large or small  Cross-platform (Windows, Mac OS, Unix) 3

THE BENEFIT TO KNOW PYTHON  A useful tool for your academic/professional career!  A very useful complementary tool for other programming languages (if you know C++, C#, Java already)  GIS professionals need this tool  Development with ESRI products (ArcPy)  Many open source GIS resources (APIs) 4

VARIABLE  How to name variables?  Meaningful: document what the variables are used for.  Must be legal: cannot be reserved words.  Follow the rules of an identifier  Start with a letter or underscore  Case sensitive!!!

DATA TYPES  An int and a float are simple data types.  A string (str) is a compound data type, because it consists of smaller pieces.  A string is a sequence of characters! fruit = "apple" letter_1 = fruit[0] letter_5 = fruit[4] print letter_1 print letter_5 >>> a >>> e

STRING MANIPULATION  slice out a sub-string from a string Index value string [a : b] Start Included End Excluded s = ‘Hello’ part = s[1 : 4] part ‘ell’

STRINGS ARE IMMUTABLE!  A string’s contents can NOT be modified  Not working by modifying: greeting = "Hello, world!" greeting[0] = ‟ J ‟ # ERROR! Can’t modify it  It works by creating a new string greeting = "Hello, world!" #create a new one newGreeting = ‟ J ‟ + greeting[1:]

WHAT IS A LIST?  A list is a sequence of values.  A string can be regarded as a sequence of characters.  The values in a list are called elements (or items).  The elements are separated by comma (,)  The elements in a list can be any type.

CREATE A LIST  The simplest way to create a list is to enclose the elements in a pair of square brackets []:  A list can be heterogeneous ["hello", 2.0, 5, [10, 20]]  Yes, empty lists [] are allowed. Nested cities= [“Boston", “Worcester"] numbers = [17, 123] empty = []

ACCESSING ELEMENTS  Elements in a list can be accessed using the index. Cheeses=[‘Cheddar’, ‘Edam’, ‘Gouda’] Cheeses [0]  ‘Cheddar’ Cheeses [1]  ‘Edam’ Cheeses [2]  ‘Gouda’

WHAT IS A TUPLE?  In Python, a tuple is similar to a list except that it is immutable  A tuple is defined within a pair of parentheses >>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’) >>> tuple[0] = ’A’ # not allowed! TypeError: object doesn’t support item assignment

ACCESS TUPLE ELEMENT  Very similar to how you access list elements. >>> tuple = (’a’, ’b’, ’c’, ’d’, ’e’) # get one element >>> tuple[0] ’a’ # get a subset of a tuple >>> tuple[1:3] (’b’, ’c’)

WHAT IS A DICTIONARY?  A dictionary is a list of key : value pairs  The order of the key-value pairs does not stay the same.  In fact, the order of items in a dictionary is unpredictable. eng2sp = {'one': 'uno', 'two': 'dos', 'three': 'tres'} >>> print eng2sp {'one': 'uno', 'three': 'tres', 'two': 'dos'}

CREATE A DICTIONARY create a dictionary by providing a list of k ey-value pairs >>> eng2sp = { ‟ one ‟ : ‟ uno ‟, ‟ two ‟ : ‟ dos ‟, ‟ three ‟ : ‟ tres ‟ } >>> print eng2sp { ‟ one ‟ : ‟ uno ‟, ‟ three ‟ : ‟ tres ‟, ‟ two ‟ : ‟ dos ‟ } >>> print eng2sp[ ‟ two ‟ ] ‟ dos ‟ >>> dic = {1:”one”, 2:”two”, 1:”uno”} # How does Python deal with it?

DICTIONARY OPERATIONS  Create a dictionary called inventory inventory = {'apples':430, 'bananas': 312, 'oranges': 525, 'pears': 217}  Print its contents >>> print inventory {'pears': 217, 'apples': 430, 'oranges': 525, 'bananas': 312}  Del the ‘pears’ element >>> del inventory['pears']  Check the length # the len() works for string, list, tuples, and dictionaries >>> len(inventory) 3

BOOLEAN EXPRESSIONS  True and False are Boolean values in Python  An Boolean expression yields either True or False.  Relational Operators / Comparison Operators are often used in Boolean expressions: == != > >= < <= equal to not equal to greater than greater than or equal to less than less than or equal to

LOGICAL OPERATORS  Logical operators are often used in building Boolean expressions.  Three logical operators: and, or, and not Expression True and False True or False not False not True Result False True False Examples: >>> x = True >>> y = False >>> z = x and y >>> z False >>> z = x or y >>> z True

CONDITIONAL EXECUTION (IF)  We often need the ability to check conditions and change the behavior of the program accordingly. x = 5 if x>0: print x, "is positive" y = -5 if y < 0: print y, 'is negative' 5 is positive -5 is negative Output in the Interactive Window

ALTERNATIVE EXECUTION (IF/ELSE) The if/else structure for alternative execution: if x%2 == 0: print x, "is even." else: print x, "is odd."

if choice == “A”: functionA() elif choice == “B”: functionB() elif choice == “C”: functionC() else: print "Invalid choice." functionC() print “Invalid choice” choice==‘A’ True functionA() False choice==‘B’ True functionB() False choice==‘C’ True False Flowchart of this alternative execution

DEFINING FUNCTIONS Syntax: def NAME (LIST OF PARAMETERS): STATEMENTS Example: # function definition def printInfo(): print 'Python version is 2.7!' # Call function printInfo() Indentation for the body of a function: Function definition: Function call

THE RETURN STATEMENT import math def printLogarithm(x): if x <= 0: print “The input number must be positive." return The return statement terminates the execution of the function immediately result = math.log(x) #log10 for common logarithm print "The natural logarithm of", x, "is", result The return here does NOT really return anything.

FRUITFUL FUNCTIONS Fruitful functions are those functions that return values. Example 1: import math # circle-area calculation def calarea(radius): area = math.pi * radius**2 return area r=1 print "The area of a circle with a radius of", r, ”is ", calarea(r) r=2 print "The area of a circle with a radius of", r, ”is ", calarea(r) r=3 print "The area of a circle with a radius of", r, ”is ", calarea(r)

THE WHILE STATEMENT  Computers are often used to automate repetitive tasks.  Python provides statements (for and while) to achieve iteration. Step 1 Evaluate the condition, yielding True or False Step 2 If the condition is false, exit the statement and continue execution at the next statement. Step 3 If the condition is true, execute the body and then go back to step 1.

FOR LOOP  for loops are used when you have a piece of code which you want to repeat n times. for iterating_var in sequence: statements Recall the Traversal Example fruit = “apple" # use ‘for … in …’ to traverse a string for char in fruit: print char

READ AN EXISTING TEXT FILE  Like how you read a file: open ()  read ()  close() strFolderPath = 'd:\\Intro2Python\\Files\\' strFileName = ‘ReadMe.txt' strFullPath = strFolderPath + strFileName f2 = open(strFullPath,'r') str= f2.read() # read the whole file f2.close() print str Output Clark University is in Worcester. Worcester is in Massachusetts. Read-only Mode

WRITE A NEW TEXT FILE  Like how you write a file: open ()  write ()  close() strFolderPath = 'd:\\Intro2Python\\Fall2012\\Files\\' strFileName = ‘NewFile.txt' strFullPath = strFolderPath + strFileName f=open(strPathName, 'w') #’w’ is for ‘writing’ mode. # if a file with the same name exits, # its contents are removed. f.write('Clark University is in Worcester.\n') f.write('Worcester is in Massachusetts.') f.close()