User Tools

Site Tools


basics_iii

This is an old revision of the document!


Basics III: Arrays and Lists

In this class we will explore the idea of adding words to a list and then sorting them.

In part II we will turn this into a game where the student can pick a number to move a word to the top of the list and then when the list is sorted they can 'win'. Well, here is the first thing:


list = []
n = 5

while n > 0:
    word = input("Please enter a word: ")

    list.append(word)
    
    print(list)
    print("==========")
    
    n = n - 1

This will show them loops and how a list works.

Next we will sort the list before printing it; add “list.sort()” before you print it. Let the students play with this for a while.

The Game

This is probably the easiest thing to do:

import random

# Create a shuffled list
list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

while list == sorted(list):
    random.shuffle(list)

while list != sorted(list):
    print(list)
    print("Switch two numbers (x y): ", end = '')
    a = input()
    a = a.split()
    x = int(a[0]) - 1
    y = int(a[1]) - 1
    
    z = list[x]
    list[x] = list[y]
    list[y] = z

    print("==========")

print(list)
print("You win!")

For homework ask them to include a round counter, which keeps track of how many guesses they make.

basics_iii.1697177628.txt.gz · Last modified: 2023/10/13 06:13 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki