Lesson Notes
In the following line of Python, which is the data and which is the algorithm?
print(“Hello World”)
The data can always be replaced with a different data of the same type, and the algorithm should still produce a similar type of result
print("Hello")
print("Goodbye")
print("Hello", "Goodbye")
Algorithms don't change (if they are valid)
Data changes value, but not type
RULE #1
Separate things that change from things that stay the same
print(): takes any number of arguments separated by a comma
print(1,2,3,'a','b','c')
A function is an algorithm with a result
In Python, algorithms are encapsulated in functions, like print()
.
Functions MUST ALWAYS be followed by a parenthesis, even if they are empty
print()
print()
is a built-in function. You can use any of the built in functions anywhere in your program.
Data in Python is called an Object, and objects have a type and value.
Examples
You can determine an object’s type with the type()
command
print( type(1) )
print( type("Hello") )
Computers assign numbers to to each character on the keyboard
<return>
: 13How does the computer know the difference between the number 65 and the letter ‘A’
This is why we need types
What about ‘1’ and 1? notice the quotes
print( ord("A") ) # Every character maps to an number value
print( ord("1") ) # Even number characters
In Computer Science, we call "text” a string. A string is a list of characters (or you might say a 'string' of characters).
Strings in Python can be enclosed in:
Each character in the string has two indexes:
"Bruce's beard"
'We are the knights who say, "Ni!"'#using quotes inside quotes
We can add strings together using concatenation:
print("5"+"3") # concatenation
but types have specific operations they can perform:
print("5"-"3") #not defined for string type
You cannot subtract “2” - “2”
because that operation is not defined for the string type.
You can multiply strings with the *
:
print("="*5) # string multiplication
print("<"+"="*5+">") # string order of operations
Robert Frost
print("The woods are lovely, dark, and deep, But I have promises to keep, And miles to go before I sleep, And miles to go before I sleep")
How could Robert Frost have written less using Python?
print("The woods are lovely, dark, and deep, But I have promises to keep" + " And miles to go before I sleep "* 2)
int
: a whole number (including 0)
float
: a fractional number
+
, -
,
*
- multiplication
/
- always results in a floating point value, i.e. 0.0
**
- exponent, 22 = 2**2
//
- integer division, always returns an int, doesn't round, i.e 1
Division vs Integer Division
print(5/6)
print(4/4)
print(5//6)
print(4//4)
% - divide, but only care about remainder
print( 5 % 6)
print( 6 % 5)