Functions Flashcards
What is len()
Give example code
Checks for length
st = ‘Print every word in this sentence that has an even number of letters’
for word in st.split(): if len(word) %2 == 0: print(word + ' ')
What is the range() function?
Give example code
A range() function returns a sequence of numbers, instead of having to write out a long list yourself like: numlist = [1, 2, 3,4,5,6]
You can instead just do:
for x in range(6):
–print (x)
OUTPUT 0 1 2 3 etc...
What is the zip function?
Give example code
A zip function basically compresses two lists together
adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "pear"]
for item in zip(adj, fruits):
print(item)
print(‘\n’)
OUTPUT
(‘red’, ‘apple’)
(‘big’, ‘banana’)
(‘tasty’, ‘pear’)
What is a function in Python?
Give an example
A function is a group of related statements that performs a specific task you want.
Functions are objects in which we organise our code help and break a program into smaller chunks of reusable code.
Example:
def function_name(parameters): """docstring""" # The first statement in the body of a function is usually a string, which can be accessed with function_name.\_\_doc\_\_ statement(s)
What is the difference between a keyword and a function?
Give example code
Generally speaking, in any language,
A function is a set of instructions that are to be executed when the function is called.
A keyword has predefined meaning in the compiler.
To make things easier, simply assume, that a keyword is an instance of some function that is already defined in the compiler.
What is the return statement?
Give example
The return statement is used to exit a function and go back to the place from where it was called.
def absolute_value(num): """This function returns the absolute value of the entered number"""
if num >= 0: return num else: return -num
print(absolute_value(2))
print(absolute_value(-4))
OUTPUT
2
4
What does list() do?
Give example
returns a list:
# empty list print(list())
# vowel string vowel_string = 'aeiou' print(list(vowel_string))
# vowel tuple vowel_tuple = ('a', 'e', 'i', 'o', 'u') print(list(vowel_tuple))
# vowel list vowel_list = ['a', 'e', 'i', 'o', 'u'] print(list(vowel_list))
What does abs() do?
x = abs(3+5j)
What does sum() do?
numbers = [2.5, 3, 4, -5]
numbers_sum = sum(numbers, 10)
print(numbers_sum)
Whats the difference between sum() and abs()?
sum() can process strings while abs() can do complex numbers