Can you write this function in python?
$f(x) = 3x + 2$
def f(x):
return 3*x+2
Can you use the function to find:
$f(3)$
$f(10)$
$f(44)$
print(f(3))
print(f(10))
print(f(44))
11 32 134
# we define the function here
def greater_than_five(n):
if n > 5:
return True
print("n is greater than 5")
else:
return False
print("n is less than 5")
# we call the function here
greater_than_five(5)
False
def add_two_numbers(x,y):
return x+y
add_two_numbers(2,3)
def long_name(name):
if len(name) > 10:
return "Long name"
else:
return "Short name"
long_name('taylor')
File "<ipython-input-4-5104d300944b>", line 3 return "Long name" ^ IndentationError: expected an indented block
def concat_strings(string1, string2):
new_string = string1 + string2
return new_string
find_the_mistake_3('I eat pancakes ', 'for breakfast')
File "<ipython-input-8-0b69a3dc6eed>", line 3 return new_string SyntaxError: 'return' outside function
def print_all_in_list(x):
for x in x:
print(x)
print_all_in_list(['Harvard', 'MIT', 'Colombia', 'Duke', 'AAiT', 'KAIST'])
Harvard MIT Colombia Duke AAiT KAIST
def same_color(color_1, color_2):
if color_1 == color_2: return True
else: return False
print(same_color('red', 'red'))
print(same_color('blue', 'yellow'))
True False
Same:
def same_color_2(color_1, color_2):
if color_1 == color_2:
return True
else:
return False
print(same_color_2('red', 'red'))
print(same_color_2('blue', 'yellow'))
True False
# Now use a for loop with range
# While loop
list_of_lists = [[1 , 2, 3], [4, 5, 6], [7, 8, 9]]
# Same thing as:
list_of_lists = [[1 , 2, 3],
[4, 5, 6],
[7, 8, 9]]
# What does this return?
list_of_lists[1]
[11, 12, 13]
# What does this return?
list_of_lists[0]
[1, 2, 3]
# What does this return?
var = list_of_lists[0]
var[2]
3
# What does this return?
list_of_lists[0][2]
3
# Let's try a few more:
# Remember:
# list_of_lists = [[1 , 2, 3],
# [4, 5, 6],
# [7, 8, 9]]
list_of_lists[1][0]
list_of_lists[[2][-1]]
list_of_lists[-1][0]
list_of_lists[-1][-2]
for i in [1,2,3,4,5]:
for j in [1,2,3,4,5]:
print(i,j)
What will happen if we just print i
?
What will happen if we just print j
? What about len(i)
?
list_of_lists = [[1 , 2, 3],
[4, 5, 6],
[7, 8, 9]]
for lst in list_of_lists:
print(lst)
[1, 2, 3] [4, 5, 6] [7, 8, 9]
# Use a nested for loop!
for lst in list_of_lists:
for num in lst:
print(num)
1 2 3 4 5 6 7 8 9
list_of_strings = ['nested', 'loops', 'are', 'very', 'useful']
def print_letters(lst):
# Use a nested for loop!
pass