Python basics Flashcards
Syntax to import datetime from an external module
extra: & then set datetime to a current_time variable
from datetime import datetime
current_time = datetime.now()
What data type does random.choice() (from the module random) take as an argument? What does it return?
random.choice() takes a list as an argument.
It returns an number (from the list passed to it).
What does random.randint() take as arguments, and how many?
What does it return?
random.randint() takes two numbers as arguments.
It returns a random number between the two numbers passed as arguments.
Call a function from the random module to generate a random number between 1 and 100.
import random
random_number = random.randint(1, 100)
NB includes both limits.
What does random.sample(list, int) do?
e.g. here:
my_list = [“apple”, “kiwi”, “lime”]
random.sample(my_list, 2)
Takes a list (first argument) and number (second argument) and returns that number of random items from the list.
Returns 2 random items from the list my_list
Syntax to import a module library as an alias
import libraryname as localname
e.g. from matplotlib import pyplot as plt
Syntax to import a module library as an alias
import libraryname as alias_name
e.g. from matplotlib import pyplot as plt
Best practice place to keep all your imports?
At the top of your file, all together
Get unique elements from a list (below) using a set.
numbers = [1, 1, 1, 2, 3, 4]
numbers = [1, 1, 1, 2, 3, 4]
set(numbers)
Get unique elements from a list (below) using a for loop and returning a list.
numbers = [1, 1, 1, 2, 3, 4]
numbers = [1, 1, 1, 2, 3, 4]
def get_unique_numbers(numbers):
unique = [ ]
for number in numbers:
if number not in unique:
unique.append(number)
return unique
Get unique elements from a list (below) using a for loop and returning a list.
What method merges a given dictionary into an existing dictionary?
.update( )
Use .update() to merge a new dictionary into an existing one.
Is the original dictionary modified in-place or a new one created with this method?
existing_dict.update(new_dict)
The original dictionary is modified in place (so inside a function, you’d want to return the original dictionary after updating it, to output the merged dictionary).