Introduction to Computing Using Python Python  Python is an interactive language.  Java or C++: compile, run  Also, a main function or method  Python:

Slides:



Advertisements
Similar presentations
CS 100: Roadmap to Computing Fall 2014 Lecture 0.
Advertisements

Introduction to Computing Using Python Imperative Programming  Python Programs  Interactive Input/Output  One-Way and Two-Way if Statements  for Loops.
Introduction to C Programming
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Introduction to Programming with Java, for Beginners Primitive Types Expressions Statements Variables Strings.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Introduction to C Programming
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.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to C++ Programming Outline Introduction to C++ Programming A Simple Program: Printing a.
Python Data Types Expressions, Variables, and Assignments Strings
CS 100: Roadmap to Computing Fall 2014 Lecture 01.
Introduction to Python
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Lists in Python.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
First Program  Open a file  In Shell  Type into the file: 3  You did it!!! You wrote your first instruction, or code, in python!
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Computer Science 111 Fundamentals of Programming I Basic Program Elements.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STARTING OUT WITH Python Python First Edition by Tony Gaddis Chapter 2 Input,
Introduction to Computing Using Python Straight-line code  In chapter 2, code was “straight-line”; the Python statements in a file (or entered into the.
Input, Output, and Processing
Computer Science 101 Introduction to Programming.
Constants Numeric Constants Integer Constants Floating Point Constants Character Constants Expressions Arithmetic Operators Assignment Operators Relational.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Lecture 2: Introduction to C Programming. OBJECTIVES In this lecture you will learn:  To use simple input and output statements.  The fundamental data.
Variables, Expressions and Statements
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
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.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Variables, Types, Expressions Intro2CS – week 1b 1.
Introduction to Programming Python Lab 3: Arithmetic 22 January PythonLab3 lecture slides.ppt Ping Brennan
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
CSx 4091 – Python Programming Spring 2013 Lecture L2 – Introduction to Python Page 1 Help: To get help, type in the following in the interpreter: Welcome.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
Introduction to Python Developed by Dutch programmer Guido van Rossum Named after Monty Python Open source development project Simple, readable language.
1 Agenda  Unit 7: Introduction to Programming Using JavaScript T. Jumana Abu Shmais – AOU - Riyadh.
Mr. Crone.  Use print() to print to the terminal window  print() is equivalent to println() in Java Example) print(“Hello1”) print(“Hello2”) # Prints:
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
String and Lists Dr. José M. Reyes Álamo.
Introduction to Programming
Fundamentals of Programming I Overview of Programming
Topics Designing a Program Input, Processing, and Output
CSc 120 Introduction to Computer Programing II Adapted from slides by
Introduction to Python
CS 100: Roadmap to Computing
Chapter 3 Instructor: Zhuojun Duan
Java Programming: From Problem Analysis to Program Design, 4e
Python Data Types Expressions, Variables, and Assignments Strings
Introduction to C++ Programming
T. Jumana Abu Shmais – AOU - Riyadh
CS 100: Roadmap to Computing
String and Lists Dr. José M. Reyes Álamo.
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Topics Designing a Program Input, Processing, and Output
Intro to Computer Science CS1510 Dr. Sarah Diesburg
Topics Designing a Program Input, Processing, and Output
COMPUTER PROGRAMMING SKILLS
CS 100: Roadmap to Computing
CS 100: Roadmap to Computing
Presentation transcript:

Introduction to Computing Using Python Python  Python is an interactive language.  Java or C++: compile, run  Also, a main function or method  Python: type expressions directly into interactive shell (or load them from a file)  Wherever you want your program to start, type this into the interactive shell (or in a file that is loaded into the shell)

Introduction to Computing Using Python Python Download and run   Downloads the Python language, plus an interactive shell called idle  To run: type idle into Search programs and files  You can type Python expressions directly into the idle window  Or, you can open a file window by clicking New file under the File menu, or Ctrl-o  To load Python code from a file, hit F5 key

Introduction to Computing Using Python Algebraic expressions >>> >>> >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> abs(-3.2) 3.2 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> abs(-3.2) 3.2 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> max(23,41,15,24) 41 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> abs(-3.2) 3.2 >>> min(23,41,15,24) 15 >>> max(23,41,15,24) 41 >>> >>> >>> >>> >>> >>> >>> 2*(3+1) 8 >>> >>> >>> 2*(3+1) 8 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 The Python interactive shell can be used to evaluate algebraic expressions 14//3 is the quotient when 14 is divided by 3 and 14%3 is the remainder 2**3 is 2 to the 3 rd power abs(), min(), and max() are functions abs() takes a number as input and returns its absolute value min() (resp., max() ) take an arbitrary number of inputs and return the “smallest” (resp., “largest”) among them >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> min(3, 2, 4) 2 >>> >>> >>> 2*(3+1) 8 >>> 5/2 2.5 >>> 5//2 2 >>> 14//3 4 >>> 14%3 2 >>> 2**3 8 >>> min(3, 2, 4) 2

Introduction to Computing Using Python Operator precedence In algrabraic expressions that use more than one operator, Python must have some way to determine the order in which operators are applied. For example: >>> * 5 (is it 25 or 17?) It’s 17, because * has higher precedence than + In other words * is computed first You can always override precedence by using parentheses

Introduction to Computing Using Python Functions A function is a sequence of simple statements that is given a name Many functions are built in to the Python language Examples: abs, min, max When you call a function, you must place parentheses after it; e.g., abs(-4) NOT abs -4

Introduction to Computing Using Python Functions Functions are often passed parameters which are pieces of information a function needs to run Example: >>> abs(-3) 3 Different functions take different numbers of parameters. For example:

Introduction to Computing Using Python Functions abs takes one parameter >>> abs(-1) 1 min takes one or more parameters >>> min(2,1) 1 >>> min(4, 2, 6) 2 Some take no parameters >>> import time >>> time.time()

Introduction to Computing Using Python Comments When you write non-trivial code, it is important to comment it. Comment symbol is # Anything on a line that is after # will be ignored by the computer

Introduction to Computing Using Python Comments Comments are used to make code more understandable for people (including you) Example: x = * radius * radius # compute the area of a circle Don’t overcomment: y = 3 # set the value of y to 3 Even the first example of a comment might not be necessary

Introduction to Computing Using Python Boolean expressions In addition to algebraic expressions, Python can evaluate Boolean expressions Boolean expressions evaluate to True or False Boolean expressions often involve arithmetic comparison operators, ==, !=, = >>> 2 < 3 True >>> 2 > 3 False >>> 2 == 3 False >>> 2 != 3 True >>> 2 <= 3 True >>> 2 >= 3 False >>> 2+4 == 2*(9/3) True >>> 2 < 3 True >>> 2 > 3 False >>> 2 == 3 False >>> 2 != 3 True >>> 2 <= 3 True >>> 2 >= 3 False >>> 2+4 == 2*(9/3) True In an expression containing algebraic and comparison operators: Algebraic operators are evaluated first Comparison operators are evaluated next

Introduction to Computing Using Python Logical operators Logical operators can also be used in Boolean expressions - and, or, not >>> 2<3 and 3<4 True >>> 4==5 and 3<4 False >>> False and True False >>> True and True True >>> 4==5 or 3<4 True >>> False or True True >>> False or False False >>> not(3<4) False >>> not(True) False >>> not(False) True >>> 4+1==5 or 4-1<4 True >>> 2<3 and 3<4 True >>> 4==5 and 3<4 False >>> False and True False >>> True and True True >>> 4==5 or 3<4 True >>> False or True True >>> False or False False >>> not(3<4) False >>> not(True) False >>> not(False) True >>> 4+1==5 or 4-1<4 True In a an expression containing algebraic, comparison, and Boolean operators: Algebraic operators are evaluated first Comparison operators are evaluated next Boolean operators are evaluated last

Introduction to Computing Using Python Exercise >>> >>> >>> 20* >>> 2** >>> min(3, 1, 8, -2, 5, -3, 0) -3 >>> 3 == 4-2 False >>> 17//5 == 3 True >>> 17%5 == 3 False >>> 284%2 == 0 True >>> 284%2 == 0 and 284%3 == 0 False >>> 284%2 == 0 or 284%3 == 0 True >>> >>> >>> 20* >>> 2** >>> min(3, 1, 8, -2, 5, -3, 0) -3 >>> 3 == 4-2 False >>> 17//5 == 3 True >>> 17%5 == 3 False >>> 284%2 == 0 True >>> 284%2 == 0 and 284%3 == 0 False >>> 284%2 == 0 or 284%3 == 0 True Translate the following into Python algebraic or Boolean expressions and then evaluate them: a)The year that was 25 years ago (use -) b)The total of 14.99, 27.95, and c)The area of a rectangle of length 20 and width 15 d)2 to the 10 th power e)The minimum of 3, 1, 8, -2, 5, -3, and 0 f)3 equals 4-2 g)The value of 17//5 is 3 h)The value of 17%5 is 3 i)284 is even j)284 is even and 284 is divisible by 3 k)284 is even or 284 is divisible by 3

Introduction to Computing Using Python Variables and assignments = Just as in algebra, a value can be assigned to a variable, such as x When variable x appears inside an expression, it evaluates to its assigned value A variable (name) does not exist until it is assigned The assignment statement has the format is evaluated first, and the resulting value is assigned to variable >>> x = 3 >>> x 3 >>> 4*x 12 >>> y Traceback (most recent call last): File " ", line 1, in y NameError: name 'y' is not defined >>> y = 5*x 15 >>> y 15 >>> x = 3 >>> x 3 >>> 4*x 12 >>> y Traceback (most recent call last): File " ", line 1, in y NameError: name 'y' is not defined >>> y = 5*x 15 >>> y 15

Introduction to Computing Using Python Naming rules Variable names can contain these characters: a through z A through Z the underscore character _ digits 0 through 9 Names cannot start with a digit For a multiple-word name, use either the underscore as the delimiter or camelCase capitalization Short and meaningful names are ideal >>> My_x2 = 21 >>> My_x2 21 >>> My_x2 = 21 >>> My_x2 21 >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newTemp = 23 >>> >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newTemp = 23 >>> >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newTemp = 23 >>> counter = 0 >>> temp = 1 >>> price = 2 >>> age = 3 >>> My_x2 = 21 >>> My_x2 21 >>> 2x = 22 SyntaxError: invalid syntax >>> new_temp = 23 >>> newTemp = 23 >>> counter = 0 >>> temp = 1 >>> price = 2 >>> age = 3

"Hello, World!" Introduction to Computing Using Python Strings In addition to number and Boolean values, Python supports string values A string value is represented as a sequence of characters enclosed within quotes >>> 'Hello, World!' 'Hello, World!' >>> >>> 'Hello, World!' 'Hello, World!' >>> 'Hello, World!' A string value can be assigned to a variable String values can be manipulated using string operators and functions >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>>

Introduction to Computing Using Python String operators >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> s == 'rock' True >>> s != t True >>> s < t False >>> s > t True >>> s + t 'rockclimbing' >>> s + ' ' + t 'rock climbing' >>> 5 * s 'rockrockrockrockrock' >>> 30 * '_' '______________________________' >>> 'o' in s True >>> 'o' in t False >>> 'bi' in t True >>> len(t) 8 >>> 'Hello, World!' 'Hello, World!' >>> s = 'rock' >>> t = 'climbing' >>> s == 'rock' True >>> s != t True >>> s < t False >>> s > t True >>> s + t 'rockclimbing' >>> s + ' ' + t 'rock climbing' >>> 5 * s 'rockrockrockrockrock' >>> 30 * '_' '______________________________' >>> 'o' in s True >>> 'o' in t False >>> 'bi' in t True >>> len(t) 8 UsageExplanation x in s x is a substring of s x not in s x is not a substring of s s + t Concatenation of s and t s * n, n * s Concatenation of n copies of s s[i] Character at index i of s len(s) (function) Length of string s >> help(str) Help on class str in module builtins: class str(object) | str(string[, encoding[, errors]]) -> str... >> help(str) Help on class str in module builtins: class str(object) | str(string[, encoding[, errors]]) -> str... To view all operators, use the help() tool

Introduction to Computing Using Python Exercise >>> s1 'good' >>> s2 'bad' >>> s3 'silly' >>> >>> s1 'good' >>> s2 'bad' >>> s3 'silly' >>> Write Python expressions involving strings s1, s2, and s3 that correspond to: a)'ll' appears in s3 b)the blank space does not appear in s1 c)the concatenation of s1, s2, and s3 d)the blank space appears in the concatenation of s1, s2, and s3 e)the concatenation of 10 copies of s3 f)the total number of characters in the concatenation of s1, s2, and s3 >>> s1 'good' >>> s2 'bad' >>> s3 'silly' >>> 'll' in s3 True >>> ' ' not in s1 True >>> s1 + s2 + s3 'goodbadsilly’ >>> ' ' in s1 + s2 + s3 False >>> 10*s3 'sillysillysillysillysillysillysillysillysillysilly' >>> len(s1+s2+s3) 12 >>> >>> s1 'good' >>> s2 'bad' >>> s3 'silly' >>> 'll' in s3 True >>> ' ' not in s1 True >>> s1 + s2 + s3 'goodbadsilly’ >>> ' ' in s1 + s2 + s3 False >>> 10*s3 'sillysillysillysillysillysillysillysillysillysilly' >>> len(s1+s2+s3) 12 >>>

Introduction to Computing Using Python Index and indexing operator 'A' 'p' 'l' 'e' s[0] = s[1] = s[2] = s[3] = s[4] = s = The index of an item in a sequence is its position with respect to the first item The first item has index 0, The index of an item in a sequence is its position with respect to the first item The first item has index 0, The second has index 1, The index of an item in a sequence is its position with respect to the first item The first item has index 0, The second has index 1, The third has index 2, … The indexing operator [] takes a nonnegative index i and returns a string consisting of the single character at index i >>> s = 'Apple' >>> s[0] 'A' >>> s[1] 'p' >>> s[4] 'e' >>> s = 'Apple' >>> s[0] 'A' >>> s[1] 'p' >>> s[4] 'e' 'A p p l e'

Introduction to Computing Using Python Negative index 'A' 'l' 'e' s[-1] = s[-2] = s[-5] = s = 'A p p l e' A negative index is used to specify a position with respect to the “end” The last item has index -1, The second to last item has index -2, The third to last item has index -3, … >>> s = 'Apple' >>> s[-1] 'e' >>> s[-2] 'l' >>> s[-5] 'A' >>> s = 'Apple' >>> s[-1] 'e' >>> s[-2] 'l' >>> s[-5] 'A'

Introduction to Computing Using Python Exercise >>> s = 'abcdefgh' >>> >>> s = 'abcdefgh' >>> String s is defined to be 'abcdefgh' Write expressions using s and the indexing operator [] that return the following strings: a)'a' b)'c' c)'h' d)'f' >>> s = 'abcdefgh' >>> s[0] 'a' >>> s[2] 'c' >>> s[7] 'h' >>> s[-1] 'h' >>> s[-3] 'f' >>> >>> s = 'abcdefgh' >>> s[0] 'a' >>> s[2] 'c' >>> s[7] 'h' >>> s[-1] 'h' >>> s[-3] 'f' >>>

['ant', 'bat', 'cod', 'dog', 'elk'] Introduction to Computing Using Python Lists In addition to number, Boolean, and string values, Python supports lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> A comma-separated sequence of items enclosed within square brackets The items can be numbers, strings, and even other lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’] >>> [0, 1, 'two', 'three', [4, 'five']] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>>

Introduction to Computing Using Python List operators and functions Like strings, lists can be manipulated with operators and functions >>> lst = [1, 2, 3] >>> lstB = [0, 4] >>> 4 in lst False >>> 4 not in lst True >>> lst + lstB [1, 2, 3, 0, 4] >>> 2*lst [1, 2, 3, 1, 2, 3] >>> lst[0] 1 >>> lst[1] 2 >>> lst[-1] 3 >>> len(lst) 3 >>> min(lst) 1 >>> max(lst) 3 >>> sum(lst) 6 >>> help(list... >>> lst = [1, 2, 3] >>> lstB = [0, 4] >>> 4 in lst False >>> 4 not in lst True >>> lst + lstB [1, 2, 3, 0, 4] >>> 2*lst [1, 2, 3, 1, 2, 3] >>> lst[0] 1 >>> lst[1] 2 >>> lst[-1] 3 >>> len(lst) 3 >>> min(lst) 1 >>> max(lst) 3 >>> sum(lst) 6 >>> help(list... UsageExplanation x in lst x is an item of lst x not in lst x is not an item of lst lst + lstB Concatenation of lst and lstB lst*n, n*lst Concatenation of n copies of lst lst[i] Item at index i of lst len(lst) Number of items in lst min(lst) Minimum item in lst max(lst) Maximum item in lst sum(lst) Sum of items in lst

Introduction to Computing Using Python Lists are mutable, strings are not >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> lst = [0, 1, 'two', 'three', [4, 'five']] >>> The elements can be numbers, strings, and even other lists >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk’] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] pets = ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> pet[2] = 'w' Traceback (most recent call last): File " ", line 1, in pet[2] = 'w' TypeError: 'str' object does not support item assignment >>> >>> pets = ['ant', 'bat', 'cod', 'dog', 'elk'] >>> pets[2] = 'cow' >>> pets ['ant', 'bat', 'cow', 'dog', 'elk'] >>> pet = 'cod' >>> pet[2] = 'w' Traceback (most recent call last): File " ", line 1, in pet[2] = 'w' TypeError: 'str' object does not support item assignment >>> pet = 'cod' Lists can be modified; they are said to be mutable Strings can’t be modified; they are said to be immutable

Introduction to Computing Using Python List methods len() and sum() are examples of functions that can be called with a list input argument; they can also be called on other type of input argument(s) >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> ` >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> ` There are also functions that are called on a list; such functions are called list methods (note the different syntax). Two of these methods are append and remove >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> lst.append(7) >>> lst [1, 2, 3, 7] >>> lst.remove(3) >>> lst [1, 2, 7] >>> lst = [1, 2, 3] >>> len(lst) 3 >>> sum(lst) 6 >>> lst.append(7) >>> lst [1, 2, 3, 7] >>> lst.remove(3) >>> lst [1, 2, 7] Later we will discuss in more detail what the difference is between a method and a function

Introduction to Computing Using Python List methods >>> lst = [1, 2, 3] >>> lst.append(7) >>> lst.append(3) >>> lst [1, 2, 3, 7, 3] >>> lst.count(3) 2 >>> lst.remove(2) >>> lst [1, 3, 7, 3] >>> lst.reverse() >>> lst [3, 7, 3, 1] >>> lst.index(3) 0 >>> lst.sort() >>> lst [1, 3, 3, 7] >>> lst.remove(3) >>> lst [1, 3, 7] >>> lst.pop() 7 >>> lst [1, 3] >>> lst = [1, 2, 3] >>> lst.append(7) >>> lst.append(3) >>> lst [1, 2, 3, 7, 3] >>> lst.count(3) 2 >>> lst.remove(2) >>> lst [1, 3, 7, 3] >>> lst.reverse() >>> lst [3, 7, 3, 1] >>> lst.index(3) 0 >>> lst.sort() >>> lst [1, 3, 3, 7] >>> lst.remove(3) >>> lst [1, 3, 7] >>> lst.pop() 7 >>> lst [1, 3] UsageExplanation lst.append(item) adds item to the end of lst lst.count(item) returns the number of times item occurs in lst lst.index(item) Returns index of (first occurrence of) item in lst lst.pop() Removes and returns the last item in lst lst.remove(item) Removes (the first occurrence of) item from lst lst.reverse(item) Reverses the order of items in lst lst.sort(item) Sorts the items of lst in increasing order Methods append(), remove(), reverse(), and sort() do not return any value; they, along with method pop(), modify list lst

Introduction to Computing Using Python Exercise List lst is a list of prices for an item at different online retailers >>> lst = [159.99, , , , ] >>> lst.append(160.00) >>> lst.count(160.00) 2 >>> min(lst) >>> lst.index(128.83) 3 >>> lst.remove(128.83) >>> lst [159.99, 160.0, , , 160.0] >>> lst.sort() >>> lst [159.99, 160.0, 160.0, , ] >>> >>> lst = [159.99, , , , ] >>> lst.append(160.00) >>> lst.count(160.00) 2 >>> min(lst) >>> lst.index(128.83) 3 >>> lst.remove(128.83) >>> lst [159.99, 160.0, , , 160.0] >>> lst.sort() >>> lst [159.99, 160.0, 160.0, , ] >>> a)You found another retailer selling the item for $160.00; add this price to list lst b)Compute the number of retailers selling the item for $ c)Find the minimum price in lst d)Using c), find the index of the minimum price in list lst e)Using c) remove the minimum price from list lst f)Sort list lst in increasing order

Introduction to Computing Using Python Objects and classes Terminology: object X is of type int = object X belongs to class int An object’s type determines what values it can have and how it can be manipulated A class is a kind of data (int, list, str, …) An object is a particular value associated with a class (3, [1, 2, 3], ‘abc’) All values in Python are objects Unlike many other programming languages

Introduction to Computing Using Python Values of number types An object of type int can be any integer number value (with no decimal point) Another type for numbers is called float. Any number with a decimal point is a float. >>> 3 3 >>> type(3) >>> >>> type(3.) >>> type(3.0) >>> 3 3 >>> type(3) >>> >>> type(3.) >>> type(3.0) An object’s type determines what values it can have and how it can be manipulated

Introduction to Computing Using Python Input from a user Function for user input: inp(prompt) where prompt is a string Example (assume the user enters ‘hello’) >>> inp = input(‘Enter a word ’) >>> inp + ‘ was your input’ Hello was your input The user’s input is always interpreted as a string Example (the user enters ‘1’) >>> x = input(‘Enter a number ’) >>> x * 2 11

Introduction to Computing Using Python Conversion of types To change a string into an integer: int( ) For example: >>> int(‘3’) 3 Example (the user enters ‘1’) >>> x = int(input(‘Enter a number ’)) >>> x * 2 2

Introduction to Computing Using Python Output to a user Function: print( ) where is a string For example: >>> print(‘Hello world’) Hello world

Introduction to Computing Using Python Conversion of types, continued What if you want to print something that isn’t a string? The str function does this >>> str(1) ‘1’ For example: >>> int(‘3’) 3 >>> int(‘3’) + 2 5

Introduction to Computing Using Python Example using str Assume user types 3 >>> x = int(input(‘Enter an integer ’)) >>> print(x + ' plus 2 is ' + y) Traceback (most recent call last): File " ", line 1, in print(x + ' plus 2 is ' + y) TypeError: unsupported operand type(s) for +: 'int' and 'str' >>> print(str(x) + ‘ plus 2 is ’ + str(y)) is 5

Introduction to Computing Using Python Writing code in a file If code becomes too complex, It is a pain to type it in to the IDLE window over and over again An alternative: write the code in a file, then hit F5 key Output might differ, so you might need to call print()

Introduction to Computing Using Python Special characters If a string contains a ‘\’, then the character after that is interpreted differently Example: ‘\n’ means a newline >>> print(‘abc\ndef’) abc def (‘\’ is an escape character within print function)

Introduction to Computing Using Python Special characters, continued ‘\t’: tab character >>> print(‘abc\tdef’) abc def However: >>> ‘abc\ndef’ abc\ndef (‘\’ is an escape character within print function)

Introduction to Computing Using Python Homework assignment 1 See Course Online Choose ‘CSC-241’ Click ‘Assignments’