Kevin

Python Beginner Tutorial 8 - For loop, Lists, and Dictionaries

Recommended Posts

This tutorial covers an introduction of for loops, lists and dictionaries. The primary goal of this video is to tie up loose ends and introduce basic data structures so they can be used in future videos. This video also covers how to import existing code in your project to spread a program over multiple files for organization and code reuse purposes. After watching this video you should have a basic understanding of for loops, lists, and dictionaries. You should feel comfortable creating lists and dictionaries and appending new elements. You should also be able to loop over all of the items in a list or dictionary using a for loop. 

Note: This video is in a different format and all code was written before the video. The code used in the video is primarily in 'randomFun.py'. Changes were made to our 'calculator.py' (this is our renamed main.py from previous videos). Both files are attached here for you to reference while watching the video. 

Files:

randomFun.py

calculator.py

Code

Quote

import time
import random

# Import our calculator code
# For code in the same directory it is as simple as
# this! Note that I renamed our calculator to
# "calculator.py". Also note the line I added
# to conditionally call the main function
import calculator

# Loop A random number of times (Between 10 and 50)
loopMax = random.randint(10, 50)

# Print mathing
print("Request for " + str(loopMax) + " maths received... Beginning mathing sequence...")

# Define python list of operations
# This list represents the strings for the 4 calculator operations
# Create the list just with addition in it and then add to it
operations = ['+']  # Defines the list using brackets. Any empty list is defined as []
# Use the append function (A function that "comes with" a python list) to add to the list
operations.append('-')
operations.append('/')
operations.append('*')
operations.append('+')

# Print the number of operations that will be used.
# Use the len() function to get return the integer count
# of the number of items in the list.
print("Operation count " + str(len(operations)))
# Take a peek at what is in the list
print("Computer will maths using the following operations " + str(operations))

# This will print three (3) new lines. The print function itself
# prints one. \n is the "string" representation of a new line.
# Turns out that a "new line" is actually just a character...
# I know life changing.
print('\n\n')

# Loop from staring index 0 to loopMax - 1.
# This will loop loopMax number of times
# Index will be 0 to (loopMax - 1)
# Example: If loopMax = 10
# Index would get these values sequentially:
# 0,1,2,3,4,5,6,7,8,9.
# There are 10 numbers (ten iterations of the loop)
# but it is zero indexed so the last index is 9.
for index in range(loopMax):
    # Get our random numbers to operate on
    num1 = random.randint(-99, 99)
    num2 = random.randint(-99, 99)

    print("Mathing with " + str(num1) + " and " + str(num2))

    # Generate random sleep time between 0 and 1 seconds
    # sleepTime = random.randint(0, 1)
    sleepTime = 0  # Save time in the video (No Sleep)

    # Run every available operation using another for loop
    # In python it is easy top loop over lists two ways of
    # doing it are shown

    print("IN FOR LOOP:")
    """Loop using the "in" keyword"""
    # The in keyword in a for loop allows you to loop over
    # all of the items in a dictionary sequentially.
    # THIS IS CRAZY USEFUL! 95% of anything you do
    # will likely use this. This is the preferred way but
    # in some instances you will need to use the "index"
    # method below.
    for operation in operations:
        print('operation = ' + operation)
        calculator.runOperation(operation, num1, num2)
        print()  # Just make a new line

    print('\n')
    print("INDEX FOR LOOP")
    """Loop using an index counter"""
    # Is is shorthand for "index". We already used index above
    # Typically, nested indexes may be referenced as j,k,l but at
    # that point it is better to give them more descriptive names.
    for i in range(len(operations)):
        print('i = ' + str(i))
        # A variable that is a list can be addressed using []'s and the
        # index of the item you want to access.
        # Lists are ZERO (0) indexed so the first item in the list is
        # at position 0!
        print('operation = ' + operations[i])
        calculator.runOperation(operations[i], num1, num2)
        print()  # Just make a new line

    # Sleep for random time
    time.sleep(sleepTime)
    # Print new lines
    print('\n----------------------\n')

# Loop is over. All done!
print("Done mathing... Goodbye!")
time.sleep(2)  # Sleep for effect :)
# BUT WAIT! There's More!
print("BUT WAIT! There's more! I forgot dictionaries!")

# A dictionary is similar to a list. They are both collections
# of items but a dictionary has key and values (opposed to just
# values in a list). Think of a dictionary... well as a dictionary.
# You have some "key" (a word let's say) and you "lookup" that
# word in your handy-dandy dictionary to get the word's
# definition or "value". Sound familiar?
wordsAndThingsDict = {}   # Define an empty dictionary using curly braces

# Add some things to the dictionary
wordsAndThingsDict['Apple'] = 'Red thing that tastes good. Specifically not an orange.'
wordsAndThingsDict['Orange'] = 'Makes great juice!'
wordsAndThingsDict[3] = 'The number 3'
wordsAndThingsDict['A list'] = ['Oh', 'boy!', 'A list in a dictionary!']
wordsAndThingsDict['Inception'] = {'Nested': 'When one dictionary is a VALUE in a dictionary'}

# Print out our dictionary
print(str(wordsAndThingsDict))
print()

print("Loop")
# Loop over all keys in the dictionary
for key in wordsAndThingsDict:
    print("Key: " + str(key))  # Call str to be safe... There is a number 3 in there
    # Print the value by using the key to "look it up"
    print("Value: " + str(wordsAndThingsDict[key]))
    print()
Quote

def add(num1, num2):
    """Returns num1 plus num2."""
    return num1 + num2


def sub(num1, num2):
    """Returns num1 minus num2."""
    return num1 - num2


def mul(num1, num2):
    """Returns num1 times num2."""
    return num1 * num2


def div(num1, num2):
    """Returns num1 divided by num2."""
    try:
        return num1 / num2
    except ZeroDivisionError:
        print("Handled div by zero. Returning zero.")
        return 0


def runOperation(operation, num1, num2):
    """Determines the operation to run based on the 
    operation argument which should be passed in as an
    int"""
    # Determine operation
    if (operation == 1 or operation == '+'):
        print("Adding...")
        print(add(num1, num2))
    elif (operation == 2 or operation == '-'):
        print("Subtracting...")
        print(sub(num1, num2))
    elif (operation == 3 or operation == '*'):
        print("Multiplying...")
        print(mul(num1, num2))
    elif (operation == 4 or operation == '/'):
        print("Dividing...")
        print(div(num1, num2))
    else:
        print("I don't understand")


def main():
    """Allows user to run basic calculator operations with two numbers."""
    validInput = False
    while not validInput:
        # Get user input
        try:
            num1 = int(input("What is number 1?"))
            num2 = int(input("What is number 2?"))
            operation = int(input("What do you want to do? 1. add, 2. subtract, 3. multiply, or 4. divide."
                                  " Enter  number: "))
            validInput = True
        except ValueError:
            print("Invalid input. Try again.")
        except:
            print("Unknown error")
        runOperation(operation, num1, num2)

# This is a fancy line of code that will
# only run the main function if we directly execute this
# file. Think of the __name__ variable as an indicator
# assigned by python for the purpose of determining
# if the "main" function should be run. Adding this
# line will enable use to import our calculator
# "module" so we can reuse its functionality.
# If you do not totally understand why this
# works DO NOT WORRY. Just know what it does
# and WHY we are using it.
if __name__ == "__main__":
    main()

 

Share this post


Link to post
Share on other sites
4 hours ago, nitindagdi said:

Hi Kevin thanks for videos they already helpful. I am looking for next tutorial can you help me with that

I plan to have the next video published by the end of the day on Saturday. Once its published there will be a thread here. Also make sure to subscribe on YouTube!

Share this post


Link to post
Share on other sites
Hi,
I tried to program the game "rock,scissors,paper": 

The results were ok but one thing, the printer had two NONE that i didn't understand way they appeared.

image.png.3f6f61d3c5c0324c0e558a51bf6055e1.png



import random

def num_to_object(x):
    if x==1:
        print('Rock')
    elif x==2:
        print('Scissors')
    elif x==3 :
        print('Paper')


userplaying = True
while userplaying:
    user= int(input('Holla '
          'please choose 1.Rock, 2. Scissors 3.Paper:__'))
    computer=(random.randint(1,3))

    print(num_to_object(user))
    print(num_to_object(computer))

    if user==computer:
        print('even!!!!!!!!(-8')

    elif user==1 and computer==2 or user ==2 and computer==3 or user==3 and computer==1:
        print('user win !!!!!!!! (-:')
    else:
        print('computer win !!!!!!!  )-;')

    user_continue=input('Would you like to play again? y/n?')
    if user_continue=='y':
        userplaying=True
    else:
        break

Share this post


Link to post
Share on other sites

can anyone in here plz help to understand the reason that we created a variable named loopMax= random.randint (10,50) and latter on we created another random number that we assigned our num1 and num2,num1 = random.randint(-99, 99),num2 = random.randint(-99, 99) , so my question is what is the relationship btw the two different random numbers? is the computer going to execute both the random numbers or its going to run one of them?. thanks.

Share this post


Link to post
Share on other sites
On 3/24/2018 at 12:12 PM, boqore said:

can anyone in here plz help to understand the reason that we created a variable named loopMax= random.randint (10,50) and latter on we created another random number that we assigned our num1 and num2,num1 = random.randint(-99, 99),num2 = random.randint(-99, 99) , so my question is what is the relationship btw the two different random numbers? is the computer going to execute both the random numbers or its going to run one of them?. thanks.

Hi Boqore,

As far as I understand it the variable LoopMax is to determine the number of time the auto generated mathing process will run (the for loop) - set here to run between 10 and 50 times.

The later random number generation assigned to num1 and num2 is generating the input numbers to perform the math operation against. So in this case the random number range is -99 to 99. 

 

So if LoopMax == 2 (not possible with the selection as 10 is the lowest but to save my typing) you'd have:

1st loop:

64 (random num1) + (random math operation) 6 (random num2)

answer = 70

2nd loop:

3 (random num1) * (random math operation) 9 (random num2)

answer = 27

Loop Ends

 

Hope this is clear enough if not, maybe someone with a better understanding can give a better/simpler answer.

Share this post


Link to post
Share on other sites

Hey Kevin,

When I am running the "randomfun.py" program, it is giving me this error

Python path configuration:
  PYTHONHOME = (not set)
  PYTHONPATH = 'C:\Users\PARTH\PycharmProjects\Functions'
  program name = 'C:\Program Files (x86)\Python38-32\python.exe'
  isolated = 0
  environment = 1
  user site = 1
  import site = 1
  sys._base_executable = 'C:\\Program Files (x86)\\Python38-32\\python.exe'
  sys.base_prefix = 'C:\\Program Files (x86)\\Python38-32'
  sys.base_exec_prefix = 'C:\\Program Files (x86)\\Python38-32'
  sys.executable = 'C:\\Users\\PARTH\\Functions\\Scripts\\python.exe'
  sys.prefix = 'C:\\Program Files (x86)\\Python38-32'
  sys.exec_prefix = 'C:\\Program Files (x86)\\Python38-32'
  sys.path = [
    'C:\\Users\\PARTH\\PycharmProjects\\Functions',
    'C:\\Program Files (x86)\\Python38-32\\python38.zip',
    'C:\\Program Files (x86)\\Python38-32\\DLLs',
    'C:\\Program Files (x86)\\Python38-32\\lib',
    'C:\\Program Files (x86)\\Python38-32',
  ]
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
Traceback (most recent call last):
  File "C:\Program Files (x86)\Python38-32\lib\encodings\__init__.py", line 155, in <module>
AttributeError: module 'codecs' has no attribute 'register'

 

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...