There are several reasons floats are not exactly accurate
Python approximates 0.1 as around 0.10000000000000000555, 0.2 as 0.2000000000000000111, and 0.3 as 0.29999999999999998889
format(0.1, ".20f" )
'0.10000000000000000555'
Suggestions on how to solve the 0.1 + 0.2 == 0.3 problem?
Python type conversion functions
Math follows “standard” rules (only returns int, if both parameters are int, except division, which always returns a float )
conversion methods try to turn their input into the given type
int(x)float(x)str(x)
Error is thrown if conversion is not possible
Python Expressions
An expression in programming language is a piece of code that describes/computes a value
Types of expressions:
literals (5, 2.45, “apple”, True)
variables
function calls
mathematical expressions
boolean expressions
(lots of other expressions through operator overloading)
Python math expressions
Python follows the same math syntax and rules as most other programming languages
Exceptions:
Two division operations:
/ (always float value)
// (always round down)
** performs exponentiation
Python Script
Let’s switch to Visual Studio code and run Python scripts
Statements (vs expressions)
Expressions represent values or the computation of values
Statements represent executable steps in a program
Statements often include expressions
Here’s a statement that invokes the print function with the expression 3 + 4 as an argument.
print(3+4)
7
Documentation
Three ways to document your code:
Use good variable names - python prefers snake_case naming
in-line comments #
Docstrings - strings included as first lines of programs or functions
Python function
Use def function_name(parameter) to define a function. Notice the indentation
def double(n):""" returns double of n """ result = n *2return result
whitespace denotes code blocks
don’t miss the colon which marks the beginning of a block
Call the function:
print(double(5))
10
What happens if there’s no return statement?
Blocks of code in python
Code block – A casual term for a series of lines of code, often introduced in if statements, loops, and functions
In Python whitespace characters must match exactly - careful with spaces and tabs.
Example
def is_divisible(x, n):"""Returns True if x is divisible by n"""return (x % n) ==0def is_even(x):""" Returns True if x is even """return is_divisible(x, 2)if__name__=="__main__":assert is_even(4) ==True
Exercise
Write a python function called circle_area, that calculate the area of a circle given a radius parameter (it returns the circle area).