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.

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

Arrays A list is an ordered collection of scalars. An array is a variable that holds a list. Arrays have a minimum size of 0 and a very large maximum size.
ThinkPython Ch. 10 CS104 Students o CS104 n Prof. Norman.
Container Types in Python
ECS 15 if and random. Topic  Testing user input using if statements  Truth and falsehood in Python  Getting random numbers.
Python Programming Language
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.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Guide To UNIX Using Linux Third Edition
JaySummet IPRE Python Review 2. 2 Outline Compound Data Types: Strings, Tuples, Lists & Dictionaries Immutable types: Strings Tuples Accessing.
Python Control of Flow.
Lilian Blot CORE ELEMENTS COLLECTIONS & REPETITION Lecture 4 Autumn 2014 TPOP 1.
Python quick start guide
Lists in Python.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Handling Lists F. Duveau 16/12/11 Chapter 9.2. Objectives of the session: Tools: Everything will be done with the Python interpreter in the Terminal Learning.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
>>> # 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.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
If statements while loop for loop
Built-in Data Structures in Python An Introduction.
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.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Introduction to Java Java Translation Program Structure
Python Functions.
_______________________________________________________________________________________________________________ PHP Bible, 2 nd Edition1  Wiley and the.
CS 105 Perl: Data Types Nathan Clement 15 May 2014.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Prof. Hilfinger CS164 Lecture 51 The Pyth Language Lecture 5.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
RUBY by Ryan Chase.
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.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
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: รัฐภูมิ เถื่อนถนอม
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.
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.
A thorough introduction to Python. What is Python exactly? Python is a modern rapid development language. – Emphasizes single, intuitive approach to most.
Introduction to python programming
String and Lists Dr. José M. Reyes Álamo.
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Introduction to Python
Computer Programming Fundamentals
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.
Python: Control Structures
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
Python Primer 2: Functions and Control Flow
Introduction To Python
CHAPTER THREE Sequences.
Introduction to Python
An Introduction to Python
CS190/295 Programming in Python for Life Sciences: Lecture 6
String and Lists Dr. José M. Reyes Álamo.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python Primer 1: Types and Operators
Python Review
Learning Python 5th Edition
Selamat Datang di “Programming Essentials in Python”
Presentation transcript:

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 single, intuitive approach to most problems. Everything can be modified dynamically. Highly object oriented.

When should you use Python? Small to medium projects that may grow over time. Where the ability to run anywhere is desired. Where the ability to interface with a variety of languages and systems is important. Where the amount of time the program takes to write is more important than the amount of time it takes to run.

Python is highly object oriented Everything is an object – Data types – Collections – Functions – Modules

Data types What are data types? Data types are simple objects that are coded directly into the python interpreter. Data types are the basic unit of information storage. Instances of data types are unique (in Python).

Python data types These are the most basic (and most frequently used) data types: Integer – 0, 7, 13, 21, -1 Floating point – 3.14, 2.718, String – “1”, “2.718”, “True”, “None”, “etc…” Boolean – True, False Null – None

Collections What are collections? Collections are containers that hold other objects. Some collections will let you organize the their contents, and some are not as cooperative. Each collection type provides special features that make it useful in different circumstances.

Python collection types List – an ordered, zero-indexed collection of objects, for example: [1, “A”, 3.0] Set – an unordered collection of elements, guarantees each element is unique. For example: {1, “A”, 3.0} Dictionary – an unordered collection of key/value pairs. Each key is unique. For example: {1:”One”, “A”:5, 3.0:”Three”}

Basic language structure Python abandons many of the common language formatting idioms. Newline terminates a command – no semicolon required. Indentation alone designates nested code blocks – no curly braces required. A ‘#’ denotes the start of a single line comment.

Indentation matters Unlike most programming languages, newlines and indentation are syntax in python. Functions, nested loops and conditionally evaluated code are all indicated using indentation. Consider the following valid python code: if something is True: do_something_else()

Basic numerical operations The +, -, *, /, % (modulo) and ** (power-of) all behave roughly as expected. The = 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 A == 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. An is tests to see if two things have the same identity. An in tests element membership in a collection.

Boolean algebra in Python Any value, other than None, False, 0, “”, or an empty collection evaluates to True in a boolean context. The boolean operators supported by python, in order of increasing precedence, are: 1.and 2.or 3.not

Basic flow control Python provides flow control using if, for and while statements. You can terminate a for or while loop using break. You can skip to the next iteration of a for or while loop using continue. You can execute code after a for or while loop that is not terminated early using else.

Example: if statement if x < 0: print “x is less than 0” elif x == 0: print “x is 0” elif x == 1: print “x is 1” else: print “x is greater than 1” There can be zero or more elif conditions. The else condition is optional. The first condition that evaluates to True has its code executed, and no further conditions are examined.

Practice intermission! Time to see if you’ve been paying attention. Go to We’ll work through sleep_in together. Please try monkey_trouble yourself. If you finish quickly, try other exercises!

Example: for statement mylist = [‘cat’, ‘dog’, ‘goat’] for animal in mylist: print “I have a “ + animal When run, this results in: I have a cat I have a dog I have a goat The for statement in python is unique in that it works over collections (or things that act like collections).

Example: break and continue statements. for number in [2, 3, 4, 5, 6, 7, 8, 9]: if number % 2 == 0: print “%s is even” % number elif number > 7: break else: continue print “I will never be seen”

Defining Functions Functions are defined in python using the def key word. The format of a function definition is def function_name(comma, separated, arguments): … After a function definition, any indented lines are considered part of the function.

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: def make_circle(size, color=“white”, outline=True): …

Keyword Arguments Functions can be called using keyword arguments. Take the following function: def parrot(age=10, state=‘awake’, type=‘African Grey’) This could be called a variety of ways: parrot(25) parrot(15, type=“Norwegian Blue”) parrot(state=“asleep”) Etc…

Strings and Things Strings in Python are created with paired single or double quotes. 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“””). The + and * operators are work for strings, so “help” + “ me” produces the string “help me”, and “help” * 3 produces “helphelphelp”.

Another practice intermission Go to Try string_times using a trick you just learned for an easy warmup. Try array_count9 for a slightly larger challenge. As before, if you’re quick work ahead!

String Formatting Operations String can be formatted via the % operator. If you are only substituting a single value you may pass it directly after the %. If you are passing multiple values you must wrap them in parenthesis. For example: “I have %s cats” % 10 “I have %s cats and %s dogs” % (5, 3)

Meet the List Lists are mutable, ordered collections of objects. Any type of object can be put in a list Lists may contain more than one type of object at a time. The + and * operators perform the same magic on lists that they do on strings.

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. For example: “Help”[0] is “H” “Help”[0:2] is “He” “Help”[2:4] is “lp”

Subscripts, continued Subscript slices can be bounded on only one end, for instance: “Help”[1:] is “elp” “Help”[:2] is “He” Subscripts can also be negative, to indicate position relative to the end of the sequence: “Help”[-1] is “p” “Help”[-3:-1] is “el” Subscript slices will return an empty result if you use indices that are out of bounds or otherwise bad. “Help”[5:10] is “”

Another practice session Head back to Try your hand at array_front9 using array slices and Python’s nifty in feature. Use slices and the same string multiplication trick to complete front_times.

The Set A set object is an unordered collection of distinct immutable objects. Common uses include membership testing and removing duplicates from a sequence. Support x in set, len(set), and for x in set. Does not support indexing, slicing, or other sequence-like behavior.

The Dictionary A dictionary maps key objects to to arbitrary value objects. Dictionaries are accessed using square brackets like a list (slicing is not supported). For example: My_dictionary = {“A”:1, 0:”Zero”, “B”:2} My_dictionary[“A”] is 1 My_dictionary[0] is “Zero” You can set new values like so: My_dictionary[“B”] = 3 My_dictionary[1] = “One” Supports x in dict, len(dict) and for x in dict.

Modules 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 it into each program. Python makes this easy – if your file is somewhere in the PYTHONPATH, you can do the following: import yourfile Then you can access stuff in that file like this: Yourfile.yourfunction()