Python For Kids (Part 30: Lists, Tuples, Dictionaries & Loops)

Python For Kids (Part 30: Lists, Tuples, Dictionaries & Loops)

For a complete table of contents of all the lessons please click below as it will give you a brief of each lesson in addition to the topics it will cover. https://github.com/mytechnotalent/Python-For-Kids

Today we are going to learn about the powerful data structures called lists and dictionaries in addition to looping logic.

Lists

Unlike variables which store only one piece of data a list can store many items or pieces of data that have a connection with each other.

Lists are often called arrays in other languages.

Imagine you wanted to store all of the letters of the alphabet. If you had individual variables you would have to make 26 different variables. With a list you can use one variable and store an array or collection of each of the letters.

Let's look at an example of a list.

chocolates = ['caramel', 'dark', 'milk']

print(chocolates)
print(chocolates[0])
print(chocolates[1])
print(chocolates[-1])
print(chocolates[-2])
print(chocolates[:])
print(chocolates[:-1])
print(chocolates[1:])

chocolates.append('sweet')

print(chocolates)

chocolates.remove('milk')

print(chocolates)


['caramel', 'dark', 'milk']
caramel
dark
milk
dark
['caramel', 'dark', 'milk']
['caramel', 'dark']
['dark', 'milk']
['caramel', 'dark', 'milk', 'sweet']
['caramel', 'dark', 'sweet']

Wow! WOOHOO! Look at all that chocolate! Let's break down exactly what is happening.

We first create list of chocolates and have 3 elements in it. Unlike strings, lists are mutable or changeable so we can keep on adding chocolate! How cool is that?

We then print the entire list of chocolates where it will print each chocolate on a separate line.

We then add a new chocolate, 'sweet', to the list.

We then print the updated list.

We then remove a chocolate, 'milk', from the list.

We then print the updated list.

Going forward we will work with what we call an Application Requirements document which is a written step of TODO items.

APP 1

Let's create our first app and call it 0003_rock_paper_scissors:

Let's create our Rock Paper Scissors Application Requirements document and call it 0003_rock_paper_scissors_ar:

Rock Paper Scissors Application Requirements
--------------------------------------------
1. Define the purpose of the application.
   a. Create a game where a computer randomly chooses a number between
      0 and two and we choose a selection of either rock, paper or
      scissors.  Based on the rules either the computer or the player
      will win.
2. Define the rules of the application.
   a. Rock wins against scissors.
   b. Scissors wins against paper.
   c. Paper wins against rock.
3. Define the logical steps of the application.
   a. Create a game_choices list and populate it with the 3 str choices. 
   b. Create a random number between 0 and 2 and assign that into a 
      computer_choice variable.
   c. Create player_choice variable and get an input from the player
      and cast to an int with a brief message.
   d. Create conditional logic to cast the int values into strings
      for both the computer and player.
   e. Display computer choice and player choice.
   f. Create conditional logic to select a winner based on rules
      and print winner.

Let's create our app based on the above criteria.

import random

game_choices = ['Rock', 'Paper', 'Scissors']

computer_choice = random.randint(0, 2)

player_choice = int(input('What do you choose?  Type 0 for Rock, 1 for Paper, 2 for Scissors. '))

if computer_choice == 0:
    computer_choice = 'Rock'
elif computer_choice == 1:
    computer_choice = 'Paper'
else:
    computer_choice = 'Scissors'  
if player_choice == 0:
    player_choice = 'Rock'
elif player_choice == 1:
    player_choice = 'Paper'
else:
    player_choice = 'Scissors'

print('Computer chose {0} and player chose {1}.'.format(computer_choice, player_choice))

if computer_choice == 'Rock' and player_choice == 'Scissors':
  print('Computer - {0}'.format(game_choices[0]))
  print('Player - {0}'.format(game_choices[2]))
  print('Computer Wins!')
elif computer_choice == 'Scissors' and player_choice == 'Rock':
  print('Computer - {0}'.format(game_choices[2]))
  print('Player - {0}'.format(game_choices[0]))
  print('Player Wins!')
elif computer_choice == 'Scissors' and player_choice == 'Paper':
  print('Computer - {0}'.format(game_choices[2]))
  print('Player - {0}'.format(game_choices[1]))
  print('Computer Wins!')
elif computer_choice == 'Paper' and player_choice == 'Scissors':
  print('Computer - {0}'.format(game_choices[1]))
  print('Player - {0}'.format(game_choices[2]))
  print('Player Wins!')
elif computer_choice == 'Paper' and player_choice == 'Rock':
  print('Computer - {0}'.format(game_choices[1]))
  print('Player - {0}'.format(game_choices[0]))
  print('Computer Wins!')
elif computer_choice == 'Rock' and player_choice == 'Paper':
  print('Computer - {0}'.format(game_choices[0]))
  print('Player - {0}'.format(game_choices[1]))
  print('Player Wins!')
else:
  if computer_choice == 'Rock':
    print('Computer - {0}'.format(game_choices[0]))
    print('Player - {0}'.format(game_choices[0]))
  elif computer_choice == 'Paper':
    print('Computer - {0}'.format(game_choices[1]))
    print('Player - {0}'.format(game_choices[1]))
  else:
    print('Computer - {0}'.format(game_choices[2]))
    print('Player - {0}'.format(game_choices[2]))
  print('Draw!')

Woah! That is a lot of code! No worry! We are Pythonista's now and we shall be victorious!

We start by creating a list of three str items.

We then pick a random number between 0 and 2 and assign to the computer.

We prompt the player for a number between 0 and 2 representing the choices.

We then create conditional logic (ONE OF OUR PYTHON SUPERPOWERS) to convert all computer numbers into str logic.

We then print the results.

We then create more conditional logic to figure out and decide a winner.

Tuples

A Python tuple is just like a list but it is immutable. You would use this if you wanted to create a list of constants that you do not want to change.

RED = (255, 0, 0)

The elements such as RED[0] will be 255 but you can't reassign it.

Dictionaries

A Python dictionary is what we refer to as a key/value pair.

During one of the most amazing events I ever took part of was called the micro:bit LIVE 2020 Virtual to which I presented an educational app called the Study Buddy. The Study Buddy gave birth to the concept of an Electronic Educational Engagement Tool designed to help students learn a new classroom subject with the assistance of a micro:bit TED (Talking Educational Database) and a micro:bit TEQ (Talking Educational Quiz).

Below is a video showing the POWER of such an amazing tool!

This concept would have never been possible without a Python dictionary!

We started out with a simple key/value pair called a generic_ted or Talking Educational Database like the following.

generic_ted = {
                'your name': 'My name is Mr. George.',
                'food': 'I like pizza.',
              }

We have a str key called 'your name' and a str value of 'My name is Mr. George.', which we can retrieve a value by doing the following by adding to the code above.

print(generic_ted['your name'])

My name is Mr. George.

Dictionaries are also mutable which means you can add to them! Let's add to the code above.

generic_ted['drink'] = 'Milkshake'

print(generic_ted)

{'your name': 'My name is Mr. George.', 'drink': 'Milkshake', 'food': 'I like pizza.'}

We see the structure come back as a list of key/value pairs. This is an unordered datatype however we see above how we can get the value of a particular key and we see how to create a new value as well.

We can also nest lists inside of a dictionary as well. Let's add to the code above.

generic_ted['interests'] = ['Python', 'Hiking']

print(generic_ted)

{'your name': 'My name is Mr. George.', 'drink': 'Milkshake', 'interests': ['Python', 'Hiking'], 'food': 'I like pizza.'}

You can see that we do have a list as a value in the interests key.

We can also remove an item from a dictionary. Let's add to the code above.

generic_ted.pop('drink')

print(generic_ted)

{'your name': 'My name is Mr. George.', 'interests': ['Python', 'Hiking'], 'food': 'I like pizza.'}

We see that the 'drink' key and 'Milkshake' value is now removed from our dictionary.

One thing to remember about dictionaries is that the key MUST be unique in a given dictionary.

APP 2

Let's create our second app and call it 0004_journal:

Let's create our Journal Application Requirements document and call it 0004_journal_ar:

Journal Application Requirements
--------------------------------
1. Define the purpose of the application.
   a. Create a Journal application where we have a starting dictionary of
      entries and create the ability to add new ones.
2. Define the logical steps of the application.
   a. Create a journal dictionary and populate it with some starting values.
   b. Create a new empty dictionary called new_journal_entry.
   c. Create a new entry and date in the new_journal_entry.
   d. Append the new_journal_entry dictionary into the journal dictionary.
   e. Print the new results of the appended journal dictionary.

Let's create our app based on the above criteria.

journal = [
    {
        'entry': 'Today I started an amazing new journey with Python!',
        'date': '12/15/20',
    },
    {
        'entry': 'Today I created my first app!',
        'date': '12/16/20',
    }
]

new_journal_entry = {}

new_journal_entry['entry'] = 'Today I created my first dictionary!'
new_journal_entry['date'] = '01/15/21'
journal.append(new_journal_entry)

print(journal)


[{'date': '12/15/20', 'entry': 'Today I started an amazing new journey with  Python!'}, {'date': '12/16/20', 'entry': 'Today I created my first app!'}, {'date': '01/15/21', 'entry': 'Today I created my first dictionary!'}]

Very cool! Let's break this down.

We first create a journal dictionary and populate it.

We then create a new_journal_entry dictionary which is an empty dictionary.

We then add values into the new_journal_entry.

We then append the new_journal_entry dictionary into the journal dictionary.

We then print the new appended journal dictionary.

Loops

This is so much fun! Now it is time to REALLY jazz up our applications! In Python we have a for loop which allows us to iterate over a list of items and then do something with each item and we also have the ability to take a variable and iterate over it with a range of numbers and finally we have the while loop which allows us to do something while a condition is true.

Woah that is a lot to process! No worries! We will take it step-by-step!

Let us start with a for loop that allows us to iterate over an item and then do something with each iteration. Let's go back to our YUMMY chocolates!

chocolates = ['caramel', 'dark', 'milk']

for chocolate in chocolates:
    print(chocolate)


caramel
dark
milk

WOW! WOOHOO! We do not have to use three print lines anymore only one! WOOHOO! Does a dance! LOL!

We can begin to see the POWER of such a concept as we could add other things to do for each chocolate as well!

chocolates = ['caramel', 'dark', 'milk']

for chocolate in chocolates:
    print(chocolate)
    print('I am eating {0} chocolate!  YUMMY!'.format(chocolate))


caramel
I am eating caramel chocolate!  YUMMY!
dark
I am eating dark chocolate!  YUMMY!
milk
I am eating milk chocolate!  YUMMY!

We can see that we printed the individual chocolate iteration and then we ate it! YAY!

We also have the ability to take a variable and iterate over it with a range of numbers.

for number in range(1, 5):
  print(number)

print()

for number in range(3, 9, 3):
  print(number)


1
2
3
4

3
6

Here we printed an int number variable and started from 1 and went up to but NOT including the last number 5. We printed 1234 as shown.

We can also start at another number 3 and go up to but NOT include 9 so 3 to 8 and print every 3rd number which would be 3 and 6.

We also have the while loop which allows us to do a series of things while something is true.

has_chocolate = True

while has_chocolate:
    print('I have chocolate!')
    print('Yay I just ate it!')
    print('So yummy!')
    has_chocolate = False
    
print('Oh no I ate all my chocolate! :(')


I have chocolate!
Yay I just ate it!
So yummy!
Oh no I ate all my chocolate! :(

We can see that we start with a boolean flag called has_chocolate which is True.

We then enter the while loop because and ONLY because has_chocolate is True.

We then print a line, print another line and print another line and then set the flag False causing the while loop to break.

This won't make a good deal of sense yet until we start to get into functions where we can really see the power of such a loop!

APP 3

Let's create our third app and call it 0005_high_score:

Let's create our High Score Application Requirements document and call it 0005_high_score_ar:

High Score Application Requirements
-----------------------------------
1. Define the purpose of the application.
   a. Create a High Score application where you enter in a list of scores and use
      a for loop to find the highest score
2. Define the logical steps of the application.
   a. Create a str scores variable and input getting a list of numbers 
      separated by a space and when the user presses enter it will
      split each number based on the space into a scores list.
   b. Cast the entire list from a str list into an int list using a for 
      loop.
   c. Print the new int list.
   d. Create a highest_score variable and init to 0.
   e. Create a for loop where we iterate over each score and create a
      conditional to check if each score is greater than the hightest
      score and if it is then take that score value and assign it
      to the highest_score variable and keep iterating.  If we find
      another score that is bigger than the highest_score than 
      assign that new score to highest_score.
   f. Print highest_score var.

Let's create our app based on the above criteria.

# We need to make sure we are entering in a str to avoid a
# TypeError: can't convert list to int
scores = input('Input each score separated by a space: ').split()

# Convert str list into an int list
for n in range(0, len(scores)):
  scores[n] = int(scores[n])

print(scores)

highest_score = 0

for score in scores:
  if score > highest_score:
    highest_score = score

print('The highest score is {0}!'.format(highest_score))


Input each score separated by a space: 1 5 2 8 3 1
[1, 5, 2, 8, 3, 1]
The highest score is 8!

Today we really learned a lot!

Take the time and type out each of these examples and apps and modify them so you really have a good understanding of how this works. This is where the real learning starts!

In our next lesson we will learn about Python Functions!

要查看或添加评论,请登录

社区洞察

其他会员也浏览了