(PPT) Introduction To The Python Programming Language
(PPT) Introduction To The Python Programming Language
in Python
Introduction to Python basics
Goals
• Become comfortable in Python
• Basic types and mathematical operations
• Calling functions
• Defining functions
• Using return correctly
• Design recipe in Python
2
Top programming languages
3
Role of programming languages
• When you click an icon for an application,
a program is run in machine language.
Machine language is designed for
particular hardware, rather than being
human-friendly and general.
4
Running a Python program
• Uses an interpreter like Wing 101
• Translates one statement at a time
• Stops when one error is found
5
What does a Python program look like?
• A series of statements
• Assignment statements
• Control statements
• Function calls
6
Some Python Basics
• Written using regular mathematical notation
3+4
5 * (3 + 4) – 1
• Two numeric types
• Integers
• floating point numbers
• Strings, booleans, lists
7
Assignment Statements
v = expr
• = is the assignment operator ("becomes” or "is")
• v is any variable name
• expr is any Python expression
• How it works:
1. Evaluate expr
2. "Assign” that value to v
• Assignment statements do not return a value. They only have an
effect.
8
A very simple Python program
x = 2 * (4 + 12)
y=x+8
z=y*y
q = 2.5 + 4.2
w = "hi"
u=w+w
9
Numeric types
• Integers in Python are stored exactly
10
Basic mathematical operations
• Addition (+), Subtraction (-), Multiplication (*):
• If combining two Int values, the result is an Int
• If combining two Float values, or a Float and an Int, the result is a Float
11
Basic mathematical operations
• Division: x / y
• The result is a Float for any numerical values x and y (even if both are Int)
• Integer division: x // y
• The result is the integer part of the division
• If x and y are both Int, the result is an Int
• If either x or y is a Float, the result is a Float
12
Other mathematical operations
• Remainder: x % y
• x and y should both be Int
• Exponents: x ** y
• (any of Int Float) (any of Int Float) -> (any of Int Float)
• returns x raised to the power of y
13
More useful things to know
• Python precedence operations are standard math precedence rules
(BEDMAS)
14
Calling functions in Python
• fn_name(arg1, arg2, ..., argN)
• built-in function or a user-defined fn_name
• must have correct number of arguments
• separate arguments by single comma
• examples:
abs(-3.8) → 3.8
len("Hello There") → 11
max(3,5.2,9) →9
min("ABC", "AA") → "AA"
15
The math Module
• A Python module is a way to group together information, including a
set of functions
• The math module includes constants and functions for basic
mathematical calculations
• To use functions from math
• Import the math module into your program
• Use math.fn or math.const to reference the function or constant you want
16
The math Module
import math
math.sqrt(25)
math.log(32,2)
math.log(32.0, 10)
math.floor(math.log(32.0, math.e))
math.factorial(10)
math.cos(math.pi)
sqrt(100.3)
17
More math functions
>>> import math
>>> dir(math)
[..., 'acos', 'asinh', 'atan', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'factorial',
'floor', 'log', 'log10', 'pi', 'pow', 'radians', 'sin', 'sqrt', 'tan', 'trunc', ...]
>>> help(math.floor)
Help on built-in function floor in module math:
floor(...)
floor(x)
Return the floor of x as an integer. This is the largest integral value <= x.
18
Creating new functions in Python
• def fn_name (p1, p2, ..., pN):
statement
...
statement
• Indent each statement the same amount
• For a function to return a value, include
return answer
where answer is the value the function returns
• If there is no return statement or a return statement without an expression for
answer, the function will return None (which is the default with a Python
function).
19
Example: Write a Python function that consumes
3 different integers and returns the middle value
def middle(a,b,c):
largest = max(a,b,c)
smallest = min(a,b,c)
mid = (a+b+c)-largest–smallest
return mid
20
Design recipe for functions
• When writing functions in Python, we should include:
• Purpose statement
• Contract
• Examples
• Function body
21
Design recipe
• Purpose statement:
• Explicitly indicate what the function does, including how the parameters are
used
• Use "returns"
• Contract
• Types of consumed and returned values
• Include any needed requirements on parameters
• Examples
• fn(arg1, arg2, ...) → expected
• middle(4,2,8) → 4
• middle(3,2,1) → 2
22
Example
def middle(a,b,c):
’’’ returns the middle (median) value of a,b,c
Examples:
middle(4,2,8) => 4
middle(3,2,1) => 2
‘’’
largest = max(a,b,c)
smallest = min(a,b,c)
mid = (a+b+c) - largest – smallest
return mid
23
Python’s docstring
• Python provides a convenient way to associate documentation with a
function.
• A string included after the function header becomes the help
documentation for that function.
• As this will require more than one line, we will use special string
delimiters: three single quotes before and after our design recipe
steps.
24
Basic docstring usage
25
Why we use the design recipe
• It provides a place to start.
26
What goes in the body of a Python function?
• Assignment statements
• May introduce new, local variables
• return statement
• Will be last code executed when present
27
Variables in functions are local
• In middle,
largest, smallest, mid
are local variables.
28
Example: Write a Python function to compute
the area of a circle with nonnegative radius r
import math
def area_circle(radius):
‘’’ returns the area of a circle with
the given radius
Examples:
area_circle(0.0) => 0.0
area_circle(1.0) => 3.14159265
’’’
29
Indentation in Python
• A small change in indentation will lead to error
def tens_digit(n):
’’’ returns the tens digit in n
tens_digit: Nat -> Nat
Examples:
tens_digit(1234) => 3
tens_digit(4) => 0
’’’
div10 = n // 10
tens = div10 % 10
return tens
30
Investigating return further
def total_digits(secret): Assume
ones = secret % 10
tens = secret // 10
sum = ones + tens
return
>>> d = total_digits(74)
def calculation(secret):
s = total_digits(secret)
return secret - s
c = calculation(74)
32
More on Basic Types in Python
• Remember that the differences between integers and floating point
numbers can complicate calculations
• Python has many built-in conversion functions from one basic type to
another
33
How to get the type we want
• float: Int → Float
• float(1) → 1.0
• float(10) → 10.0
• float: Str → Float
• float("34.1") → 34.1
• float("2.7.2") → Error
• float("23") → 23.0
• float: Float → Float
• float(23.4) → 23.4
34
More casting functions
• int: (any of Float Str Int) → Int
• int(4.7) → 4
• int(3.0/4) → 0
• int(-12.4) → -12
• int("23") → 23
• int("2.3") → Error
35
Review
• Become comfortable in Python
• Basic types and mathematical operations
• Calling functions
• Defining functions
• Using return correctly
• Design recipe in Python
36