DS4UX (Spring 2016)/Day 3 follow up

Here are some important concepts that we didn't have a chance to go into in great detail last week. You can use the sections below to review the concepts individually. You can also review how they work together in, which is included in the week 4 lecture files.

Return random values with the module
Use  to select items at random from a list.

>>> import random >>> my_list = ["terry j.","john","parrot","michael","terry g.", "graham", "llama"] >>> random.choice(my_list) 'graham' >>> random.choice(my_list) 'terry j.' >>>

Use  to gather a given number of random items from a list. The first argument you pass to the  function is the set of items you are sampling from. The second argument is the number of items you want to gather from that set.

>>> random.sample(my_list,3) ['terry j.', 'llama', 'michael']

Use  to gather a random number from a list of numbers. You specify the list of sequential numbers by passing the starting number as the first argument, and the final number as the last argument. Unlike with  function discussed below, when you use   both the first and last numbers you specify are included in the set you are sampling from.

>>> random.randint(1,10) 8 >>> random.randint(1,10) 3 >>> random.randint(1,10) 10 >>>

Generating a list of numbers easily with
>>> range(5) [0, 1, 2, 3, 4] >>> for i in range(5): ...    print("Hi" * i) ...

Hi HiHi HiHiHi HiHiHiHi

The  function returns a list of numbers. This is handy for when you want to generate a list of numbers on the fly instead of creating the list yourself.

>>> range(5) [0, 1, 2, 3, 4]

Use  when you want to loop over a bunch of numbers in a list, or perform an operation a certain number of times:

>>> numbers = range(5) >>> for number in numbers: ...    print(number * number) ... 0 1 4 9 16

We could rewrite the above example like this:

>>> for number in range(5): ...    print(number * number) ... 0 1 4 9 16

You can also set the start, end, and increment value (called "step") for a range. >>> for i in range(2,20,2): ...        print(i) 2 4 6 8 10 12 14 16 18

Get user input with
>>> for i in range(100): ...    my_input = input("Please type something> ") ...    if my_input == "Quit": ...        print("Goodbye!") ...        break ...    else: ...        print("You said: " + my_input) ... Please type something> Hello You said: Hello Please type something> How are you? You said: How are you? Please type something> Quit Goodbye! >>>

Things to remember about
 * Input simply asks the user to type something.
 * You can test out input interactively. Just go into the python interpreter and type: input("What's your favorite color?")
 * The stuff that goes inside the parentheses is the "prompt". It's a string, and should be surrounded by quotes. When you run your program, the prompt text will be shown to the user right to the left of the blinking cursor where they will type their input.
 * Python will ask the user to type something at the point in the script where input is called. Remember that Python executes scripts from top to bottom, left to right. If you put input inside a loop, it will ask the user to type something every time the loop is executed in your script.
 * What you DO with that user input is up to you. The best thing to do is to save it as a variable, i.e. user_name = input("Please type your name")
 * Python saves user input as a string, so if the user types "Daria" in the example above, then user_name will equal "Daria".
 * Once you've saved your user's input, you can use it like any other string variable. In the case of the babynames challenges, you probably want to compare it with the keys in one of the babynames dictionaries (ssadata.boys or ssadata.girls), so that you can find out how many people share that name. These keys are also strings.
 * REMEMBER: the keys in the babynames dictionaries are all in lowercase, but you can't necessarily control how a user will type their input--it's natural that people will want to capitalize their own name! Fortunately, there are string methods (https://docs.python.org/3/library/stdtypes.html#string-methods (Links to an external site.)) that will convert any string into all lowercase. You can make a string lowercase by adding .lower to the end of the string (or the variable that holds the string)!

Iterating an indeterminate number of times with loops
Use  loops when you don't know how many times you want to repeat ("iterate") an operation.

grocery_list = [] testAnswer = input('Press y if you want to enter more groceries: ') while testAnswer == 'y': food = input('Next item:') grocery_list.append(food) testAnswer = input('Press y if you want to enter more groceries: ')

print('Your grocery list:') for food in grocery_list: print(food)

Most of the time, you will find that  loops are more common for the kind of coding that you will be doing. For example, if you are reading through a CSV file, a  loop makes perfect sense: there are a set number of lines in the file, and you want to loop through the file line by line until you reach the end of the file. However, whenever your code is accepting input from a person or an API, you may find that you don't know ahead of time how many times you will need to perform an operation before stopping. In these cases, it's useful to know how to keep looping until a particular condition is met, and then stop.

Splicing list items together with
Use  when you have a list of string items that you want to join together into a single string. You specify the DELIMITER (the thing you want to separate the items) in quotes first, then call the  function by appending a dot (".") followed by the word join and—inside the parentheses—the list that you want to join together.

>>> print("The members of Monty Python are: %s" % (", ".join(my_list))) The members of Monty Python are: terry j., john, parrot, michael, terry g., graham, llama, eric