CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)

Slides:



Advertisements
Similar presentations
Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
Advertisements

A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
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?
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Structured programming
Python Crash Course by Monica Sweat. Python Perspective is strongly typed, interpreted language is used to define scripts (Don't even need to define a.
Guide To UNIX Using Linux Third Edition
1 Outline 7.1 Introduction 7.2 Implementing a Time Abstract Data Type with a Class 7.3 Special Attributes 7.4Controlling Access to Attributes 7.4.1Get.
PHP Server-side Programming. PHP  PHP stands for PHP: Hypertext Preprocessor  PHP is interpreted  PHP code is embedded into HTML code  interpreter.
Python Control of Flow.
CS 11 C track: lecture 1 Preliminaries Need a CS cluster account cgi-bin/sysadmin/account_request.cgi Need to know UNIX ITS.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
“Everything Else”. Find all substrings We’ve learned how to find the first location of a string in another string with find. What about finding all matches?
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
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
H3D API Training  Part 3.1: Python – Quick overview.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
If statements while loop for loop
Python – May 11 Briefing Course overview Introduction to the language Lab.
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Introduction to Information Security Python. Python motivation Python is to a Hacker what Matlab is to an engineer Lots of built-in modules Lots of 3.
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.
CSCI/CMPE 4341 Topic: Programming in Python Review: Exam I Xiang Lian The University of Texas – Pan American Edinburg, TX 78539
Python Functions.
CSC 110 Using Python [Reading: chapter 1] CSC 110 B 1.
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.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Prof. Hilfinger CS164 Lecture 51 The Pyth Language Lecture 5.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
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.
PHP vs. Python. Similarities are interpreted, high level languages with dynamic typing are Open Source are supported by large developer communities are.
Python Let’s get started!.
General Computer Science for Engineers CISC 106 Lecture 12 James Atlas Computer and Information Sciences 08/03/2009.
A Tutorial on the Python Programming Language. Overview Running Python and Output Data Types Input and File I/O Control Flow Functions.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 8 Java Fundamentals Control Structures Fri.
Python Basics  Functions  Loops  Recursion. Built-in functions >>> type (32) >>> int(‘32’) 32  From math >>>import math >>> degrees = 45 >>> radians.
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Python Basics  Values, Types, Variables, Expressions  Assignments  I/O  Control Structures.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
CSC 108H: Introduction to Computer Programming Summer 2012 Marek Janicki.
Fundamentals of Programming I Overview of Programming
CS170 – Week 1 Lecture 3: Foundation Ismail abumuhfouz.
Python Let’s get started!.
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
CSC 108H: Introduction to Computer Programming
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Introduction to Python
PH2150 Scientific Computing Skills
What Is a Program? A program is like an algorithm, but describes a process that is ready or can be made ready to run on a real computer Retrieved from:
Introduction to Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
CISC101 Reminders All assignments are now posted.
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
Learning Python 5th Edition
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)

Overview Administration issues Class survey Syllabus Etc. Getting started with examples First assignment

Setting Up a CS Account Get an account from the CS department CS department offers guest account Do all assignments on CS Unix machines They will be graded on CS Linux/Unix CS account comes with webspace Needed for some assignments

What is python? Object oriented language Interpreter language Support dynamic data type Independent from platforms Focused on development time Simple and easy grammar High-level internal object data types Automatic memory management It’s free (open source)!

Why learn python? Fun-to-use "Scripting language" Object-oriented Highly educational Very easy to learn Powerful, scalable, easy to maintain high productivity Lots of libraries Glue language Interactive front-end for C/C++ code

Why learn python? (cont.) Reduce development time Reduce code length Easy to learn and use as developers Easy to understand codes Easy to do team projects Easy to extend to other languages Interactive front-end for C/C++ code

Where to use python? System management (i.e., scripting) Graphic User Interface (GUI) Internet programming Database (DB) programming Text data processing Distributed processing Numerical operation Graphics And so on…

python syntax Much of it is similar to C syntax Exceptions: missing operators: ++, -- no {} for blocks; uses whitespace different keywords lots of extra features no type declarations!

Starting and exiting python % python Python >>> print "hello" hello >>> ^D %

Simple data types Numbers Integer, floating-point, complex! Strings characters are strings of length 1 Booleans are False or True

Simple data types: operators + - * / % (like C) += -= etc. (no ++ or -- ) Assignment using = but semantics are different! a = 1 a = "foo" # OK Can also use + to concatenate strings

Compound data types (1) Lists: a = [1, 2, 3, 4, 5] print a[1] # 2 some_list = [] some_list.append("foo") some_list.append(12) print len(some_list) # 2

Compound data types (2) Dictionaries: like an array indexed by a string d = { "foo" : 1, "bar" : 2 } print d["bar"] # 2 some_dict = {} some_dict["foo"] = "yow!" print some_dict.keys() # ["foo"]

Compound data types (3) Tuples: a = (1, 2, 3, 4, 5) print a[1] # 2 empty_tuple = () lists vs. tuples: lists are mutable; tuples are immutable lists can expand, tuples can’t tuples slightly faster

Compound data types (3) Objects: class thingy: # next week’s lecture t = thingy() t.method() print t.field Built-in data structures (lists, dictionaries) are also objects though internal representation is different

Control flow (1) if, if/else, if/elif/else if a == 0: print "zero!" elif a < 0: print "negative!" else: print "positive!"

Control flow (2) Notes: blocks delimited by indentation! colon (:) used at end of lines containing control flow keywords

Control flow (3) while loops a = 10 while a > 0: print a a -= 1

Control flow (4) for loops for a in range(10): print a really a "foreach" loop

Control flow (5) Common for loop idiom: a = [3, 1, 4, 1, 5, 9] for i in range(len(a)): print a[i]

Control flow (6) Common while loop idiom: f = open(filename, "r") while True: line = f.readline() if not line: break # do something with line

aside: open() and file() These are identical: f = open(filename, "r") f = file(filename, "r") The open() version is older The file() version is the recommended way to open a file now uses object constructor syntax (next lecture)

aside 2: file iteration Instead of using while loop to iterate through file, can write: for line in file: # do something with line... More concise, generally considered better

Control flow (7): odds & ends continue statement like in C pass keyword: if a == 0: pass # do nothing else: # whatever

Defining functions def foo(x): y = 10 * x + 2 return y All variables are local unless specified as global Arguments passed by value

Executing functions def foo(x): y = 10 * x + 2 return y print foo(10) # 102

Comments Start with # and go to end of line What about C, C++ style comments? NOT supported!

Writing standalone scripts Can execute any file like this: % python myprog.py Might want file to be directly executable, so... at top of file, write this: #! /usr/bin/env python # code goes here... Then make file executable: % chmod +x myprog.py % myprog.py

File naming conventions python files usually end in.py but executable files usually don’t have the.py extension modules (later) should always have the.py extension

Strings and formatting i = 10 d = s = "I am a string!" print "%d\t%f\t%s" % (i, d, s) print "no newline",

Modules (1) Access other code by importing modules import math print math.sqrt(2.0) or: from math import sqrt print sqrt(2.0)

Modules (2) or: from math import * print sqrt(2.0) Can import multiple modules on one line: import sys, string, math Only one " from x import y " per line

Modules (3) NOTE! from some_module import * should be avoided dumps all names from some_module into local namespace easy to get inadvertent name conflicts this way

Modules (4) Code you write in file foo.py is part of module " foo " Can import this code from within other files: import foo # code that uses stuff from foo

Command-line arguments import sys print len(sys.argv) # NOT argc # Print all arguments: print sys.argv # Print all arguments but the program # or module name: print sys.argv[1:] # "array slice"

File I/O f = file("foo", "r") line = f.readline() print line, f.close() # Can use sys.stdin as input; # Can use sys.stdout as output.