User Tools

Site Tools


basics_iii

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.

Advanced

Here is a “final” version which includes try and except error handling as well as easier logic.

import random

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
random.shuffle(list)

score = 0

while list != sorted(list):
    score = score + 1
    print(list)
    print("score:", score)

    x = input("Switch two numbers (x): ")
    y = input("Switch two numbers (y): ")

    try:
        x = int(x) - 1
        y = int(y) - 1
    except:
        print("")
        print("Oops! Please only enter numbers! :)")
        score = score - 1
        continue

    (list[x], list[y]) = (list[y], list[x])

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

print(list)
print("you win!")
print("Your score is", score, "points.")

basics_iii.txt · Last modified: 2023/10/13 11:48 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki