Functions Flashcards
Sum all the elements of the following list:
a_list = [4444, 8897, 6340, 9896, 4835, 4324, 10, 6445,
661, 1246, 1000, 7429, 1376, 8121, 647, 1280,
3993, 4881, 9500, 6701, 1199, 6251, 4432, 37]
sum(a_list)
Write a function that returns the square of any number
def square(a_number): squared_number = a_number * a_number return squared_number
First line when writning a new function
def nameofthefunction(input):
Second step when writing a new function
squared_number = a_number * a_number
Third step when writing a funtion
return squared_number
Write a function that extracts any column from a dataset called apps_data.
def extract(index): column=[] for row in apps_data[1:]: value=row[index] column.append(value) return column
Write a frequency table function
def freq_table(column): frequency_table={} for value in column: if value in frequency_table: frequency_table[value]+=1 else: frequency_table[value]=1 return frequency_table
Loop through the apps_data data set (excluding the header).
for row in apps_data[1:]:
Write a function that obtains the mean of a column of a data set
def mean(data_set, index): column = extract(data_set, index) return find_sm(column) / find_length(column)
Write a function named max() that takes in a list but just returns the string “No max value returned”.
def max(a_list): return "No max value returned"
Write a function named max() that takes in a list but just returns the string “No max value returned”.
Use the max() function on the list a_list. Assign the result to a variable named max_val_test_0.
def max(a_list): return "No max value returned"
max_val_test_0=max(a_list)
Run the code del max to delete the max() function you wrote. This will allow you to use the built-in max() function again.
del max
Edit the open_dataset() function and add the name of iOS apps data set (‘AppleStore.csv’) as a default argument for the file_name parameter.
def open_dataset(file_name=”AppleStore.csv”):
Without passing in any argument, use the open_dataset() function to open the AppleStore.csv file. Assign the data set to a variable named apps_data.
def open_dataset(file_name=”AppleStore.csv”):
opened_file = open(file_name) from csv import reader read_file = reader(opened_file) data = list(read_file)
return data
apps_data=open_dataset()
By using the right parameters and arguments:
Round 3.43 to one decimal point. Assign the result to one_decimal.
Round 0.23321 to two decimal points. Assign the result to two_decimals.
Round 921.2225227 to five decimal points. Assign the result to five_decimals.
one_decimal=round(3.43, ndigits=1)
two_decimals=round(0.23321,2)
five_decimals=round(921.2225227,5)