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.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Introduction to Python
Intro to Python Paul Martin. History Designed by Guido van Rossum Goal: “Combine remarkable power with very clear syntax” Very popular in science labs.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Announcements Project 2 Available Tomorrow (we will send mail) Will be due 11:59PM October 9 th (Sunday) Week 6 ( I will be traveling this week) Review.
Lists in Python.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
CPTR 124 Review for Test 1. Development Tools Editor Similar to a word processor Allows programmer to compose/save/edit source code Compiler/interpreter.
CSE 1301 Lecture 2 Data Types Figures from Lewis, “C# Software Solutions”, Addison Wesley Richard Gesick.
Input, Output, and Processing
CPS120: Introduction to Computer Science Decision Making in Programs.
Built-in Data Structures in Python An Introduction.
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
With Python.  One of the most useful abilities of programming is the ability to manipulate files.  Python’s operations for file management are relatively.
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.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
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.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
JavaScript, Fourth Edition
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
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.
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.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Introduction to Python Sajal Desai. What is Python? Versitile, simple, high level language No linking and compilation “By the way, the language is named.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 next week. See next slide. Both versions of assignment 3 are posted. Due today.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
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.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
Q and A for Sections 2.9, 4.1 Victor Norman CS106 Fall 2015.
Lecture III Syntax ● Statements ● Output ● Variables ● Conditions ● Loops ● List Comprehension ● Function Calls ● Modules.
String and Lists Dr. José M. Reyes Álamo.
Topics Designing a Program Input, Processing, and Output
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Introduction to Python
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
CHAPTER FOUR Functions.
Arithmetic operations, decisions and looping
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Introduction To Python
An Introduction to Python
String and Lists Dr. José M. Reyes Álamo.
Python Primer 1: Types and Operators
CISC101 Reminders All assignments are now posted.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Introduction to Computer Science
COMPUTER PROGRAMMING SKILLS
Topics Introduction to File Input and Output
CISC101 Reminders Assignment 3 due today.
Class code for pythonroom.com cchsp2cs
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

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 interpreter just type “python” and just issue python commands (called interactive mode) FUN FACT: no semicolons needed in python! FUN FACT: in Python, the last printed expression can be referenced as an automatically stored variable called “_” in interactive mode

Argument passing To access arguments passed in a python script type “import sys” and the arguments are stored in sys.argv When no arguments are given, sys.argv[0] is an empty string

To handle error Type Control-C or DELETE (the interrupt character) cancels the input and returns to the main prompt If a command is being executed, it raises the KeyboardInterrupt exception which could be handled with a try statement

Things about Python scripts # designates comments “$ chmod +x myscript.py” to make a script executable in Unix, and “#! /usr/bin/env python” must go at the beginning of the script “import” at the beginning of a script to make it import things After the initial “#!” line one can define the source coding style with a special comment like “# -*- coding: iso *-” If you want the python interpreter to do certain things during start-up, you can set an environment variable called “PYTHONSTARTUP” to the name of the file containing the startup commands

Numbers in Python Python interpreter can be used as a straight up calculator like 2+2 will come out as 4 with no extra syntax Integer division/multiplication returns the floor, and integer + floating point operations return floating point An equal sign assigns a value to a variable but can do it to several variables at once like “x=y=z=0” Can also assign like so “a, b = 0, 1” and a=0, b=1 Variables don’t need type designation, but of course need a value to be used or else an error will occur Complex numbers are supported as well in the form of a = complex(real,imaginary) or a = j and returned as (real+imaginaryj); can be accessed in parts like a.real, a.imag, or abs(a) gives its magnitude

Strings in Python Strings can be in single or double quotes, but usually in single quotes unless the string is a single quote in two double quotes A string can span several lines of code; newline character is \n, and to indicate that the next line is a continuation of the last the \ character is used Type “print” to print a string or just a given value of a whole expression Can also surround strings in triple quote pairs “”” “”” or ‘’’ ‘’’ and then newline characters don’t need escaping

More about strings in Python Strings can be concatenated with “+” and if the strings are just string literals they can be concatenated with just a space between them like word = “lame” “Ya” word = “lameYa” Strings can be indexed like char arrays in C, so word[0] = l Colon has different effects in indexing: “word[0:2] = la” or “word[:2] = la” or “word[2:] = meYa” If an index is too large it is replaced by the string size like for example “word[1:1000] = ameYa” If an index is too small or too negative it is truncated unless it is a single-element reference (yes, you can use negative indices as long as the last element is 0)

More on strings Can’t change parts of strings in python, but can easily create a new string len(string) returns its length, but length of a slice is index2-index1 u‘string’ indicates a unicode based string and Python Unicode-Escape encoding can be used for characters then or ur‘string’ for raw unicode unicode() gives access to all Unicode codecs, unicode strings can be converted with str() to normal strings string.encode(‘utf-8’) will encode in 8-bit or in whatever coding is specified in encode()

Lists in Python list = [123, ‘abc’] is a list Can be indexed and concatenated like strings (but not using a space) Slice operations return a new list of the indexed elements Individual elements of a list can be changed and can be replaced by slice operations like list[0:1] = 3  list = [3, ‘abc’] len() still gives length, range() generates arithmetic progressions of numbers in a list like range(5,20,5) = [5,10,15,20] lists can contain other lists mixed with single elements like list = [[‘k’, 23], ‘f’, 5]

Some syntax There is no {} for while or for loops or for if statements, there must be a tab or spaces for each indented line, everything within a block by the same amount Loop conditions don’t need to be written in parentheses To instead print spaced answers instead of by newline with print in a while loop use print b, next line instead of print b next line (trailing comma dodges the newline after output)

Control Flow in Python If statements don’t need elif or else parts but can have as many elifs as needed, “if elif elif” statement is equivalent to a switch or case statement For statements work as an iteration over items of a list or sequence like “for x in list[:]:” and then the items are executed in order that they appear Can use “for i in range(len(list)): print i, a[i];” to get an iteration through the list easily

More on Control Flow break statement breaks out of smallest enclosing loop, to move on with going to “else” in an if statement for example continue statement moves on with next iteration of the loop pass statement does nothing and is used syntactically for things like empty classes or used as a placeholder when you are working on a function or condition

Functions in Python The term “def” introduces the definition of a function and is followed by a function name and in parentheses a list of arguments def statement is like “def func(number):” By default all variable assignments in a function store local variables return is used to give back a result Function can be renamed as a variable and stored to be used in the interpreter like “f = func f(423)” >>> output variable.append(new stuff) is the more efficient way to concatenate new elements at the end of a list in a function

Some more function stuff To assign default values one just needs to set each argument in the definition to a value like: “def func(number=100, why=“not”, tiny)” Also, “in” can be used to test if a sequence has a value like “if func in (‘no’, ‘not’) return True” If the default value is a mutable object, it is evaluated only once, and a function can accumulate arguments like “def func(thing, list=[]) list.append(thing) return list” for “print func(1), func(‘f’), func(10)” This would print “[1], [1,’f’], [1,’f’,10]” To fix the above just put if list is None for each call so that it doesn’t append continually

A bit more on functions If a function is written like so “def func(arg, *name, **args)” then the formal parameter **args acts as dictionary containing the keyword arguments except for the whats already a formal parameter or *name in this case which just contains the positional arguments (a variable number not including ** args after *name) Like in def func(arg1, *name, **args) for arg in name: print arg key = args.keys() for keyword in key: print keyword, “-”, key[keyword] “func(“hi”, “bye”, “try”, haha = “three”, nine = “five”)” would make bye try haha – three nine – five Functions can be called with arbitrary number of arguments Dictionaries can deliver keyword arguments into a function using the ** operator and the *operator can unpack arguments from a list/tuple lambda function can be used to make small anonymous function inside function definition Like “def super(arg): return lambda q: q * arg” can be used to say “func=super(5) func(5)” func(5) is equal to 25 and func(10) = 50

Documentation and Style Try using 4-space indentation instead of tabs Type a string in a function definition without print in front of it and it can be seen by type func.__doc__ to see what is called the docstring

Done! Any questions?