simple python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-simple-python.pdf ·...

29
Simple Python Jerry Cain CS 106AX October 21, 2019 slides leveraged from those constructed by Eric Roberts

Upload: others

Post on 22-Jul-2020

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Simple Python

Jerry CainCS 106AX

October 21, 2019slides leveraged from those constructed by Eric Roberts

Page 2: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Python Data Types• Python includes three data types for numbers: the data type

int for integers or whole numbers, the data type float for floating-point numbers containing a decimal point, and the data type complex for complex numbers, which are beyond the scope of this course. Much of what you know from JavaScript about integers and floating point numbers applies to Python as well.

• Python also provides string support in much the same way that JavaScript does. Strings are immutable objects in both JavaScript and Python, and Python includes many of the same string methods you’ve seen with JavaScript strings.• The biggest differences are notational, notably around substrings.

The differences are substantial enough that we’ll spend all of Wednesday discussing them.

Page 3: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Arithmetic Expressions• Like most languages, Python specifies computation in the

form of an arithmetic expression, which consists of termsjoined together by operators.

• Each term in an arithmetic expression is one of the following:– An explicit numeric value, such as 2 or 3.14159265– A variable name that serves as a placeholder for a value– A function call that computes a value– An expression enclosed in parentheses

• The operators include the conventional ones from arithmetic, along with a few that are somewhat less familiar:

+ Addition– Subtraction* Multiplication/ Division (exact)

// Quotient (floor division)% Remainder** Exponentiation

Page 4: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Python Division and Exponentiation• Python has three operators that involve division:

– The / operator computes the exact result of division, so that the expression 6 / 4 has the value 1.5. Applying the / operator always produces a floating-point value.

– The // operator implements floor division, which is the result of exact division rounded down to the next smaller integer. The expression 6 // 4 produces the value 1, and -6 // 4produces the value –2.

– The % operator behaves the same in Python and JavaScript. As before, we assume the first operand is nonnegative and the second operand is positive, so that 6 % 4 is 2 and 0 % 11 is 0.

• The ** operator doesn’t appear in JavaScript. It implements exponentiation, so the expression 3 ** 4 evaluates to 81.

• The other operators all behave as you’d expect.

Page 5: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Using the PyCharm Interpreter• The easiest way to get a sense of how arithmetic expressions

work in Python is to enter them into the PyCharm interpreter, which you’ll be using for the Python segment of the course.

PyCharm

>>> 2 + 24>>> 342 - 173169>>> 12345679 * 63777777777>>> 9 * 9 * 9 + 10 * 10 * 10 1729>>>

Page 6: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Python Variables and Assignment

variable = expression

• In Python, you create a variable simply by assigning it a value in an assignment statement, which has the general form:

• As in most languages, including JavaScript, the effect of an assignment statement is to compute the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left, as with:

total = total + value

• Note you need not precede the variable name with the letkeyword. If the Python interpreter encountered an identifier it’s not seen prior, it assumes a new variable is coming into scope.

• Python includes shorthand notation like +=, but not ++ or --!

Page 7: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Naming Conventions• In Python, names uses for variables, functions, and classes are

called identifiers. Identifier names are composed of letters, digits, and underscores and cannot begin with a digit.

• Programmers use a variety of different conventions to mark word boundaries in an identifier:– Snake case uses underscores, as in number_of_students.– Camel case embeds uppercase, as in numberOfStudents.

• CS 106AX and the Python reader use these conventions:– Variable and function names use camel case and begin with a

lowercase letter.– Constant names are written entirely in uppercase and use the

underscore character, as in MAX_HEADROOM.– Class names and function names designed to be run as

programs use camel case and begin with an uppercase letter.

Page 8: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Multiple Assignment• Python, unlike JavaScript, supports multiple assignment, where

the left side of an assignment consists of a list of variables and the right side consists of a list of expressions, as with:

x, y, z = 5, 12, 13

• All the values on the right side are computed before any assignments are performed. For example, the statement

exchanges the values of the variables a and b.a, b = b, a

which sets x to 5, y to 12, and z to 13.

Page 9: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Functions• A function is a sequence of statements that has been collected

together and given a name, which makes it possible to invoke the complete set of statements simply by supplying the name.

• A function typically takes information from its caller in the form of arguments, perform some computation involving the values of the arguments, and then returns a result to the caller, which continues from the point of the call;

• This notion that functions exist to manipulate information and return results makes functions in programming similar to functions in mathematics, which is the historical reason for the name.

• All of this is a repeat of how functions operate in JavaScript (and virtually all other languages).

Page 10: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Functions in Mathematics

• Plugging in a value for x allows you to compute the value of f (x), as follows:

• The graph at the right shows the values of the function

f (x) = x2 - 5

f (0) = 02 - 5 = -5f (1) = 12 - 5 = -4f (2) = 22 - 5 = -1f (3) = 32 - 5 = 4

• The Python version of f (x) isdef f(x):

return x**2 – 5

Page 11: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Built-In Functions• To make programming easier, all modern languages

(including Python, of course) include collections of predefined functions. The built-in functions that operate on numeric data appear in the following table:

max(x, y, . . .)min(x, y, . . .)

float(x)

round(x)

abs(x)

int(x)

The absolute value of xThe largest of the argumentsThe smallest of the arguments

The value of x converted to floating-point

The value of x rounded to the nearest integerThe value of x truncated to an integer

Page 12: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Importing Library Functions• In addition to the built-in functions, Python offers a larger set

of resources, which are organized into collections called libraries. Before you can use a library function, you must import that library in one of two ways.

• The most common strategy is to use an import statement to acquire access to that library’s facilities without specifying any particular functions. For example, the statement

import math

indicates that your program will use resources from the mathlibrary. When you do, you must use the fully qualified name,which includes the library name, as in math.sqrt.

• You can also use the from-import statement to gain access to specific functions without having to include the library name.

Page 13: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Useful Entries in Python’s math Library

math.floor(x)

math.log(x)

math.sin(q)math.cos(q)

math.sqrt(x)

math.pimath.e

math.exp(x)

The mathematical constant πThe mathematical constant e

Rounds x down to the nearest integer

The natural logarithm of x

The inverse logarithm (e x)The sine of q, measured in radiansThe cosine of q, measured in radians

The square root of x

math.ceil(x) Rounds x up to the nearest integer

math.atan2(y, x) The arctangent of y / xmath.degrees(q)math.radians(q )

Converts from radians to degreesConverts from degrees to radians

math.log10(x) The common (base 10) logarithm of x

math.atan(x) The principal arctangent of x

Page 14: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Writing Your Own Functions• The general form of a Python function definition is

def name(parameter list):statements in the function body

where name is the name of the function, and parameter list is a list of variables used to hold the values of each argument.

• You can return a value from a function by including a returnstatement, which is usually written as

return expression

Note the lack of curly braces and semicolons! Python instead relies on strict indentation to specify block structure.

Page 15: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Examples of Simple Functions• The following function converts Fahrenheit temperatures to

their Celsius equivalent:

def ftoc(f):return 5 / 9 * (f – 32)

• The following function computes the volume of a cylinder of radius r and height h.

def cylinderVolume(r, h):return math.pi * r**2 * h

Page 16: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Built-In Functions for Strings• Python includes the following built-in functions that operate

on string values:

• Python programs often require that the user type in free form text in response to input calls. This underscores a key difference between JavaScript programs, which are almost always event-driven, and Python programs, which are often scripts that run uninterrupted, save for occasional calls to input.

str(x)int(s)

input(prompt)

float(s)

len(s)

print(. . .)

The number of characters in sThe value of x converted to a stringThe string s interpreted as an integer

Reads a string from the user

The string s interpreted as floating-pointPrints the arguments separated by spaces

Page 17: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Running Command-Line Programs• Although it is possible to import programs into PyCharm and

run them there, most Python programs are created as text files and then invoked from a command line.

• Python programs specify what happens when the program is run from the command line using the following lines at the end of the program file:

if __name__ == "__main__":function()

where function is the name of the function that serves as an entry point into the entire program.

• Lines of this sort are often called boilerplate. It’s generally more important to just memorize the boilerplate than to understand it.

Page 18: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The AddTwoIntegers Program# File: AddTwoIntegers.py

"""This program adds two integers entered by the user."""def AddTwoIntegers():

print("This program adds two integers.")n1 = int(input("Enter n1? "))n2 = int(input("Enter n2? "))sum = n1 + n2print("The sum is", sum)

# Startup codeif __name__ == "__main__":

AddTwoIntegers()

Page 19: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Boolean Expressions in Python• Unsurprisingly Python defines operators that work with

Boolean data: relational operators and logical operators.• There are six relational operators that compare values of other

types and produce a True/False result (note == versus ===):== Equals< Less than

!= Not equals<= Less than or equal to>= Greater than or equal to> Greater than

Of course, the expression n <= 10 evaluates to True if n is less than or equal to 10 and evaluates to False otherwise.

p or q means either p or q (or both)

• Whereas JavaScript has &&, ||, and !, Python has these:and Logical AND

or Logical OR

not Logical NOT

p and q means both p and q

not p means the opposite of p

Page 20: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The if Statement

if condition:statements to be executed if the condition is true

• The simplest of the control statements is the if statement, which occurs in two forms. You use the first when you need to perform an operation only if a particular condition is true:

if condition:statements to be executed if the condition is true

else:statements to be executed if the condition is false

• You use the second form whenever you need to choose between two alternative paths, depending on whether the condition is true or false:

Page 21: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Functions Involving Control Statements• The body of a function can contain statements of any type,

including control statements. As an example, the following function uses an if statement to find the larger of two values:

def max(x, y):if x > y:

return xelse:

return y

• Notice the reliance on the : and struct indentation to specify block structure. It’s very easy to identify Python code because of this.

• Python doesn’t require semicolons to terminate expressions as our JavaScript programs do.

Page 22: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The while Statement

while condition:statements to be repeated

• The while statement is the simplest of Python’s iterative control statements and has the following form:

while condition:statements to be repeated

while True:line = input(prompt)if line == "": breakrest of loop body

• A particularly useful while loop pattern we never needed in JavaScript looks like this:

• The while True control line loops forever. The loop exits when the break statement is executed at the end of the input.

Page 23: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The AddList Program# File: AddList.py

def AddList():print("This program adds a list of integers.")print("Enter a blank line to stop.")sum = 0while True:

line = input(" ? ")if line == "": breaksum += int(line)

print("The sum is", sum)

# Startup codeif __name__ == "__main__":

AddList()

Page 24: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The for Statement• The for statement is Python’s most powerful mechanism for

specifying iteration and has the following general form:

• In this pattern, var is a variable name and iterable is any expression that produces a value that supports iteration.

• The effect of the for statement is to iterate over each value produced by the iterable object and assign it to var. The forloop continues as long as there are more values in the iterable.

for var in iterable:statements to be repeated

Page 25: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The range Function• The most common for loop pattern uses the built-in range

function to produce the iterable object.• The range function can take one, two, or three arguments, as

follows: range(limit) counts from 0 up to limit–1range(start, limit) counts from start up to limit–1range(start, limit, step) counts by step

• Note that the range function always stops one step before the limit value is reached.

• The first of the three range structures above is the most common.

Page 26: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The fact Function• The factorial of a number n (which is usually written as n! in

mathematics) is defined to be the product of the integers from 1 up to n. Thus, 5! is equal to 120, which is 1 x2 x3 x4 x5.

def fact(n):result = 1for i in range(1, n + 1):

result *= ireturn result

• The following function definition uses a for loop to compute the factorial function:

Page 27: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

Iterating over Sequences• The for statement is also used to iterate over the elements of

a sequence of values.• Python supports many different kinds of sequences that you

will learn over the course of the next three weeks. The only sequence type you’ve seen so far is the string, which represents a sequence of characters.

• The following function returns the number of times the character c appears in the string s:

def countOccurrences(c, s):count = 0for ch in s:

if c == ch:count += 1 # no ++ operator

return count

Page 28: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The End

Page 29: Simple Python - web.stanford.eduweb.stanford.edu/class/cs106ax/res/lectures/13-Simple-Python.pdf · data type complexfor complex numbers,which are beyond the scope of this course

The End