lists
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
lists [2023/10/27 02:18] – created appledog | lists [2024/07/29 00:08] (current) – appledog | ||
---|---|---|---|
Line 1: | Line 1: | ||
= Lists | = Lists | ||
+ | Note: This course can be skipped for older kids or people with prior experience. They can go to pyhang from here. They just need to know what a list is and what the difference is between a list and a string, and they can do pyhang (in general). | ||
+ | |||
If you didn't know what a //Class// is in Python, you should know by the end of this lesson series. That is because this lesson series dives deep into what a list is, and we will also explore trees! We're not going to specifically focus on //' | If you didn't know what a //Class// is in Python, you should know by the end of this lesson series. That is because this lesson series dives deep into what a list is, and we will also explore trees! We're not going to specifically focus on //' | ||
Line 73: | Line 75: | ||
< | < | ||
+ | def random_fruit(): | ||
+ | fruit_list = [ | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ] | ||
+ | |||
+ | count = len(fruit_list) | ||
+ | n = random.choice(range(count)) | ||
+ | return fruit_list[n] | ||
+ | </ | ||
+ | |||
+ | At this point, a simple program can print random fruits: | ||
+ | < | ||
+ | f = random_fruit() | ||
+ | print(f) | ||
+ | </ | ||
+ | |||
+ | It's finally time to write the actual program! We will create a list of random fruits, and print it! | ||
+ | |||
+ | < | ||
+ | import random | ||
+ | |||
+ | def main(): | ||
+ | num = 5 | ||
+ | list = [] | ||
+ | |||
+ | while len(list) < num: | ||
+ | f = random_fruit() | ||
+ | list.append(f) | ||
+ | |||
+ | print(list) | ||
+ | | ||
+ | ##### | ||
+ | |||
+ | def random_fruit(): | ||
+ | fruit_list = [ | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | " | ||
+ | ] | ||
+ | |||
+ | count = len(fruit_list) | ||
+ | n = random.choice(range(count)) | ||
+ | return fruit_list[n] | ||
+ | |||
+ | ##### | ||
+ | |||
+ | if __name__ == ' | ||
+ | main() | ||
+ | </ | ||
+ | |||
+ | == Homework | ||
+ | Now you can build a function that pairs students into groups. There basic idea is the same, but, make sure that the same student is not added to a group using the check "if name not in list:" | ||
+ | |||
+ | < | ||
+ | n = random.choice(len(students)) | ||
+ | s = students.pop(n) | ||
+ | group.append(s) | ||
+ | </ | ||
+ | |||
+ | The code above moves the student out of the list called " | ||
+ | == Next | ||
+ | Next, we can look at [[Lists II]], however, you might also want to look at [[Basics III]] to see how lists are used in action! |
lists.1698373097.txt.gz · Last modified: 2023/10/27 02:18 by appledog