Introduction to Programming with Python Marty Stepp University of Washington Special thanks to Scott Shawcroft, Ryan Tucker,

Slides:



Advertisements
Similar presentations
Week 1 basic Python programs, defining functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Advertisements

Week 5 while loops; logic; random numbers; tuples Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except.
Working with JavaScript. 2 Objectives Introducing JavaScript Inserting JavaScript into a Web Page File Writing Output to the Web Page Working with Variables.
Week 4 Strings, if/else, return, user input Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Week 4 gur zntvp jbeqf ner fdhrnzvfu bffvsentr Strings, if/else, return, user input Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their.
Strings, if/else, return, user input
Week 1 basic Python programs, defining functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
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.
JavaScript, Third Edition
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
INTRODUCTION TO PYTHON PART 4 – TEXT AND FILE PROCESSING CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
INTRODUCTION TO PYTHON PART 3 - LOOPS AND CONDITIONAL LOGIC CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
INTRODUCTION TO PYTHON PART 1 CSC482 Introduction to Text Analytics Thomas Tiahrt, MA, PhD.
1 Building Java Programs Chapter 1: Introduction to Java Programming These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may.
Python. What is Python? A programming language we can use to communicate with the computer and solve problems We give the computer instructions that it.
1 Introduction to Programming with Python. 2 Some influential ones: FORTRAN science / engineering COBOL business data LISP logic and AI BASIC a simple.
Fundamentals of Python: From First Programs Through Data Structures
Introduction to MATLAB ENGR 1187 MATLAB 1. Programming In The Real World Programming is a powerful tool for solving problems in every day industry settings.
Ruby (on Rails) CSE 190M, Spring 2009 Week 1. The Players Kelly "Everyday I'm Hustlin' " Dunn Kim "Mouse" Todd Ryan "Papa T" Tucker.
Unit 5 while loops; logic; random numbers; tuples Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work.
Python  By: Ben Blake, Andrew Dzambo, Paul Flanagan.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
An Introduction to Textual Programming
1 Lab Session-III CSIT-120 Fall 2000 Revising Previous session Data input and output While loop Exercise Limits and Bounds Session III-B (starts on slide.
Computing with Numbers CSC 161: The Art of Programming Prof. Henry Kautz 9/14/2009.
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.
Python Lesson Week 01. What we will accomplish today Install Python on your computer Using IDLE interactively to explore String Variables if/else while.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
PYTHON: PART 2 Catherine and Annie. VARIABLES  That last program was a little simple. You probably want something a little more challenging.  Let’s.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Ruby on Rails. What is Ruby? Programming Language Object-oriented Interpreted.
C++ Programming: Basic Elements of C++.
PHP Logic. Review: Variables Variables: a symbol or name that stands for a value – Data types ( Similar to C++ or Java): Int, Float, Boolean, String,
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Week 1 basic Python programs, defining functions Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where.
Unit 1 Basic Python programs, functions Special thanks to Roy McElmurry, John Kurkowski, Scott Shawcroft, Ryan Tucker, Paul Beck for their work. Except.
CSC 1010 Programming for All Lecture 3 Useful Python Elements for Designing Programs Some material based on material from Marty Stepp, Instructor, University.
Introduction to Programming with Python
1 Introduction to Programming with Python: overview.
1/10/2008. >>> About Us Paul Beck * Third quarter TA * Computer Engineering * Ryan Tucker * Second quarter TA * Computer.
If/else, return, user input, strings
8/2/07. >>> About Me Scott Shawcroft * Junior * Computer Engineering * Third Quarter TA * Creative Commons Intern * Small-time Open Source Developer
Introduction to Python Developed by Dutch programmer Guido van Rossum Named after Monty Python Open source development project Simple, readable language.
CS 106A, Lecture 4 Introduction to Java
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
Introduction to Programming with Python
Introduction to Programming
Primitive Data, Variables, Loops (Maybe)
Variables, Expressions, and IO
basic Python programs, defining functions
Week 4 gur zntvp jbeqf ner fdhrnzvfu bffvsentr
Arithmetic operations, decisions and looping
Introduction to Python
basic Python programs, defining functions
while loops; logic; random numbers; tuples
Introduction to programming with Python
A look at Python Programming Language 2018.
Introduction to Programming with Python
SSEA Computer Science: Track A
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Unit 3: Variables in Java
Introduction to Programming with Python
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Introduction to Programming with Python Marty Stepp University of Washington Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under:

2 Outline Programming languages and Python Basic programs and numeric data Control statements Text processing What's next? / CSE 142 at UW

3 Languages Some influential ones: –FORTRAN science / engineering –COBOL business data –LISP logic and AI –BASIC a simple language

4 Python Created in 1991 by Guido van Rossum (now at Google) –Named for Monty Python Useful as a scripting language –script: A program meant for use in small/medium projects Used by: –Google, Yahoo!, Youtube –Many Linux distributions –Games and apps (e.g. Eve Online)

5 Installing Python Windows: Download Python from Install Python. Run Idle from the Start Menu. Mac OS X: Python is already installed. Open a terminal and run python or run Idle from Finder. Linux: Chances are you already have Python installed. To check, run python from the terminal. If not, install from your distribution's package system. Note: For step by step installation instructions, see the course web site.

6 Interpreted Languages interpreted –Not compiled like many other languages (Java, C, C++) –Code is written and then directly executed by an interpreter –Type commands into interpreter and see immediate results Computer Runtime Environment CompilerCode Java: ComputerInterpreterCode Python:

7 The Python Interpreter Allows you to type commands one-at-a-time and see results A great way to explore Python's syntax

Basic Programs and Numeric Data

9 The print Statement A Python program's code is just written directly into a file print " text " print (a blank line) swallows.py print "Hello, world!" print print "Suppose two swallows carry it together." print "African or European swallow?" hello.py 1print "Hello, world!"

10 Comments Syntax: # comment text (one line) swallows2.py # Suzy Student, CSE 142, Fall 2097 # This program prints important messages. print "Hello, world!" print # blank line print "Suppose two swallows \"carry\" it together." print 'African or "European" swallows?'

11 Expressions expression: A value or operation(s) to compute a value. Example: * 3 Arithmetic operators: –+ - * / add, subtract/negate, multiply, divide –** exponentiate –% modulus, a.k.a. remainder precedence: Order in which operations are computed. –* / % ** have a higher precedence than * 4 is 13 (1 + 3) * 4 is 16

12 Integer division When we divide integers with /, the quotient is an integer ) ) / 5 is 7 84 / 10 is 8 The % operator computes a remainder from integer division ) 14 5 )

13 Variables variable: A named piece of memory that stores a value. assignment: Stores a value into a variable. –Syntax: name = expression –Examples: x = 5 gpa = 3.14 x 5 gpa 3.14 –A variable can be used in expressions. x + 4 is 9

14 Exercise This program's code is redundant. Improve it with variables: print "Subtotal:" print print "Tax:" print ( ) *.09 print "Tip:" print ( ) *.15 print "Total:" print ( ) *.15 + ( ) *.09

15 Data Types type: A category or set of data values. –Constrains the operations that can be performed on the data –Examples: integer, real number, text string Python is relaxed about types. –A variable's type does not need to be declared. –A variable can change types as a program is running. ValuePython type 42int 3.14float "ni!"str

16 Parameters parameter: A value supplied to a command as you run it. –Syntax: command ( value ) command ( value, value,..., value ) Example: print sqrt(25) print sqrt( * ) x = 5 print sqrt(x + sqrt(16))

17 Math commands To use these commands, place this line atop your program: from math import * Function nameDescription abs( value ) absolute value ceil( value ) rounds up cos( value ) cosine, in radians floor( value ) rounds down log10( value ) logarithm, base 10 max( value1, value2 ) larger of two values min( value1, value2 ) smaller of two values round( value ) nearest whole number sin( value ) sine, in radians sqrt( value ) square root ConstantDescription e pi

18 input : Reads a number from the user's keyboard. –You can store the result of input into a variable. –Example: age = input("How old are you? ") print "Your age is", age print "You have", 65 - age, "years until retirement" Output: How old are you? 53 Your age is 53 You have 12 years until retirement Exercise : Modify the restaurant program to ask the user how much of a tip to leave. input

Control Statements

20 if if statement: Executes a set of commands only if a certain condition is True. Otherwise, the commands are skipped. –Syntax: if condition : statements –Example: gpa = input("What is your GPA? ") if gpa > 2.0: print "Your application is accepted."

21 if/else if/else statement: Executes one set of statements if a certain condition is True, and a second set if it is False. –Syntax: if condition : statements else: statements –Example: gpa = input("What is your GPA? ") if gpa > 2.0: print "Welcome to Mars University!" else: print "Your application is denied." Multiple conditions can be chained with elif

22 Logic –Logical expressions can be combined using logical operators: OperatorExampleResult and(9 != 6) and (2 < 3)True or(2 == 3) or (-1 < 5)True notnot (7 > 0)False OperatorMeaningExampleResult == equals == 2True != does not equal 3.2 != 2.5True < less than 10 < 5False > greater than 10 > 5True <= less than or equal to 126 <= 100False >= greater than or equal to 5.0 >= 5.0True

23 for loops for name in range( start, end ): statements for name in range( start, end, step ): statements –Repeats for values start (inclusive) to end (exclusive) >>> for i in range(2, 6): print i >>> for i in range(15, 0, -5): print i, "squared is", (i * i) 15 squared is squared is squared is 25

24 Cumulative loops Some loops incrementally compute a value. –sometimes called a cumulative loop sum = 0 for i in range(1, 11): sum = sum + (i * i) print "sum of first 10 squares is", sum Output: sum of first 10 squares is 385

25 Exercise Write a program that reads a student's homework scores as input and computes the student's homework percentage. This program computes your average homework grade. How many assignments were there? 3 Assignment 1 Points earned? 12 Points possible? 15 Assignment 2 Points earned? 10 Points possible? 20 Assignment 3 Points earned? 4 Points possible? 5 Your total score: 26 / 40 : 65 %

26 while while loop: Executes as long as a condition is True. –good for indefinite loops (repeat an unknown number of times) Syntax: while condition : statements Example: number = 1 while number < 200: print number, number = number * 2 –Output:

27 Random numbers –from random import * –randint( min, max ) Produces a random value between min and max (inclusive) –Example: coinflip = randint(1, 2) if coinflip == 1: print "Heads" else: print "Tails"

28 Exercise Write a program that plays a guessing game with the user: Let's play a game. Try to guess my number from 1-100! Your guess? 40 Too low. Your guess? 85 Too high. Your guess? 68 Too high. Your guess? 51 Too low. Your guess? 57 Too low. Your guess? 63 Too high. Your guess? 61 You got it right in 7 guesses!

Text Processing

30 string: A sequence of text characters in a program. –Strings start and end with quote " or apostrophe ' characters. "hello" "This is a string" "This, too, is a string. It can be very long!" A string can represent special characters with a backslash. –\"quotation mark character –\t tab character –\\ backslash character "Bob said, \"Hello!\" to Susan." Strings

31 Indexes Characters in a string are numbered with indexes : name = "P. Diddy" Accessing an individual character from a string: variable [ index ] print name, "starts with", name[0] Output: P. Diddy starts with P index character P. Diddy

32 String properties len( string ) - number of characters in a string (including spaces) str.lower( string ) - lowercase version of a string str.upper( string ) - uppercase version of a string Example: name = "Martin Douglas Stepp" big_name = str.upper(name) print big_name, "has", len(big_name), "characters" Output: MARTIN DOUGLAS STEPP has 20 characters

33 raw_input : Reads a string of text from the user's keyboard. –Example: name = raw_input("Howdy. What's yer name? ") print name, "... what a silly name!" Output: Howdy. What's yer name? Paris Hilton Paris Hilton... what a silly name! raw_input

34 Text processing text processing: Examining, editing, formatting text. –Often uses loops that examine characters one by one. A for loop can examine each character in a string in order. –Example: for c in "booyah": print c Output: b o y a h

35 Strings and numbers ord( text ) - Converts a string into a number. –Example: ord("a") is 97, ord("b") is 98,... –Characters use standard mappings such as ASCII and Unicode. chr( number)- Converts a number into a string. –Example: chr(99) is "c"

36 Exercise Write a program that "encrypts" a secret message by shifting the letters of the message by 1: –e.g. "Attack" when rotated by 1 becomes "buubdl"

What's Next?

38 Further programming What do students learn next? –Arrays, data structures –Objects and object-oriented programming –Algorithms: searching, sorting, recursion, etc. –Graphical user interfaces, drawing, event-driven programming

39 CSE 142 Homework Our homeworks process interesting data and text

40 Around the 3rd week, we assign a graphical program Two parts: –draw a particular figure using loops and parameters –draw any figure you want figures posted on course web site and voted on by students Student pictures

41 Critter simulation Students write several small classes to represent animals in a simulation world Each student writes a custom "Husky" animal with their choice of behavior The best huskies compete in a tournament for prizes

42 Facebook integration

43 Links Python for math teachers: – Physics and 3D in Python: – Handbook of the Physics Computing Course (Python): – Biopython - Python tools for biology: – Python course in Bioinformatics: –