4 + 4.5 + 0.375
8.875
1500 * 0.08875
133.125
995.50 * 0.08875
88.350625
def tax(subtotal):
return subtotal * 0.08875
def return(subtotal):
return subtotal * 0.08875
File "/tmp/ipykernel_3436/2480525607.py", line 1 def return(subtotal): ^ SyntaxError: invalid syntax
tax()
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_3436/1737278063.py in <module> ----> 1 tax() TypeError: tax() missing 1 required positional argument: 'subtotal'
tax(1500)
133.125
def tax(1500)
File "/tmp/ipykernel_3436/3862704308.py", line 1 def tax(1500) ^ SyntaxError: invalid syntax
def tax(1500):
return subtotal * 0.08875
File "/tmp/ipykernel_3436/3680281193.py", line 1 def tax(1500): ^ SyntaxError: invalid syntax
1500 + tax(1500)
1633.125
200 + 1500 + tax(1500)
1833.125
sum = 1500
sum = sum + sum * 0.08875 # Add the tax amount
sum
1633.125
def set_a():
a = 10
print('The value of a:', a)
set_a()
The value of a: 10
a = 20
print ('Initially, the value of a:', a)
set_a()
print('Finally, the value of a:', a)
Initially, the value of a: 20 The value of a: 10 Finally, the value of a: 20
def scoped(la, lala):
lalala = lala + lala - la
return lalala
first = 10
second = 11
third = 12
scoped(2, 4)
first, second, third replaced by la, lala, lalala
first
10
second
11
third
12
l = [7, 4, 2, 6]
this is called an assignment | numbers in bracket assigned to variable named l
for num in l: print (num)
7 4 2 6
for num in l:
print(num)
7 4 2 6
NOTE: iteration template / pattern for iteration is
for in :
___
for num in l:
print(num * 2)
14 8 4 12
def mean(sequence):
for element in sequence:
total = total + element
return total / len(sequence)
NOTE: remove the indent to one level to enter the last line / represents one code block ending
temperature - 80
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_3436/3334237015.py in <module> ----> 1 temperature - 80 NameError: name 'temperature' is not defined
def mean(sequence):
total = 0
for element in sequence:
total = total + element
return total / len(sequence)
total = 0 means initializing the variable total / assigns the value 0 to total
short = [5, 5, 5, 5]
mean(short)
5.0
x = 5
type(x)
int
type(5)
int
x = 'hello world'
type(x)
str
str means string / sequence of characters AKA "hello world"
type(x)
str
Q: how to directly check the value of a string?
concatenation = the operation of putting two strings together by using +
'hello' + 'world'
'helloworld'
'knock' + 'knock'
'knockknock'
a = 'hello'
b = 'world'
a + b
'helloworld'
len('hello world')
11
len([1, 2, 3])
3
works for both strings and lists
- strings = returns how many characters are in the string
- lists = returns how many elements the list has
len(['hello', 'world'])
Q: what does the in the bracket on the left mean?*
NOTE:
- not everything has a length
- not everything can be added together
len(5)
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_3436/4108502181.py in <module> ----> 1 len(5) TypeError: object of type 'int' has no len()
2 + 'hello'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_3436/2556979404.py in <module> ----> 1 2 + 'hello' TypeError: unsupported operand type(s) for +: 'int' and 'str'
NOTE:
- don't take the length of an integer
- don't add an integer to a string
len(str(5))
1
- tells Python to treat integers as strings
- tells us how many characters are in the string
str(2) + 'hello'
'2hello'
^ tells Python unit '2' should be concatenated to 'hello'
- casting = converting between types
- polymorphism = when a single arithmetic operator/function/method is able to work on different types of data (integers/strings/lists)
volume = [4.0, 2.0, 3.0, 5.5]
result = []
for element in volume:
result = result + [element * 2]
result
[8.0, 4.0, 6.0, 11.0]
^ this code takes a list of volume levels and doubles it
result = []
result
[]
^ the variable was assigned the value of an empty list
result = result + [4.0]
result
[4.0]
result = result + [2.0]
result
[4.0, 2.0]
^ the list is being built up AKA a list is being added/concatenated to the current result
result = []
result = result + 4.0
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_3436/440397681.py in <module> 1 result = [] ----> 2 result = result + 4.0 TypeError: can only concatenate list (not "float") to list
what went wrong:
- [] = empty list
- 4.0 = float (number with a decimal point)
avoid DRY = use double()
!
- ✓ bundled
- ✓ can be reused
- ✓ does iteration (via using a for loop)
- ✓ implements polymorphism | function can work on any element that can be multiplied by 2
- ✓ can double strings
- ✓ will work on sequences
double()
to double strings:¶words = ['hello', 'world']
double(words)
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_3436/2412218211.py in <module> ----> 1 double(words) NameError: name 'double' is not defined
Q: ^ how do I define 'double' again??
double()
can take the list as an argument:¶countdown = [3, 2, 1, 'contact']
double(countdown)
double('abstraction')
--------------------------------------------------------------------------- NameError Traceback (most recent call last) /tmp/ipykernel_3436/3286799117.py in <module> ----> 1 double('abstraction') NameError: name 'double' is not defined
2 + 2 == 4
True
Using = and == in Python:
- = for assignment (giving a variable a value)
- == to test if the left and right-hand sides are equal
2 + 2 == 3 + 1
True
2 + 2 == 2 + 1
False
NOTE: Boolean data type = value doesn't have quotation marks around it AKA
True
orFalse
NOTE: checking equality is most useful when there's at least one variable involved
greeting = 'hello'
(NOT A TEST): assigns a value to the variable "greeting" / nothing is returned
greeting == 'hello'
True
(A TEST): using the == operator
greeting == 'hi'
False
greeting == 'sawasdee'
False
greeting = '2'
greeting == '2'
True
greeting == 1 + 1
False
if
¶def secret(word):
if word == 'please':
return 'Yes!'
example of test for equality using ==
secret('hello')
secret('world')
secret('please')
'Yes!'
a conversation with Python
- "secret('please') returns the value
Yes!
to signal that the correct word was input- causes certain code to run ONLY if the condition is true
- example of the conditional statemet AKA
if
statement
secret('please')
'Yes!'
secret('Please')
Q: if nothing returned, does this mean I just redefined secret with another word? or does it mean that the incorrect word was input?
def yesno(word):
if word == 'yes':
return True
if word == 'no':
return False
yesno('haha')
yesno('no')
False
yesno('yes')
True
yesno('Yes')
if word == 'please':
return 'Yes!'
else:
return 'No.'
File "/tmp/ipykernel_3436/617998124.py", line 2 return 'Yes!' ^ SyntaxError: 'return' outside function
new keyword
else
= indicates indented code that should run otherwise (when the if condition doesn't hold)
secret()
to return True
or False
instead of two strings:¶def secret(word):
if word == 'please':
return True
else:
return False
this can be refactored
- refactor = revise code to make it easier for people to read/understand/modify/further develop while keeping the function of the code the same
- ex:
True
whenword
has the value'please'
andFalse
otherwise -> new version ofsecret()
=
def secret(word):
return (word == 'please')
return whether or not the value of
word
is the stringplease
(so we can return the result of that equality test)
don't ever allow your program to attempt to divide by zero
'hi' * 2
'hihi'
'hihi' / 2
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) /tmp/ipykernel_3436/3445710781.py in <module> ----> 1 'hihi' / 2 TypeError: unsupported operand type(s) for /: 'str' and 'int'
half()