User Tools

Site Tools


basics_iii

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
basics_iii [2023/10/13 04:29] – created appledogbasics_iii [2023/10/13 11:48] (current) appledog
Line 3: Line 3:
 In this class we will explore the idea of adding words to a list and then sorting them. 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'.+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: 
 + 
 +<Code:Python> 
 + 
 +list = [] 
 +n = 5 
 + 
 +while n > 0: 
 +    word = input("Please enter a word: ") 
 + 
 +    list.append(word) 
 +     
 +    print(list) 
 +    print("=========="
 +     
 +    n = n - 1 
 + 
 +</Code> 
 + 
 +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: 
 + 
 +<Code:Python> 
 +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!"
 +</Code> 
 + 
 +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. 
 + 
 +<Code:Python> 
 +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."
 + 
 +</Code>
basics_iii.1697171389.txt.gz · Last modified: 2023/10/13 04:29 by appledog

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki