Skip to content
Snippets Groups Projects
Commit b3eac698 authored by GURMAIL SINGH's avatar GURMAIL SINGH
Browse files

Minor change

parent 2e74835e
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
# Using Functions # Using Functions
   
## Readings ## Readings
   
- Parts of Chapter 3 of Think Python - Parts of Chapter 3 of Think Python
- Chapter 5.1 to 5.4 of Python for Everybody - Chapter 5.1 to 5.4 of Python for Everybody
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
### Self-practice ### Self-practice
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Short-circuiting with `and`, `or` Short-circuiting with `and`, `or`
   
- if the first half of an AND is False, skip the second half for evaluation - if the first half of an AND is False, skip the second half for evaluation
- if the first half of an OR is True, skip the second half for evaluation - if the first half of an OR is True, skip the second half for evaluation
   
Predict the output of each expression and then uncomment and run the expression, to validate. Predict the output of each expression and then uncomment and run the expression, to validate.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(7+3 == 9 and 4/0 == 0) # False print(7+3 == 9 and 4/0 == 0) # False
print(7 + 3 == 10 or 4/0 == 0) # True print(7 + 3 == 10 or 4/0 == 0) # True
print(4/0 == 0 and 7+3 == 9) # ZeroDivisionError print(4/0 == 0 and 7+3 == 9) # ZeroDivisionError
#print(4/0 == 0 or 7+3 == 10) # ZeroDivisionError #print(4/0 == 0 or 7+3 == 10) # ZeroDivisionError
# print(4+5 == 9 or 5**10000000 < 10000000) # True # print(4+5 == 9 or 5**10000000 < 10000000) # True
``` ```
   
%% Output %% Output
   
False False
True True
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last) ZeroDivisionError Traceback (most recent call last)
Input In [1], in <cell line: 3>() Input In [1], in <cell line: 3>()
1 print(7+3 == 9 and 4/0 == 0) # False 1 print(7+3 == 9 and 4/0 == 0) # False
2 print(7 + 3 == 10 or 4/0 == 0) # True 2 print(7 + 3 == 10 or 4/0 == 0) # True
----> 3 print(4/0 == 0 and 7+3 == 9) ----> 3 print(4/0 == 0 and 7+3 == 9)
ZeroDivisionError: division by zero ZeroDivisionError: division by zero
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Learning Objectives ## Learning Objectives
   
- Call `input()` to accept and process string input - Call `input()` to accept and process string input
- Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()` - Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()`
- Concatenate values onto strings within a print function by converting to `str()` - Concatenate values onto strings within a print function by converting to `str()`
- Using correct vocabulary, explain a function call - Using correct vocabulary, explain a function call
- call/invoke, parameter, argument, keyword arguments, return value - call/invoke, parameter, argument, keyword arguments, return value
- Use `sep`, `end` keyword arguments with the print() function - Use `sep`, `end` keyword arguments with the print() function
- Yse some common built-in functions such as round(), abs() - Yse some common built-in functions such as round(), abs()
- import functions from a built-in module using `import`, `from` - import functions from a built-in module using `import`, `from`
- Call functions in modules using the attribute operator `.` - Call functions in modules using the attribute operator `.`
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
<div> <div>
<img src="attachment:Function_example.png" width="800"/> <img src="attachment:Function_example.png" width="800"/>
</div> </div>
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Vocabulary ## Vocabulary
   
- **function definition**: a grouping of lines of code; a way for us to tell our program to run that entire group of code - **function definition**: a grouping of lines of code; a way for us to tell our program to run that entire group of code
- **call / invoke**: a statement in Python code that instructs the program to run all the lines of code in a function definition, and then come back afterward - **call / invoke**: a statement in Python code that instructs the program to run all the lines of code in a function definition, and then come back afterward
- **parameter**: variable that receives input to function - **parameter**: variable that receives input to function
- **argument**: value sent to a function (lines up with parameter) - **argument**: value sent to a function (lines up with parameter)
- **keyword argument**: argument explicitly tied to a parameter - **keyword argument**: argument explicitly tied to a parameter
- **return value**: function output sent back to calling code - **return value**: function output sent back to calling code
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Calling / invoking a function ## Calling / invoking a function
   
- Syntax: `function_name(argument1, argument2, ...)` - Syntax: `function_name(argument1, argument2, ...)`
- ALWAYS: - ALWAYS:
- function’s name - function’s name
- followed by parenthesis (even if you have 0 arguments) - followed by parenthesis (even if you have 0 arguments)
- SOMETIMES: - SOMETIMES:
- one or more arguments: each argument is separated by a comma `,` - one or more arguments: each argument is separated by a comma `,`
- return value (result) - return value (result)
- Examples: - Examples:
- `print("Hello, world!")` - `print("Hello, world!")`
- `type(222 - 2)` - `type(222 - 2)`
- `len("Friday")` - `len("Friday")`
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Recall print(...), type(...) functions ## Recall print(...), type(...) functions
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print("hello\nworld") print("hello\nworld")
``` ```
   
%% Output %% Output
   
hello hello
world world
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
type(1) type(1)
``` ```
   
%% Output %% Output
   
int int
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
You could either display the return value of a function into an output box or capture it into a variable. You could either display the return value of a function into an output box or capture it into a variable.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
t = type(1 == 1.0) t = type(1 == 1.0)
print(t) print(t)
``` ```
   
%% Output %% Output
   
<class 'bool'> <class 'bool'>
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
One function's return value can become another function's argument directly. One function's return value can become another function's argument directly.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(type(1 == 1.0)) print(type(1 == 1.0))
``` ```
   
%% Output %% Output
   
<class 'bool'> <class 'bool'>
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## input() ## input()
- accepts user input - accepts user input
- argument to input() function is a prompt - argument to input() function is a prompt
- prompt provides meaningful information to the user - prompt provides meaningful information to the user
- return value of input() function is always of type str - return value of input() function is always of type str
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 1: Accept user input for name and say hello. Example 1: Accept user input for name and say hello.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
#TODO: call input function and capture the return value into a variable called "name" #TODO: call input function and capture the return value into a variable called "name"
name = input("Enter your name: ") name = input("Enter your name: ")
#TODO: print type of the variable name #TODO: print type of the variable name
print(type(name)) print(type(name))
print("Hello " + name + "!") print("Hello " + name + "!")
``` ```
   
%% Output %% Output
   
Enter your name: Gurmail Enter your name: Gurmail
<class 'str'> <class 'str'>
Hello Gurmail! Hello Gurmail!
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 2a: Accept user input for age (incorrect version) Example 2a: Accept user input for age (incorrect version)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
age = input("Enter your age: ") age = input("Enter your age: ")
#TODO: print type of the variable age #TODO: print type of the variable age
print(type(age)) print(type(age))
# Let's celebrate a birthday :) # Let's celebrate a birthday :)
age += 1 # What is wrong? age += 1 # What is wrong?
print(age) print(age)
``` ```
   
%% Output %% Output
   
Enter your age: 38 Enter your age: 38
<class 'str'> <class 'str'>
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
TypeError Traceback (most recent call last) TypeError Traceback (most recent call last)
Input In [7], in <cell line: 5>() Input In [7], in <cell line: 5>()
3 print(type(age)) 3 print(type(age))
4 # Let's celebrate a birthday :) 4 # Let's celebrate a birthday :)
----> 5 age += 1 # What is wrong? ----> 5 age += 1 # What is wrong?
6 print(age) 6 print(age)
TypeError: can only concatenate str (not "int") to str TypeError: can only concatenate str (not "int") to str
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Type casting functions ## Type casting functions
- convert one type into another type - convert one type into another type
- int(), float(), str(), bool() - int(), float(), str(), bool()
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these int conversions # Let's try these int conversions
print(int(32.5)) print(int(32.5))
print(int("2012") + 10) print(int("2012") + 10)
# Some conversions don't make sense to us # Some conversions don't make sense to us
# So they won't make sense to Python either # So they won't make sense to Python either
print(int("nineteen")) print(int("nineteen"))
``` ```
   
%% Output %% Output
   
32 32
2022 2022
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
ValueError Traceback (most recent call last) ValueError Traceback (most recent call last)
Input In [8], in <cell line: 6>() Input In [8], in <cell line: 6>()
3 print(int("2012") + 10) 3 print(int("2012") + 10)
4 # Some conversions don't make sense to us 4 # Some conversions don't make sense to us
5 # So they won't make sense to Python either 5 # So they won't make sense to Python either
----> 6 print(int("nineteen")) ----> 6 print(int("nineteen"))
ValueError: invalid literal for int() with base 10: 'nineteen' ValueError: invalid literal for int() with base 10: 'nineteen'
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(int(32.5)) # this works print(int(32.5)) # this works
print(int(float("32.5"))) # this works print(int(float("32.5"))) # this works
   
# this doesn't work, less intuitive (tricky case!) # this doesn't work, less intuitive (tricky case!)
print(int("32.5")) print(int("32.5"))
``` ```
   
%% Output %% Output
   
32 32
32 32
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
ValueError Traceback (most recent call last) ValueError Traceback (most recent call last)
Input In [9], in <cell line: 5>() Input In [9], in <cell line: 5>()
2 print(int(float("32.5"))) # this works 2 print(int(float("32.5"))) # this works
4 # this doesn't work, less intuitive (tricky case!) 4 # this doesn't work, less intuitive (tricky case!)
----> 5 print(int("32.5")) ----> 5 print(int("32.5"))
ValueError: invalid literal for int() with base 10: '32.5' ValueError: invalid literal for int() with base 10: '32.5'
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these float conversions # Let's try these float conversions
print(float(26)) print(float(26))
print(float("3.14") * 2) print(float("3.14") * 2)
# Some conversions don't make sense to us # Some conversions don't make sense to us
# So they won't make sense to Python either # So they won't make sense to Python either
print(float("three point one")) print(float("three point one"))
``` ```
   
%% Output %% Output
   
26.0 26.0
6.28 6.28
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
ValueError Traceback (most recent call last) ValueError Traceback (most recent call last)
Input In [10], in <cell line: 6>() Input In [10], in <cell line: 6>()
3 print(float("3.14") * 2) 3 print(float("3.14") * 2)
4 # Some conversions don't make sense to us 4 # Some conversions don't make sense to us
5 # So they won't make sense to Python either 5 # So they won't make sense to Python either
----> 6 print(float("three point one")) ----> 6 print(float("three point one"))
ValueError: could not convert string to float: 'three point one' ValueError: could not convert string to float: 'three point one'
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these str conversions # Let's try these str conversions
year = 2022 year = 2023
print("Next year will be: " + str(year+1)) print("Next year will be: " + str(year+1))
print("It is good to be: " + str(True)) print("It is good to be: " + str(True))
print("Who wants a pi? " + str(3.14)) print("Who wants a pi? " + str(3.14))
#Pretty much you can convert anything to string in Python #Pretty much you can convert anything to string in Python
``` ```
   
%% Output %% Output
   
Next year will be: 2023 Next year will be: 2024
It is good to be: True It is good to be: True
Who wants a pi? 3.14 Who wants a pi? 3.14
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 2b: Accept user input for age (correct version) Example 2b: Accept user input for age (correct version)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
age = input("Enter your age: ") age = input("Enter your age: ")
#TODO: convert age to int type #TODO: convert age to int type
age = int(age) # Just saying int(age) won't work, you have to re-assign age variable age = int(age) # Just saying int(age) won't work, you have to re-assign age variable
# Let's celebrate a birthday :) # Let's celebrate a birthday :)
age += 1 age += 1
print(age) print(age)
``` ```
   
%% Output %% Output
   
Enter your age: 38 Enter your age: 38
39 39
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 3: Accept user input for temperature Example 3: Accept user input for temperature
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# To enter their day care, kids have their temp checked # To enter their day care, kids have their temp checked
temp = float(input("Enter your temperature: ")) temp = float(input("Enter your temperature: "))
temp = float(temp) temp = float(temp)
#TODO: check that temp is less than equal to 98.6 #TODO: check that temp is less than equal to 98.6
temp_ok = temp <= 98.6 temp_ok = temp <= 98.6
#TODO: print type of temp_ok #TODO: print type of temp_ok
print(type(temp_ok)) print(type(temp_ok))
print("OK to enter: " + str(temp_ok)) print("OK to enter: " + str(temp_ok))
``` ```
   
%% Output %% Output
   
Enter your temperature: 70 Enter your temperature: 72
<class 'bool'> <class 'bool'>
OK to enter: True OK to enter: True
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# TODO: figure out how this works # TODO: figure out how this works
print("Somebody had a birthday: " + name + " " + str(age) + " years old :)") print("Somebody had a birthday: " + name + " " + str(age) + " years old :)")
# TODO: What error will you get when you take out str(...) around age? # TODO: What error will you get when you take out str(...) around age?
``` ```
   
%% Output %% Output
   
Somebody had a birthday: Gurmail 39 years old :) Somebody had a birthday: Gurmail 39 years old :)
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
### parameters for print(...) function ### parameters for print(...) function
- can accept multiple arguments: - can accept multiple arguments:
- all arguments get printed on the same line - all arguments get printed on the same line
- `sep` allows you to configure separator between the arguments: - `sep` allows you to configure separator between the arguments:
- default value: space `" "` - default value: space `" "`
- `end` allows you to configure what character gets printed after - `end` allows you to configure what character gets printed after
- default value: newline `"\n"` - default value: newline `"\n"`
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Instead of using + (concatenation) operator, we could pass multiple arguments to print # Instead of using + (concatenation) operator, we could pass multiple arguments to print
print("hello", "world") print("hello", "world")
print("hello", "cs220/cs319") print("hello", "cs220/cs319")
``` ```
   
%% Output %% Output
   
hello world hello world
hello cs220/cs319 hello cs220/cs319
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print("hello", "cs220/cs319", sep = "---") print("hello", "cs220/cs319", sep = "---")
print("hello", "cs220/cs319", end = "!!!\n") print("hello", "cs220/cs319", end = "!!!\n")
``` ```
   
%% Output %% Output
   
hello---cs220/cs319 hello---cs220/cs319
hello cs220/cs319!!! hello cs220/cs319!!!
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Self-practic: Guess what will get printed # Self-practic: Guess what will get printed
print("hello", "world", sep = "|", end = ";\n") print("hello", "world", sep = "|", end = ";\n")
print("hello", "world", sep = "^", end = "...\n") print("hello", "world", sep = "^", end = "...\n")
   
print("*" * 4, "#" * 6, sep = "||", end = "<END>") print("*" * 4, "#" * 6, sep = "||", end = "<END>")
print("*" * 6, "#" * 8, sep = "||", end = "<END>") print("*" * 6, "#" * 8, sep = "||", end = "<END>")
   
print("\n", end = "") print("\n", end = "")
   
print("*" * 4, "#" * 6, sep = "||", end = "<END>\n") print("*" * 4, "#" * 6, sep = "||", end = "<END>\n")
print("*" * 6, "#" * 8, sep = "||", end = "<END>\n") print("*" * 6, "#" * 8, sep = "||", end = "<END>\n")
``` ```
   
%% Output %% Output
   
hello|world; hello|world;
hello^world... hello^world...
****||######<END>******||########<END> ****||######<END>******||########<END>
****||######<END> ****||######<END>
******||########<END> ******||########<END>
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## More built-in functions ## More built-in functions
- print(), type(), int(), float(), str(), bool() are all examples of built-in functions - print(), type(), int(), float(), str(), bool() are all examples of built-in functions
- built-in functions are functions you can use readily (without importing anything) - built-in functions are functions you can use readily (without importing anything)
- you definitely don't have to know all the built-in functions, but here is the list: https://docs.python.org/3/library/functions.html - you definitely don't have to know all the built-in functions, but here is the list: https://docs.python.org/3/library/functions.html
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
abs function abs function
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Guess what will get printed # Guess what will get printed
print(abs(-10)) print(abs(-10))
print(abs(10)) print(abs(10))
``` ```
   
%% Output %% Output
   
10 10
10 10
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
round function round function
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Guess what will get printed # Guess what will get printed
print(round(10.525252, 4)) print(round(10.525252, 4))
print(round(5.2953, 2)) print(round(5.2953, 2))
print(round(5.2423, 2)) print(round(5.2423, 2))
``` ```
   
%% Output %% Output
   
10.5253 10.5253
5.3 5.3
5.24 5.24
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Modules ## Modules
- collection of similar functions and variables - collection of similar functions and variables
- requires import - requires import
- `import`, `from` keywords - `import`, `from` keywords
- 2 styles of import: - 2 styles of import:
1. `import` module_name: 1. `import` module_name:
- need to specify module_name`.`function_name to call it. - need to specify module_name`.`function_name to call it.
- `.` is called attribute operator. - `.` is called attribute operator.
2. `from` module_name `import` function_name 2. `from` module_name `import` function_name
- can call the function without specifying module name - can call the function without specifying module name
- `help` module_name: - `help` module_name:
- documentation for all functions and variables inside a module - documentation for all functions and variables inside a module
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try to find square root of 10 # Let's try to find square root of 10
sqrt(10) # doesn't work because it is part of math module sqrt(10) # doesn't work because it is part of math module
``` ```
   
%% Output %% Output
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
NameError Traceback (most recent call last) NameError Traceback (most recent call last)
Input In [20], in <cell line: 2>() Input In [20], in <cell line: 2>()
1 # Let's try to find square root of 10 1 # Let's try to find square root of 10
----> 2 sqrt(10) ----> 2 sqrt(10)
NameError: name 'sqrt' is not defined NameError: name 'sqrt' is not defined
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
It is a good practice to include all your import statements at the top of your notebook file. We will make exception just for a couple of lectures. It is a good practice to include all your import statements at the top of your notebook file. We will make exception just for a couple of lectures.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
import math import math
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.sqrt(10) math.sqrt(10)
``` ```
   
%% Output %% Output
   
3.1622776601683795 3.1622776601683795
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.cos(3.14159) math.cos(3.14159)
``` ```
   
%% Output %% Output
   
-0.9999999999964793 -0.9999999999964793
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Modules contain useful variables too. Modules contain useful variables too.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.pi math.pi
``` ```
   
%% Output %% Output
   
3.141592653589793 3.141592653589793
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's get help # Let's get help
help(math) help(math)
``` ```
   
%% Output %% Output
   
Help on built-in module math: Help on built-in module math:
NAME NAME
math math
DESCRIPTION DESCRIPTION
This module provides access to the mathematical functions This module provides access to the mathematical functions
defined by the C standard. defined by the C standard.
FUNCTIONS FUNCTIONS
acos(x, /) acos(x, /)
Return the arc cosine (measured in radians) of x. Return the arc cosine (measured in radians) of x.
The result is between 0 and pi. The result is between 0 and pi.
acosh(x, /) acosh(x, /)
Return the inverse hyperbolic cosine of x. Return the inverse hyperbolic cosine of x.
asin(x, /) asin(x, /)
Return the arc sine (measured in radians) of x. Return the arc sine (measured in radians) of x.
The result is between -pi/2 and pi/2. The result is between -pi/2 and pi/2.
asinh(x, /) asinh(x, /)
Return the inverse hyperbolic sine of x. Return the inverse hyperbolic sine of x.
atan(x, /) atan(x, /)
Return the arc tangent (measured in radians) of x. Return the arc tangent (measured in radians) of x.
The result is between -pi/2 and pi/2. The result is between -pi/2 and pi/2.
atan2(y, x, /) atan2(y, x, /)
Return the arc tangent (measured in radians) of y/x. Return the arc tangent (measured in radians) of y/x.
Unlike atan(y/x), the signs of both x and y are considered. Unlike atan(y/x), the signs of both x and y are considered.
atanh(x, /) atanh(x, /)
Return the inverse hyperbolic tangent of x. Return the inverse hyperbolic tangent of x.
ceil(x, /) ceil(x, /)
Return the ceiling of x as an Integral. Return the ceiling of x as an Integral.
This is the smallest integer >= x. This is the smallest integer >= x.
comb(n, k, /) comb(n, k, /)
Number of ways to choose k items from n items without repetition and without order. Number of ways to choose k items from n items without repetition and without order.
Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates Evaluates to n! / (k! * (n - k)!) when k <= n and evaluates
to zero when k > n. to zero when k > n.
Also called the binomial coefficient because it is equivalent Also called the binomial coefficient because it is equivalent
to the coefficient of k-th term in polynomial expansion of the to the coefficient of k-th term in polynomial expansion of the
expression (1 + x)**n. expression (1 + x)**n.
Raises TypeError if either of the arguments are not integers. Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative. Raises ValueError if either of the arguments are negative.
copysign(x, y, /) copysign(x, y, /)
Return a float with the magnitude (absolute value) of x but the sign of y. Return a float with the magnitude (absolute value) of x but the sign of y.
On platforms that support signed zeros, copysign(1.0, -0.0) On platforms that support signed zeros, copysign(1.0, -0.0)
returns -1.0. returns -1.0.
cos(x, /) cos(x, /)
Return the cosine of x (measured in radians). Return the cosine of x (measured in radians).
cosh(x, /) cosh(x, /)
Return the hyperbolic cosine of x. Return the hyperbolic cosine of x.
degrees(x, /) degrees(x, /)
Convert angle x from radians to degrees. Convert angle x from radians to degrees.
dist(p, q, /) dist(p, q, /)
Return the Euclidean distance between two points p and q. Return the Euclidean distance between two points p and q.
The points should be specified as sequences (or iterables) of The points should be specified as sequences (or iterables) of
coordinates. Both inputs must have the same dimension. coordinates. Both inputs must have the same dimension.
Roughly equivalent to: Roughly equivalent to:
sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q))) sqrt(sum((px - qx) ** 2.0 for px, qx in zip(p, q)))
erf(x, /) erf(x, /)
Error function at x. Error function at x.
erfc(x, /) erfc(x, /)
Complementary error function at x. Complementary error function at x.
exp(x, /) exp(x, /)
Return e raised to the power of x. Return e raised to the power of x.
expm1(x, /) expm1(x, /)
Return exp(x)-1. Return exp(x)-1.
This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x. This function avoids the loss of precision involved in the direct evaluation of exp(x)-1 for small x.
fabs(x, /) fabs(x, /)
Return the absolute value of the float x. Return the absolute value of the float x.
factorial(x, /) factorial(x, /)
Find x!. Find x!.
Raise a ValueError if x is negative or non-integral. Raise a ValueError if x is negative or non-integral.
floor(x, /) floor(x, /)
Return the floor of x as an Integral. Return the floor of x as an Integral.
This is the largest integer <= x. This is the largest integer <= x.
fmod(x, y, /) fmod(x, y, /)
Return fmod(x, y), according to platform C. Return fmod(x, y), according to platform C.
x % y may differ. x % y may differ.
frexp(x, /) frexp(x, /)
Return the mantissa and exponent of x, as pair (m, e). Return the mantissa and exponent of x, as pair (m, e).
m is a float and e is an int, such that x = m * 2.**e. m is a float and e is an int, such that x = m * 2.**e.
If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0. If x is 0, m and e are both 0. Else 0.5 <= abs(m) < 1.0.
fsum(seq, /) fsum(seq, /)
Return an accurate floating point sum of values in the iterable seq. Return an accurate floating point sum of values in the iterable seq.
Assumes IEEE-754 floating point arithmetic. Assumes IEEE-754 floating point arithmetic.
gamma(x, /) gamma(x, /)
Gamma function at x. Gamma function at x.
gcd(*integers) gcd(*integers)
Greatest Common Divisor. Greatest Common Divisor.
hypot(...) hypot(...)
hypot(*coordinates) -> value hypot(*coordinates) -> value
Multidimensional Euclidean distance from the origin to a point. Multidimensional Euclidean distance from the origin to a point.
Roughly equivalent to: Roughly equivalent to:
sqrt(sum(x**2 for x in coordinates)) sqrt(sum(x**2 for x in coordinates))
For a two dimensional point (x, y), gives the hypotenuse For a two dimensional point (x, y), gives the hypotenuse
using the Pythagorean theorem: sqrt(x*x + y*y). using the Pythagorean theorem: sqrt(x*x + y*y).
For example, the hypotenuse of a 3/4/5 right triangle is: For example, the hypotenuse of a 3/4/5 right triangle is:
>>> hypot(3.0, 4.0) >>> hypot(3.0, 4.0)
5.0 5.0
isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0)
Determine whether two floating point numbers are close in value. Determine whether two floating point numbers are close in value.
rel_tol rel_tol
maximum difference for being considered "close", relative to the maximum difference for being considered "close", relative to the
magnitude of the input values magnitude of the input values
abs_tol abs_tol
maximum difference for being considered "close", regardless of the maximum difference for being considered "close", regardless of the
magnitude of the input values magnitude of the input values
Return True if a is close in value to b, and False otherwise. Return True if a is close in value to b, and False otherwise.
For the values to be considered close, the difference between them For the values to be considered close, the difference between them
must be smaller than at least one of the tolerances. must be smaller than at least one of the tolerances.
-inf, inf and NaN behave similarly to the IEEE 754 Standard. That -inf, inf and NaN behave similarly to the IEEE 754 Standard. That
is, NaN is not close to anything, even itself. inf and -inf are is, NaN is not close to anything, even itself. inf and -inf are
only close to themselves. only close to themselves.
isfinite(x, /) isfinite(x, /)
Return True if x is neither an infinity nor a NaN, and False otherwise. Return True if x is neither an infinity nor a NaN, and False otherwise.
isinf(x, /) isinf(x, /)
Return True if x is a positive or negative infinity, and False otherwise. Return True if x is a positive or negative infinity, and False otherwise.
isnan(x, /) isnan(x, /)
Return True if x is a NaN (not a number), and False otherwise. Return True if x is a NaN (not a number), and False otherwise.
isqrt(n, /) isqrt(n, /)
Return the integer part of the square root of the input. Return the integer part of the square root of the input.
lcm(*integers) lcm(*integers)
Least Common Multiple. Least Common Multiple.
ldexp(x, i, /) ldexp(x, i, /)
Return x * (2**i). Return x * (2**i).
This is essentially the inverse of frexp(). This is essentially the inverse of frexp().
lgamma(x, /) lgamma(x, /)
Natural logarithm of absolute value of Gamma function at x. Natural logarithm of absolute value of Gamma function at x.
log(...) log(...)
log(x, [base=math.e]) log(x, [base=math.e])
Return the logarithm of x to the given base. Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x. If the base not specified, returns the natural logarithm (base e) of x.
log10(x, /) log10(x, /)
Return the base 10 logarithm of x. Return the base 10 logarithm of x.
log1p(x, /) log1p(x, /)
Return the natural logarithm of 1+x (base e). Return the natural logarithm of 1+x (base e).
The result is computed in a way which is accurate for x near zero. The result is computed in a way which is accurate for x near zero.
log2(x, /) log2(x, /)
Return the base 2 logarithm of x. Return the base 2 logarithm of x.
modf(x, /) modf(x, /)
Return the fractional and integer parts of x. Return the fractional and integer parts of x.
Both results carry the sign of x and are floats. Both results carry the sign of x and are floats.
nextafter(x, y, /) nextafter(x, y, /)
Return the next floating-point value after x towards y. Return the next floating-point value after x towards y.
perm(n, k=None, /) perm(n, k=None, /)
Number of ways to choose k items from n items without repetition and with order. Number of ways to choose k items from n items without repetition and with order.
Evaluates to n! / (n - k)! when k <= n and evaluates Evaluates to n! / (n - k)! when k <= n and evaluates
to zero when k > n. to zero when k > n.
If k is not specified or is None, then k defaults to n If k is not specified or is None, then k defaults to n
and the function returns n!. and the function returns n!.
Raises TypeError if either of the arguments are not integers. Raises TypeError if either of the arguments are not integers.
Raises ValueError if either of the arguments are negative. Raises ValueError if either of the arguments are negative.
pow(x, y, /) pow(x, y, /)
Return x**y (x to the power of y). Return x**y (x to the power of y).
prod(iterable, /, *, start=1) prod(iterable, /, *, start=1)
Calculate the product of all the elements in the input iterable. Calculate the product of all the elements in the input iterable.
The default start value for the product is 1. The default start value for the product is 1.
When the iterable is empty, return the start value. This function is When the iterable is empty, return the start value. This function is
intended specifically for use with numeric values and may reject intended specifically for use with numeric values and may reject
non-numeric types. non-numeric types.
radians(x, /) radians(x, /)
Convert angle x from degrees to radians. Convert angle x from degrees to radians.
remainder(x, y, /) remainder(x, y, /)
Difference between x and the closest integer multiple of y. Difference between x and the closest integer multiple of y.
Return x - n*y where n*y is the closest integer multiple of y. Return x - n*y where n*y is the closest integer multiple of y.
In the case where x is exactly halfway between two multiples of In the case where x is exactly halfway between two multiples of
y, the nearest even value of n is used. The result is always exact. y, the nearest even value of n is used. The result is always exact.
sin(x, /) sin(x, /)
Return the sine of x (measured in radians). Return the sine of x (measured in radians).
sinh(x, /) sinh(x, /)
Return the hyperbolic sine of x. Return the hyperbolic sine of x.
sqrt(x, /) sqrt(x, /)
Return the square root of x. Return the square root of x.
tan(x, /) tan(x, /)
Return the tangent of x (measured in radians). Return the tangent of x (measured in radians).
tanh(x, /) tanh(x, /)
Return the hyperbolic tangent of x. Return the hyperbolic tangent of x.
trunc(x, /) trunc(x, /)
Truncates the Real x to the nearest Integral toward 0. Truncates the Real x to the nearest Integral toward 0.
Uses the __trunc__ magic method. Uses the __trunc__ magic method.
ulp(x, /) ulp(x, /)
Return the value of the least significant bit of the float x. Return the value of the least significant bit of the float x.
DATA DATA
e = 2.718281828459045 e = 2.718281828459045
inf = inf inf = inf
nan = nan nan = nan
pi = 3.141592653589793 pi = 3.141592653589793
tau = 6.283185307179586 tau = 6.283185307179586
FILE FILE
(built-in) (built-in)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
from random import randint from random import randint
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(randint(1,10)) # correct invocation print(randint(1,10)) # correct invocation
``` ```
   
%% Output %% Output
   
5 9
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(random.randint(1,10)) # incorrect invocation print(random.randint(1,10)) # incorrect invocation
``` ```
   
%% Output %% Output
   
--------------------------------------------------------------------------- ---------------------------------------------------------------------------
NameError Traceback (most recent call last) NameError Traceback (most recent call last)
Input In [28], in <cell line: 1>() Input In [28], in <cell line: 1>()
----> 1 print(random.randint(1,10)) ----> 1 print(random.randint(1,10))
NameError: name 'random' is not defined NameError: name 'random' is not defined
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
import random import random
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(random.randint(1,10)) print(random.randint(1,10))
``` ```
   
%% Output %% Output
   
6 7
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(random.uniform(1,10)) print(random.uniform(1,10))
``` ```
   
%% Output %% Output
   
2.1271689697278386 7.745758054798275
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
# Using Functions # Using Functions
   
## Readings ## Readings
   
- Parts of Chapter 3 of Think Python - Parts of Chapter 3 of Think Python
- Chapter 5.1 to 5.4 of Python for Everybody - Chapter 5.1 to 5.4 of Python for Everybody
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
### Self-practice ### Self-practice
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Short-circuiting with `and`, `or` Short-circuiting with `and`, `or`
   
- if the first half of an AND is False, skip the second half for evaluation - if the first half of an AND is False, skip the second half for evaluation
- if the first half of an OR is True, skip the second half for evaluation - if the first half of an OR is True, skip the second half for evaluation
   
Predict the output of each expression and then uncomment and run the expression, to validate. Predict the output of each expression and then uncomment and run the expression, to validate.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(7+3 == 9 and 4/0 == 0) # False print(7+3 == 9 and 4/0 == 0) # False
print(7 + 3 == 10 or 4/0 == 0) # True print(7 + 3 == 10 or 4/0 == 0) # True
#print(4/0 == 0 and 7+3 == 9) # ZeroDivisionError #print(4/0 == 0 and 7+3 == 9) # ZeroDivisionError
#print(4/0 == 0 or 7+3 == 10) # ZeroDivisionError #print(4/0 == 0 or 7+3 == 10) # ZeroDivisionError
print(4+5 == 9 or 5**10000000 < 10000000) # True print(4+5 == 9 or 5**10000000 < 10000000) # True
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Learning Objectives ## Learning Objectives
   
- Call `input()` to accept and process string input - Call `input()` to accept and process string input
- Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()` - Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()`
- Concatenate values onto strings within a print function by converting to `str()` - Concatenate values onto strings within a print function by converting to `str()`
- Using correct vocabulary, explain a function call - Using correct vocabulary, explain a function call
- call/invoke, parameter, argument, keyword arguments, return value - call/invoke, parameter, argument, keyword arguments, return value
- Use `sep`, `end` keyword arguments with the print() function - Use `sep`, `end` keyword arguments with the print() function
- Yse some common built-in functions such as round(), abs() - Yse some common built-in functions such as round(), abs()
- import functions from a built-in module using `import`, `from` - import functions from a built-in module using `import`, `from`
- Call functions in modules using the attribute operator `.` - Call functions in modules using the attribute operator `.`
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
<div> <div>
<img src="attachment:Function_example.png" width="800"/> <img src="attachment:Function_example.png" width="800"/>
</div> </div>
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Vocabulary ## Vocabulary
   
- **function definition**: a grouping of lines of code; a way for us to tell our program to run that entire group of code - **function definition**: a grouping of lines of code; a way for us to tell our program to run that entire group of code
- **call / invoke**: a statement in Python code that instructs the program to run all the lines of code in a function definition, and then come back afterward - **call / invoke**: a statement in Python code that instructs the program to run all the lines of code in a function definition, and then come back afterward
- **parameter**: variable that receives input to function - **parameter**: variable that receives input to function
- **argument**: value sent to a function (lines up with parameter) - **argument**: value sent to a function (lines up with parameter)
- **keyword argument**: argument explicitly tied to a parameter - **keyword argument**: argument explicitly tied to a parameter
- **return value**: function output sent back to calling code - **return value**: function output sent back to calling code
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Calling / invoking a function ## Calling / invoking a function
   
- Syntax: `function_name(argument1, argument2, ...)` - Syntax: `function_name(argument1, argument2, ...)`
- ALWAYS: - ALWAYS:
- function’s name - function’s name
- followed by parenthesis (even if you have 0 arguments) - followed by parenthesis (even if you have 0 arguments)
- SOMETIMES: - SOMETIMES:
- one or more arguments: each argument is separated by a comma `,` - one or more arguments: each argument is separated by a comma `,`
- return value (result) - return value (result)
- Examples: - Examples:
- `print("Hello, world!")` - `print("Hello, world!")`
- `type(222 - 2)` - `type(222 - 2)`
- `len("Friday")` - `len("Friday")`
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Recall print(...), type(...) functions ## Recall print(...), type(...) functions
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print("hello\nworld") print("hello\nworld")
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
type(1) type(1)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
You could either display the return value of a function into an output box or capture it into a variable. You could either display the return value of a function into an output box or capture it into a variable.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
t = type(1 == 1.0) t = type(1 == 1.0)
print(t) print(t)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
One function's return value can become another function's argument directly. One function's return value can become another function's argument directly.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(type(1 == 1.0)) print(type(1 == 1.0))
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## input() ## input()
- accepts user input - accepts user input
- argument to input() function is a prompt - argument to input() function is a prompt
- prompt provides meaningful information to the user - prompt provides meaningful information to the user
- return value of input() function is always of type str - return value of input() function is always of type str
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 1: Accept user input for name and say hello. Example 1: Accept user input for name and say hello.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
#TODO: call input function and capture the return value into a variable called "name" #TODO: call input function and capture the return value into a variable called "name"
   
#TODO: print type of the variable name #TODO: print type of the variable name
   
print("Hello " + name + "!") print("Hello " + name + "!")
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 2a: Accept user input for age (incorrect version) Example 2a: Accept user input for age (incorrect version)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
age = input("Enter your age: ") age = input("Enter your age: ")
#TODO: print type of the variable age #TODO: print type of the variable age
   
# Let's celebrate a birthday :) # Let's celebrate a birthday :)
age ??? 1 # What is wrong? age ??? 1 # What is wrong?
print(age) print(age)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Type casting functions ## Type casting functions
- convert one type into another type - convert one type into another type
- int(), float(), str(), bool() - int(), float(), str(), bool()
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these int conversions # Let's try these int conversions
print(int(32.5)) print(int(32.5))
print(int("2012") + 10) print(int("2012") + 10)
# Some conversions don't make sense to us # Some conversions don't make sense to us
# So they won't make sense to Python either # So they won't make sense to Python either
print(int("nineteen")) print(int("nineteen"))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(int(32.5)) # this works print(int(32.5)) # this works
print(int(float("32.5"))) # this works print(int(float("32.5"))) # this works
   
# this doesn't work, less intuitive (tricky case!) # this doesn't work, less intuitive (tricky case!)
print(int("32.5")) print(int("32.5"))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these float conversions # Let's try these float conversions
print(float(26)) print(float(26))
print(float("3.14") * 2) print(float("3.14") * 2)
# Some conversions don't make sense to us # Some conversions don't make sense to us
# So they won't make sense to Python either # So they won't make sense to Python either
print(float("three point one")) print(float("three point one"))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these str conversions # Let's try these str conversions
year = 2022 year = 2023
print("Next year will be: " + year+1) print("Next year will be: " + year+1)
print("It is good to be: " + str(True)) print("It is good to be: " + str(True))
print("Who wants a pi? " + str(3.14)) print("Who wants a pi? " + str(3.14))
#Pretty much you can convert anything to string in Python #Pretty much you can convert anything to string in Python
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 2b: Accept user input for age (correct version) Example 2b: Accept user input for age (correct version)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
age = input("Enter your age: ") age = input("Enter your age: ")
#TODO: convert age to int type #TODO: convert age to int type
age = int(age) # Just saying int(age) won't work, you have to re-assign age variable age = int(age) # Just saying int(age) won't work, you have to re-assign age variable
# Let's celebrate a birthday :) # Let's celebrate a birthday :)
age += 1 age += 1
print(age) print(age)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 3: Accept user input for temperature Example 3: Accept user input for temperature
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# To enter their day care, kids have their temp checked # To enter their day care, kids have their temp checked
temp = float(input("Enter your temperature: ")) temp = float(input("Enter your temperature: "))
temp = float(temp) temp = float(temp)
#TODO: check that temp is less than equal to 98.6 #TODO: check that temp is less than equal to 98.6
temp_ok = temp <= 98.6 temp_ok = temp <= 98.6
#TODO: print type of temp_ok #TODO: print type of temp_ok
print(type(temp_ok)) print(type(temp_ok))
print("OK to enter: " + str(temp_ok)) print("OK to enter: " + str(temp_ok))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# TODO: figure out how this works # TODO: figure out how this works
print("Somebody had a birthday: " + name + " " + str(age) + " years old :)") print("Somebody had a birthday: " + name + " " + str(age) + " years old :)")
# TODO: What error will you get when you take out str(...) around age? # TODO: What error will you get when you take out str(...) around age?
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
### parameters for print(...) function ### parameters for print(...) function
- can accept multiple arguments: - can accept multiple arguments:
- all arguments get printed on the same line - all arguments get printed on the same line
- `sep` allows you to configure separator between the arguments: - `sep` allows you to configure separator between the arguments:
- default value: space `" "` - default value: space `" "`
- `end` allows you to configure what character gets printed after - `end` allows you to configure what character gets printed after
- default value: newline `"\n"` - default value: newline `"\n"`
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Instead of using + (concatenation) operator, we could pass multiple arguments to print # Instead of using + (concatenation) operator, we could pass multiple arguments to print
print("hello" + " world") print("hello" + " world")
print("hello" + " cs220/cs319") print("hello" + " cs220/cs319")
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Self-practic: Guess what will get printed # Self-practic: Guess what will get printed
print("hello", "world", sep = "|", end = ";\n") print("hello", "world", sep = "|", end = ";\n")
print("hello", "world", sep = "^", end = "...\n") print("hello", "world", sep = "^", end = "...\n")
   
print("*" * 4, "#" * 6, sep = "||", end = "<END>") print("*" * 4, "#" * 6, sep = "||", end = "<END>")
print("*" * 6, "#" * 8, sep = "||", end = "<END>") print("*" * 6, "#" * 8, sep = "||", end = "<END>")
   
print("\n", end = "") print("\n", end = "")
   
print("*" * 4, "#" * 6, sep = "||", end = "<END>\n") print("*" * 4, "#" * 6, sep = "||", end = "<END>\n")
print("*" * 6, "#" * 8, sep = "||", end = "<END>\n") print("*" * 6, "#" * 8, sep = "||", end = "<END>\n")
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## More built-in functions ## More built-in functions
- print(), type(), int(), float(), str(), bool() are all examples of built-in functions - print(), type(), int(), float(), str(), bool() are all examples of built-in functions
- built-in functions are functions you can use readily (without importing anything) - built-in functions are functions you can use readily (without importing anything)
- you definitely don't have to know all the built-in functions, but here is the list: https://docs.python.org/3/library/functions.html - you definitely don't have to know all the built-in functions, but here is the list: https://docs.python.org/3/library/functions.html
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
abs function abs function
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Guess what will get printed # Guess what will get printed
print(abs(-10)) print(abs(-10))
print(abs(10)) print(abs(10))
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
round function round function
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Guess what will get printed # Guess what will get printed
print(round(10.525252, 4)) print(round(10.525252, 4))
print(round(5.2953, 2)) print(round(5.2953, 2))
print(round(5.2423, 2)) print(round(5.2423, 2))
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Modules ## Modules
- collection of similar functions and variables - collection of similar functions and variables
- requires import - requires import
- `import`, `from` keywords - `import`, `from` keywords
- 2 styles of import: - 2 styles of import:
1. `import` module_name: 1. `import` module_name:
- need to specify module_name`.`function_name to call it. - need to specify module_name`.`function_name to call it.
- `.` is called attribute operator. - `.` is called attribute operator.
2. `from` module_name `import` function_name 2. `from` module_name `import` function_name
- can call the function without specifying module name - can call the function without specifying module name
- `help` module_name: - `help` module_name:
- documentation for all functions and variables inside a module - documentation for all functions and variables inside a module
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try to find square root of 10 # Let's try to find square root of 10
sqrt(10) # doesn't work because it is part of math module sqrt(10) # doesn't work because it is part of math module
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
It is a good practice to include all your import statements at the top of your notebook file. We will make exception just for a couple of lectures. It is a good practice to include all your import statements at the top of your notebook file. We will make exception just for a couple of lectures.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
import math import math
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.sqrt(10) math.sqrt(10)
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.cos(3.14159) math.cos(3.14159)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Modules contain useful variables too. Modules contain useful variables too.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.pi math.pi
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's get help # Let's get help
help(math) help(math)
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
from random import randint from random import randint
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(randint(1,10)) # correct invocation print(randint(1,10)) # correct invocation
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(random.randint(1,10)) # incorrect invocation print(random.randint(1,10)) # incorrect invocation
``` ```
......
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
# Using Functions # Using Functions
   
## Readings ## Readings
   
- Parts of Chapter 3 of Think Python - Parts of Chapter 3 of Think Python
- Chapter 5.1 to 5.4 of Python for Everybody - Chapter 5.1 to 5.4 of Python for Everybody
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
### Self-practice ### Self-practice
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Short-circuiting with `and`, `or` Short-circuiting with `and`, `or`
   
- if the first half of an AND is False, skip the second half for evaluation - if the first half of an AND is False, skip the second half for evaluation
- if the first half of an OR is True, skip the second half for evaluation - if the first half of an OR is True, skip the second half for evaluation
   
Predict the output of each expression and then uncomment and run the expression, to validate. Predict the output of each expression and then uncomment and run the expression, to validate.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(7+3 == 9 and 4/0 == 0) # False print(7+3 == 9 and 4/0 == 0) # False
print(7 + 3 == 10 or 4/0 == 0) # True print(7 + 3 == 10 or 4/0 == 0) # True
#print(4/0 == 0 and 7+3 == 9) # ZeroDivisionError #print(4/0 == 0 and 7+3 == 9) # ZeroDivisionError
#print(4/0 == 0 or 7+3 == 10) # ZeroDivisionError #print(4/0 == 0 or 7+3 == 10) # ZeroDivisionError
print(4+5 == 9 or 5**10000000 < 10000000) # True print(4+5 == 9 or 5**10000000 < 10000000) # True
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Learning Objectives ## Learning Objectives
   
- Call `input()` to accept and process string input - Call `input()` to accept and process string input
- Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()` - Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()`
- Concatenate values onto strings within a print function by converting to `str()` - Concatenate values onto strings within a print function by converting to `str()`
- Using correct vocabulary, explain a function call - Using correct vocabulary, explain a function call
- call/invoke, parameter, argument, keyword arguments, return value - call/invoke, parameter, argument, keyword arguments, return value
- Use `sep`, `end` keyword arguments with the print() function - Use `sep`, `end` keyword arguments with the print() function
- Yse some common built-in functions such as round(), abs() - Yse some common built-in functions such as round(), abs()
- import functions from a built-in module using `import`, `from` - import functions from a built-in module using `import`, `from`
- Call functions in modules using the attribute operator `.` - Call functions in modules using the attribute operator `.`
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
<div> <div>
<img src="attachment:Function_example.png" width="800"/> <img src="attachment:Function_example.png" width="800"/>
</div> </div>
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Vocabulary ## Vocabulary
   
- **function definition**: a grouping of lines of code; a way for us to tell our program to run that entire group of code - **function definition**: a grouping of lines of code; a way for us to tell our program to run that entire group of code
- **call / invoke**: a statement in Python code that instructs the program to run all the lines of code in a function definition, and then come back afterward - **call / invoke**: a statement in Python code that instructs the program to run all the lines of code in a function definition, and then come back afterward
- **parameter**: variable that receives input to function - **parameter**: variable that receives input to function
- **argument**: value sent to a function (lines up with parameter) - **argument**: value sent to a function (lines up with parameter)
- **keyword argument**: argument explicitly tied to a parameter - **keyword argument**: argument explicitly tied to a parameter
- **return value**: function output sent back to calling code - **return value**: function output sent back to calling code
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Calling / invoking a function ## Calling / invoking a function
   
- Syntax: `function_name(argument1, argument2, ...)` - Syntax: `function_name(argument1, argument2, ...)`
- ALWAYS: - ALWAYS:
- function’s name - function’s name
- followed by parenthesis (even if you have 0 arguments) - followed by parenthesis (even if you have 0 arguments)
- SOMETIMES: - SOMETIMES:
- one or more arguments: each argument is separated by a comma `,` - one or more arguments: each argument is separated by a comma `,`
- return value (result) - return value (result)
- Examples: - Examples:
- `print("Hello, world!")` - `print("Hello, world!")`
- `type(222 - 2)` - `type(222 - 2)`
- `len("Friday")` - `len("Friday")`
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Recall print(...), type(...) functions ## Recall print(...), type(...) functions
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print("hello\nworld") print("hello\nworld")
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
type(1) type(1)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
You could either display the return value of a function into an output box or capture it into a variable. You could either display the return value of a function into an output box or capture it into a variable.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
t = type(1 == 1.0) t = type(1 == 1.0)
print(t) print(t)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
One function's return value can become another function's argument directly. One function's return value can become another function's argument directly.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(type(1 == 1.0)) print(type(1 == 1.0))
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## input() ## input()
- accepts user input - accepts user input
- argument to input() function is a prompt - argument to input() function is a prompt
- prompt provides meaningful information to the user - prompt provides meaningful information to the user
- return value of input() function is always of type str - return value of input() function is always of type str
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 1: Accept user input for name and say hello. Example 1: Accept user input for name and say hello.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
#TODO: call input function and capture the return value into a variable called "name" #TODO: call input function and capture the return value into a variable called "name"
   
#TODO: print type of the variable name #TODO: print type of the variable name
   
print("Hello " + name + "!") print("Hello " + name + "!")
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 2a: Accept user input for age (incorrect version) Example 2a: Accept user input for age (incorrect version)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
age = input("Enter your age: ") age = input("Enter your age: ")
#TODO: print type of the variable age #TODO: print type of the variable age
   
# Let's celebrate a birthday :) # Let's celebrate a birthday :)
age ??? 1 # What is wrong? age ??? 1 # What is wrong?
print(age) print(age)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Type casting functions ## Type casting functions
- convert one type into another type - convert one type into another type
- int(), float(), str(), bool() - int(), float(), str(), bool()
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these int conversions # Let's try these int conversions
print(int(32.5)) print(int(32.5))
print(int("2012") + 10) print(int("2012") + 10)
# Some conversions don't make sense to us # Some conversions don't make sense to us
# So they won't make sense to Python either # So they won't make sense to Python either
print(int("nineteen")) print(int("nineteen"))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(int(32.5)) # this works print(int(32.5)) # this works
print(int(float("32.5"))) # this works print(int(float("32.5"))) # this works
   
# this doesn't work, less intuitive (tricky case!) # this doesn't work, less intuitive (tricky case!)
print(int("32.5")) print(int("32.5"))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these float conversions # Let's try these float conversions
print(float(26)) print(float(26))
print(float("3.14") * 2) print(float("3.14") * 2)
# Some conversions don't make sense to us # Some conversions don't make sense to us
# So they won't make sense to Python either # So they won't make sense to Python either
print(float("three point one")) print(float("three point one"))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try these str conversions # Let's try these str conversions
year = 2022 year = 2023
print("Next year will be: " + year+1) print("Next year will be: " + year+1)
print("It is good to be: " + str(True)) print("It is good to be: " + str(True))
print("Who wants a pi? " + str(3.14)) print("Who wants a pi? " + str(3.14))
#Pretty much you can convert anything to string in Python #Pretty much you can convert anything to string in Python
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 2b: Accept user input for age (correct version) Example 2b: Accept user input for age (correct version)
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
age = input("Enter your age: ") age = input("Enter your age: ")
#TODO: convert age to int type #TODO: convert age to int type
age = int(age) # Just saying int(age) won't work, you have to re-assign age variable age = int(age) # Just saying int(age) won't work, you have to re-assign age variable
# Let's celebrate a birthday :) # Let's celebrate a birthday :)
age += 1 age += 1
print(age) print(age)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Example 3: Accept user input for temperature Example 3: Accept user input for temperature
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# To enter their day care, kids have their temp checked # To enter their day care, kids have their temp checked
temp = float(input("Enter your temperature: ")) temp = float(input("Enter your temperature: "))
temp = float(temp) temp = float(temp)
#TODO: check that temp is less than equal to 98.6 #TODO: check that temp is less than equal to 98.6
temp_ok = temp <= 98.6 temp_ok = temp <= 98.6
#TODO: print type of temp_ok #TODO: print type of temp_ok
print(type(temp_ok)) print(type(temp_ok))
print("OK to enter: " + str(temp_ok)) print("OK to enter: " + str(temp_ok))
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# TODO: figure out how this works # TODO: figure out how this works
print("Somebody had a birthday: " + name + " " + str(age) + " years old :)") print("Somebody had a birthday: " + name + " " + str(age) + " years old :)")
# TODO: What error will you get when you take out str(...) around age? # TODO: What error will you get when you take out str(...) around age?
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
### parameters for print(...) function ### parameters for print(...) function
- can accept multiple arguments: - can accept multiple arguments:
- all arguments get printed on the same line - all arguments get printed on the same line
- `sep` allows you to configure separator between the arguments: - `sep` allows you to configure separator between the arguments:
- default value: space `" "` - default value: space `" "`
- `end` allows you to configure what character gets printed after - `end` allows you to configure what character gets printed after
- default value: newline `"\n"` - default value: newline `"\n"`
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Instead of using + (concatenation) operator, we could pass multiple arguments to print # Instead of using + (concatenation) operator, we could pass multiple arguments to print
print("hello" + " world") print("hello" + " world")
print("hello" + " cs220/cs319") print("hello" + " cs220/cs319")
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Self-practic: Guess what will get printed # Self-practic: Guess what will get printed
print("hello", "world", sep = "|", end = ";\n") print("hello", "world", sep = "|", end = ";\n")
print("hello", "world", sep = "^", end = "...\n") print("hello", "world", sep = "^", end = "...\n")
   
print("*" * 4, "#" * 6, sep = "||", end = "<END>") print("*" * 4, "#" * 6, sep = "||", end = "<END>")
print("*" * 6, "#" * 8, sep = "||", end = "<END>") print("*" * 6, "#" * 8, sep = "||", end = "<END>")
   
print("\n", end = "") print("\n", end = "")
   
print("*" * 4, "#" * 6, sep = "||", end = "<END>\n") print("*" * 4, "#" * 6, sep = "||", end = "<END>\n")
print("*" * 6, "#" * 8, sep = "||", end = "<END>\n") print("*" * 6, "#" * 8, sep = "||", end = "<END>\n")
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## More built-in functions ## More built-in functions
- print(), type(), int(), float(), str(), bool() are all examples of built-in functions - print(), type(), int(), float(), str(), bool() are all examples of built-in functions
- built-in functions are functions you can use readily (without importing anything) - built-in functions are functions you can use readily (without importing anything)
- you definitely don't have to know all the built-in functions, but here is the list: https://docs.python.org/3/library/functions.html - you definitely don't have to know all the built-in functions, but here is the list: https://docs.python.org/3/library/functions.html
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
abs function abs function
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Guess what will get printed # Guess what will get printed
print(abs(-10)) print(abs(-10))
print(abs(10)) print(abs(10))
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
round function round function
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Guess what will get printed # Guess what will get printed
print(round(10.525252, 4)) print(round(10.525252, 4))
print(round(5.2953, 2)) print(round(5.2953, 2))
print(round(5.2423, 2)) print(round(5.2423, 2))
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
## Modules ## Modules
- collection of similar functions and variables - collection of similar functions and variables
- requires import - requires import
- `import`, `from` keywords - `import`, `from` keywords
- 2 styles of import: - 2 styles of import:
1. `import` module_name: 1. `import` module_name:
- need to specify module_name`.`function_name to call it. - need to specify module_name`.`function_name to call it.
- `.` is called attribute operator. - `.` is called attribute operator.
2. `from` module_name `import` function_name 2. `from` module_name `import` function_name
- can call the function without specifying module name - can call the function without specifying module name
- `help` module_name: - `help` module_name:
- documentation for all functions and variables inside a module - documentation for all functions and variables inside a module
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's try to find square root of 10 # Let's try to find square root of 10
sqrt(10) # doesn't work because it is part of math module sqrt(10) # doesn't work because it is part of math module
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
It is a good practice to include all your import statements at the top of your notebook file. We will make exception just for a couple of lectures. It is a good practice to include all your import statements at the top of your notebook file. We will make exception just for a couple of lectures.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
import math import math
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.sqrt(10) math.sqrt(10)
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.cos(3.14159) math.cos(3.14159)
``` ```
   
%% Cell type:markdown id: tags: %% Cell type:markdown id: tags:
   
Modules contain useful variables too. Modules contain useful variables too.
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
math.pi math.pi
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
# Let's get help # Let's get help
help(math) help(math)
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
from random import randint from random import randint
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(randint(1,10)) # correct invocation print(randint(1,10)) # correct invocation
``` ```
   
%% Cell type:code id: tags: %% Cell type:code id: tags:
   
``` python ``` python
print(random.randint(1,10)) # incorrect invocation print(random.randint(1,10)) # incorrect invocation
``` ```
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment