ACHIEVEMENTS

We help our clients integrate, analyze, and use their data to improve their business.

36

GREAT POST

300

HAPPY CLIENTS

650

COFFEES DRUNK

2000

PAGE VIEW

  • Facing Errors In Python- Part 4

    Working with exception arguments

    Most exceptions don’t provide arguments (a list of values that you can check for additional information). The exception either occurs or it doesn’t. However, a few exceptions do provide arguments, and you see them used later in the book. The arguments tell you more about the exception and provide details that you need to correct it.

    For the sake of completeness, this Post includes a simple example that generates an exception with an argument. You can safely skip the remainder of this section if desired because the information is covered in more detail later in the book.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    import sys

    try:

    File = open('myfile.txt') except IOError as e:
    print("Error opening file!\r\n" +
    "Error Number: {0}\r\n".format(e.errno) + "Error Text: {0}".format(e.strerror))
    else:
    print("File opened as expected.") File.close();

    This example uses some advanced features. The import statement obtains code from another file. Post 10 tells you how to use this Python feature.

    The open() function opens a file and provides access to the file through the File variable. Post 15 tells you how file access works. Given that myfile.txt doesn’t exist in the application directory, the operating system can’t open it and will tell Python that the file doesn’t exist.

    Trying to open a nonexistent file generates an IOError exception. This particular exception provides access to two arguments:

     errno: Provides the operating system error number as an integer

     strerror: Contains the error information as a human-readable string

    The as clause places the exception information into a variable, e, that you can access as needed for additional information. The except block contains a print() call that formats the error information into an easily read error message.

    If you should decide to create the myfile.txt file, the else clause executes. In this case, you see a message stating that the file opened normally. The code then closes the file without doing anything with it.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application displays the Error opening file information, as


    Obtaining a list of exception arguments

    The list of arguments supplied with exceptions varies by exception and by what the sender pro­ vides. It isn’t always easy to figure out what you can hope to obtain in the way of additional informa­ tion. One way to handle the problem is to simply print everything using code like this

    import sys

    try:

    File = open('myfile.txt') except IOError as e:

    for Arg in e.args: print(Arg)
    else:
    print("File opened as expected.") File.close();

    The args property always contains a list of the exception arguments in string format. You can use a simple for loop to print each of the arguments. The only problem with this approach is that you’re missing the argument names, so you know the output information (which is obvious in this case), but you don’t know what to call it.

    A more complex method of dealing with the issue is to print both the names and the contents of the arguments. The following code displays both the names and the values of each of the arguments

    import sys

    try:
    File = open('myfile.txt')

    except IOError as e: for Entry in dir(e):

    if (not Entry.startswith("_")): try:

    print(Entry, " = ", e.__getattribute__(Entry)) except AttributeError:
    print("Attribute ", Entry, " not accessible.")
    else:
    print("File opened as expected.") File.close();

    In this case, you begin by getting a listing of the attributes associated with the error argument object using the dir() function. The output of the dir() function is a list of strings containing the names of the attributes that you can print. Only those arguments that don’t start with an under­ score (_) contain useful information about the exception. However, even some of those entries are inaccessible, so you must encase the output code in a second try...except block

    The attribute name is easy because it’s contained in Entry. To obtain the value associated with that attribute, you must use the __getattribute__() function and supply the name of the attribute you want. When you run this code, you see both the name and the value of each of the attributes supplied with a particular error argument object. In this case, the actual output is as follows:

    args = (2, 'No such file or directory')
    Attribute  characters_written  not accessible.
    errno = 2
    filename = myfile.txt
    strerror =  No such file or directory
    winerror = None
    with_traceback  =  <built-in method with_traceback of
    FileNotFoundError object at 0x0000000003416DC8>
       

    Handling multiple exceptions with a single except clause


    Most applications can generate multiple exceptions for a single line of code. How you handle the multiple exceptions depends on your goals for the application, the types of exceptions, and the relative skill of your users. Sometimes when working with a less skilled user, it’s simply easier to say that the application experienced a nonrecoverable error and then log the details into a log file in the application directory or a central location.

    Using a single except clause to handle multiple exceptions works only when a common source of action fulfills the needs of all the exception types. Otherwise, you need to handle each exception individually. The following steps show how to handle multiple exceptions using a single except clause.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    try:

    Value = int(input("Type a number between 1 and 10: "))
    except (ValueError, KeyboardInterrupt):
    print("You must type a number between 1 and 10!") else:

    if (Value > 0) and (Value <= 10): print("You typed: ", Value)
    else:
    print("The value you typed is incorrect!")

    However, notice that the except clause now sports both a ValueError and a KeyboardInterrupt exception. In addition, these exceptions appear within parentheses and are separated by commas.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application asks you to type a number between 1 and 10.

     Type Hello and press Enter.

    The application displays an error message.

     Perform Steps 3 and 4 again, but type 22 instead of Hello.

    The application outputs the expected range error message.

     Perform Steps 3 and 4 again, but press Ctrl+C, Cmd+C, or the alterna-tive for your platform instead of typing anything.

    You see the error message that’s usually associated with error input.

     Perform Steps 3 and 4 again, but type 7 instead of Hello.

    This time, the application finally reports that you’ve provided a correct value of 7.

    Handling multiple exceptions with multiple except clauses

    When working with multiple exceptions, it’s usually a good idea to place each exception in its own except clause. This approach allows you to provide custom handling for each exception and makes it easier for the user to know precisely what went wrong. Of course, this approach is also a lot more work.

    The following steps demonstrate how to perform exception handling using multiple except clauses.

    Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    try:

    Value = int(input("Type a number between 1 and 10: "))
    except ValueError:
    print("You must type a number between 1 and 10!") except KeyboardInterrupt:
    print("You pressed Ctrl+C!") else:

    if (Value > 0) and (Value <= 10): print("You typed: ", Value)
    else:
    print("The value you typed is incorrect!")

    Notice the use of multiple except clauses in this case. Each except clause handles a different exception. You can use a combination of techniques, with some except clauses handling just one exception and other except clauses handling multiple exceptions. Python lets you use the approach that works best for the error-handling situation.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application asks you to type a number between 1 and 10.

     Type Hello and press Enter.

    The application displays an error message.

     Perform Steps 3 and 4 again, but type 22 instead of Hello.

    The application outputs the expected range error message.

     Perform Steps 3 and 4 again, but press Ctrl+C, Cmd+C, or the alterna-tive for your platform instead of typing anything.

    The application outputs a specific message that tells the user what went wrong,

     Perform Steps 3 and 4 again, but type 7 instead of Hello.

    This time, the application finally reports that you’ve provided a correct value of 7.



  • Facing Errors in Python - Part 3

    Basic exception handling

    To handle exceptions, you must tell Python that you want to do so and then provide code to perform the handling tasks. You have a number of ways in which you can perform this task. The following sections start with the simplest method first and then move on to more complex methods that offer added flexibility.


    Handling a single exception

    Some examples have a terrible habit of spitting out exceptions when the user inputs unexpected values. Part of the solution is to provide range checking. However, range checking doesn’t over-come the problem of a user typing text such as Hello in place of an expected numeric value. Exception handling provides a more complex solution to the problem, as described in the following steps.

    Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    try:

    Value = int(input("Type a number between 1 and 10: "))
    except ValueError:
    print("You must type a number between 1 and 10!") else:

    if (Value > 0) and (Value <= 10): print("You typed: ", Value)
    else:
    print("The value you typed is incorrect!")

    The code within the try block has its exceptions handled. In this case, handling the exception means getting input from the user using the int(input()) calls. If an exception occurs outside this block, the code doesn’t handle it. With reliability in mind, the temptation might be to enclose all the executable code in a try block so that every exception would be handled. However, you want to make your exception handling small and specific to make locating the problem easier.


    The except block looks for a specific exception in this case: ValueError. When the user creates a ValueError exception by typing Hello instead of a numeric value, this particular exception block is executed. If the

    user were to generate some other exception, this except block wouldn’t handle it.

    The else block contains all the code that is executed when the try block code is successful (doesn’t generate an exception). The remainder of the code is in this block because you don’t want to execute it unless the user does provide valid input. When the user provides a whole number as input, the code can then range check it to ensure that it’s correct.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application asks you to type a number between 1 and 10.

     Type Hello and press Enter.

    The application displays an error message.

    Typing the wrong input type generates an error instead of an exception.


     Perform Steps 3 and 4 again, but type 5.5 instead of Hello.

    The application generates the same error message,.

     Perform Steps 3 and 4 again, but type 22 instead of Hello.

    The application outputs the expected range error message,. Exception handling doesn’t weed out range errors. You must still check for them separately.


    Exception handling doesn’t ensure that the value is in the correct range.


     Perform Steps 3 and 4 again, but type 7 instead of Hello.

    This time, the application finally reports that you’ve provided a correct value of 7. Even though it seems like a lot of work to perform this level of checking, you can’t really be certain that your application is working correctly without it.

     Perform Steps 3 and 4 again, but press Ctrl+C, Cmd+C, or the alterna-tive for your platform instead of typing anything.

    The application generates a KeyboardInterrupt exception. Because this exception isn’t handled, it’s still a problem for the user. You see several techniques for fixing this problem later in the Post.

    Using the except clause without an exception

    You can create an exception handling block in Python that’s generic because it doesn’t look for a specific exception. In most cases, you want to provide a specific exception when performing exception handling for these reasons:

     To avoid hiding an exception you didn’t consider when designing the application

     To ensure that others know precisely which exceptions your application will handle

     To handle the exceptions correctly using specific code for that exception

    However, sometimes you may need a generic exception-handling capability, such as when you’re working with third-party libraries or interacting with an external service. The following steps demonstrate how to use an except clause without a specific exception attached to it.

    Open a Python File window.

    You see an editor in which you can type the example code.



     Type the following code into the window — pressing Enter after each line:

    try:
    Value = int(input("Type a number between 1 and 10: "))
    except:
    print("You must type a number between 1 and 10!") else:

    if (Value > 0) and (Value <= 10): print("You typed: ", Value)
    else:
    print("The value you typed is incorrect!")

    The only difference between this example and the previous example is that the except clause doesn’t have the ValueError exception specifi-cally associated with it. The result is that this except clause will also catch any other exception that occurs.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application asks you to type a number between 1 and 10.

     Type Hello and press Enter.

    The application displays an error message.

     Perform Steps 3 and 4 again, but type 5.5 instead of Hello.

    The application generates the same error message.

     Perform Steps 3 and 4 again, but type 22 instead of Hello.

    The application outputs the expected range error message. Exception handling doesn’t weed out range errors. You must still check for them separately.

     Perform Steps 3 and 4 again, but type 7 instead of Hello.

    This time, the application finally reports that you’ve provided a correct value of 7. Even though it seems like a lot of work to perform this level of checking, you can’t really be certain that your application is working correctly without it.

     Perform Steps 3 and 4 again, but press Ctrl+C, Cmd+C, or the alternative for your platform instead of typing anything.

    You see the error message that’s usually associated with input error. The error message is incorrect, which might con-fuse users. However, the plus side is that the application didn’t crash, which means that you won’t lose any data and the application can recover. Using generic exception handling does have some advantages, but you must use it carefully.


  • Facing Errors In Python - Part 2

    Distinguishing error types

    You can distinguish errors by type, that is, by how they’re made. Knowing the error types helps you understand where to look in an application for poten-tial problems. Exceptions work like many other things in life. For example, you know that electronic devices don’t work without power. So, when you try to turn your television on and it doesn’t do anything, you might look to ensure that the power cord is firmly seated in the socket.

    Understanding the error types helps you locate errors faster, earlier, and more consistently, resulting in fewer misdiagnoses. The best developers know that fixing errors while an application is in development is always easier than fixing it when the application is in production because users are inherently impa-tient and want errors fixed immediately and correctly. In addition, fixing an error earlier in the development cycle is always easier than fixing it when the application nears completion because less code exists to review.

    The trick is to know where to look. With this in mind, Python (and most other programming languages) breaks errors into the following types:


    •  Syntactical
    •  Semantic
    •  Logical


    The following sections examine each of these error types in more detail. I’ve arranged the sections in order of difficulty, starting with the easiest to find. A syntactical error is generally the easiest; a logical error is generally the hardest.


    Syntactical

    Whenever you make a typo of some sort, you create a syntactical error. Some Python syntactical errors are quite easy to find because the application simply doesn’t run. The interpreter may even point out the error for you by highlighting the errant code and displaying an error message. However, some syntactical errors are quite hard to find. Python is case sensitive, so you may use the wrong case for a variable in one place and find that the variable isn’t quite working as you thought it would. Finding the one place where you used the wrong capitalization can be quite challenging.


    Most syntactical errors occur at compile time and the interpreter points them out for you. Fixing the error is made easy because the interpreter generally tells you what to fix, and with considerable accuracy. Even when the interpreter doesn’t find the problem, syntactical errors prevent the application from running correctly, so any errors the interpreter doesn’t find show up during the testing phase. Few syntactical errors should make it into production as long as you perform adequate application testing.

    Semantic

    When you create a loop that executes one too many times, you don’t generally receive any sort of error information from the application. The application will happily run because it thinks that it’s doing everything correctly, but that one additional loop can cause all sorts of data errors. When you create an error of this sort in your code, it’s called a semantic error.

    Semantic errors occur because the meaning behind a series of steps used to perform a task is wrong — the result is incorrect even though the code apparently runs precisely as it should. Semantic errors are tough to find, and you sometimes need some sort of debugger to find them

    Logical

    Some developers don’t create a division between semantic and logical errors, but they are different. A semantic error occurs when the code is essentially correct but the implementation is wrong (such as having a loop execute once too often). Logical errors occur when the developer’s thinking is faulty. In many cases, this sort of error happens when the developer uses a relational or logical operator incorrectly. However, logical errors can happen in all sorts of other ways, too. For example, a developer might think that data is always stored on the local hard drive, which means that the application may behave in an unusual manner when it attempts to load data from a network drive instead.

    Logical errors are quite hard to fix because the problem isn’t with the actual code, yet the code itself is incorrectly defined. The thought process that went into creating the code is faulty; therefore, the developer who created the error is less likely to find it. Smart developers use a second pair of eyes to help spot logical errors. Having a formal application specification also helps because the logic behind the tasks the application performs is usually given a formal review.


    Catching Exceptions

    Generally speaking, a user should never see an exception dialog box. Your application should always catch the exception and handle it before the user sees it. Of course, the real world is different — users do see unexpected exceptions from time to time. However, catching every potential exception is still the goal when developing an application. The following sections describe how to catch exceptions and handle them.


    Understanding the built-in exceptions

    Python comes with a host of built-in exceptions — far more than you might think possible. You can see a list of these exceptions. The documentation breaks the exception list down into categories. Here is a brief overview of the Python exception categories that you work with regularly:

     Base classes: The base classes provide the essential building blocks (such as the Exception exception) for other excep­tions. However, you might actually see some of these exceptions, such as the ArithmeticError exception, when working with an application.

     Concrete exceptions: Applications can experience hard errors — errors that are hard to overcome because there really isn’t a good way to handle them or they signal an event that the application must handle. For example, when a system runs out of memory, Python generates a MemoryError exception. Recovering from this error is hard because it isn’t always possible to release memory from other uses. When the user presses an interrupt key (such as Ctrl+C or Delete), Python gener­ ates a KeyboardInterrupt exception. The application must handle this exception before proceeding with any other tasks.

     OS exceptions: The operating system can generate errors that Python then passes them along to your application. For exam­ ple, if your application tries to open a file that doesn’t exist, the operating system generates a FileNotFoundError exception.

     Warnings: Python tries to warn you about unexpected events or actions that could result in errors later. For example, if you try to inappropriately use a resource, such as an icon, Python generates a
    ResourceWarning exception. It’s important to remember that this particular category is a warning and not an actual error: Ignoring it can cause you woe later, but you can ignore it.


  • Understanding Data Sorting and Types in Python - Part 4

    Working with queues


    A queue works differently from a stack. Think of any line you’ve ever stood in: You go to the back of the line, and when you reach the front of the line you get to do whatever you stood in the line to do. A queue is often used for task scheduling and to maintain program flow — just as it is in the real world. The following steps help you create a queue-based application.
     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    import queue

    MyQueue = queue.Queue(3)

    print(MyQueue.empty())
    input("Press any key when ready...")


    MyQueue.put(1)
    MyQueue.put(2)
    print(MyQueue.full())
    input("Press any key when ready...")

    MyQueue.put(3)
    print(MyQueue.full())
    input("Press any key when ready...")

    print(MyQueue.get())
    print(MyQueue.empty())
    print(MyQueue.full())
    input("Press any key when ready...")

    print(MyQueue.get())
    print(MyQueue.get())

    To create a queue, you must import the queue module. This module actually contains a number of queue types, but this example uses only the standard FIFO queue.

    When a queue is empty, the empty() function returns True. Likewise, when a queue is full, the full() function returns True. By testing the state of empty() and full(), you can determine whether you need to perform additional work with the queue or whether you can add other information to it. These two functions help you manage a queue . It’s not possible to iterate through a queue using a for loop as you have done with other collection types, so you must monitor empty() and full() instead.

    The two functions used to work with data in a queue are put(), which adds new data, and get(), which removes data. A problem with queues is that if you try to put more items into the queue than it can hold, it simply waits until space is available to hold it. Unless you’re using a multithreaded application (one that uses individual threads of execution to perform more than one task at one time), this state could end up freezing your application.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application tests the state of the queue. In this case, you see an output of True, which means that the queue is empty.

     Press Enter.

    The application adds two new values to the queue. In doing so, the queue is no longer empty.


     Press Enter.

    The application adds another entry to the queue, which means that the queue is now full because it was set to a size of 3. This means that full() will return True because the queue is now full.

     Press Enter.

    To free space in the queue, the application gets one of the entries. Whenever an application gets an entry, the get() function returns that entry. Given that 1 was the first value added to the queue, the print() function should return a value of 1,. In addition, both empty() and full() should now return False.




     Press Enter.

    The application gets the remaining two entries. You see 2 and 3 (in turn) as output.


    Working with deques


    A deque is simply a queue where you can remove and add items from either end. In many languages, a queue or stack starts out as a deque. Specialized code serves to limit deque functionality to what is needed to perform a particular task.

    When working with a deque, you need to think of the deque as a sort of horizontal line. Certain individual functions work with the left and right ends of the deque so that you can add and remove items from either side. The following steps help you create an example that demonstrates deque usage.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line.

    import collections

    MyDeque = collections.deque("abcdef", 10)

    print("Starting state:") for Item in MyDeque:

    print(Item, end=" ")

    print("\r\n\r\nAppending and extending right") MyDeque.append("h")
    MyDeque.extend("ij") for Item in MyDeque:

    print(Item, end=" ") print("\r\nMyDeque contains {0} items."
    .format(len(MyDeque)))

    print("\r\nPopping right")

    print("Popping {0}".format(MyDeque.pop())) for Item in MyDeque:
    print(Item, end=" ")

    print("\r\n\r\nAppending and extending left") MyDeque.appendleft("a") MyDeque.extendleft("bc")
    for Item in MyDeque: print(Item, end=" ")
    print("\r\nMyDeque contains {0} items."
    .format(len(MyDeque)))


    print("\r\nPopping left")
    print("Popping {0}".format(MyDeque.popleft())) for Item in MyDeque:
    print(Item, end=" ")

    print("\r\n\r\nRemoving")
    MyDeque.remove("a") for Item in MyDeque:
    print(Item, end=" ")

    The implementation of deque is found in the collections module, so you need to import it into your code. When you create a deque, you can optionally specify a starting list of iterable items (items that can be accessed and processed as part of a loop structure) and a maximum size, as shown.

    A deque differentiates between adding one item and adding a group of items. You use append() or appendleft() when adding a single item. The extend() and extendleft() functions let you add multiple items. You use the pop() or popleft() functions to remove one item at a time. The act of popping values returns the value popped, so the example prints the value onscreen. The remove() function is unique in that it always works from the left side and always removes the first instance of the requested data.

    Unlike some other collections, a deque is fully iterable. This means that you can obtain a list of items using a for loop whenever necessary.

    3. Choose Run➪Run Module.

    You see a Python Shell window open.


    It’s important to follow the output listing closely. Notice how the size of the deque changes over time. After the application pops the j, the deque still contains eight items. When the application appends and extends from the left, it adds three more items. However, the resulting deque contains only ten items. When you exceed the maximum size of a deque, the extra data simply falls off the other e
  • Understanding Data Sorting and Types in Python - Part 3

    Creating and using a dictionary


    Creating and using a dictionary is much like working with a list, except that you must now define a key and value pair. Here are the special rules for creating a key:

     The key must be unique. When you enter a duplicate key, the information found in the second entry wins — the first entry is simply replaced with the second.

     The key must be immutable. This rule means that you can use strings, numbers, or tuples for the key. You can’t, however, use a list for a key.

    You have no restrictions on the values you provide. A value can be any Python object, so you can use a dictionary to access an employee record or other complex data. The following steps help you understand how to use dictionaries better.


     Open a Python Shell window.

    You see the familiar Python prompt.

     Type Colors = {“Sam”: “Blue”, “Amy”: “Red”, “Sarah”: “Yellow”} and press Enter.

    Python creates a dictionary containing three entries with people’s favorite colors. Notice how you create the key and value pair. The key comes first, followed by a colon and then the value. Each entry is separated by a comma.

     Type Colors and press Enter.

    You see the key and value pairs. However, notice that the entries are sorted in key order. A dictionary automatically keeps the keys sorted to make access faster, which means that you get fast


    search times even when working with a large data set. The downside is that creating the dictionary takes longer than using something like a list because the computer is busy sorting the entries.


     Type Colors[“Sarah”] and press Enter.

    You see the color associated with Sarah, Yellow. Using a string as a key, rather than using a numeric index, makes the code easier to read and makes it self-documenting to an extent. By making your code more readable, dictionaries save you considerable time in the long run (which is why they’re so popular). However, the convenience of a dictionary comes at the cost of additional creation time and a higher use of resources, so you have trade-offs to consider.



     Type Colors.keys( ) and press Enter.

    The dictionary presents a list of the keys it contains. You can use these keys to automate access to the dictionary.


     Type the following code (pressing Enter after each line and pressing Enter twice after the last line):

    for Item in Colors.keys(): print("{0} likes the color {1}."
    .format(Item, Colors[Item]))

    The example code outputs a listing of each of the user names and the user’s favorite color. Using dictionaries can make creating useful output a lot easier. The use of a meaningful key means that the key can easily be part of the output.


     Type Colors[“Sarah”] = “Purple” and press Enter.

    The dictionary content is updated so that Sarah now likes Purple instead of Yellow.

     Type Colors.update({“Harry”: “Orange”}) and press Enter. A new entry is added to the dictionary.

     Place your cursor at the end of the third line of the code you typed in Step 6 and press Enter.

    The editor creates a copy of the code for you. This is a time-saving technique that you can use in the Python Shell when you experiment while using code that takes a while to type. Even though you have to type it the first time, you have no good reason to type it the second time.

     Press Enter twice.

    You see the updated output. Notice that Harry is added in sorted order. In addition, Sarah’s entry is changed to the color Purple.


     Type del Colors[“Sam”] and press Enter.

    Python removes Sam’s entry from the dictionary.

     Repeat Steps 9 and 10.

    You verify that Sam’s entry is actually gone.

     Type len(Colors) and press Enter.

    The output value of 3 verifies that the dictionary contains only three entries now, rather than 4.

     Type Colors.clear( ) and press Enter.

     Type len(Colors) and press Enter.

    Python reports that Colors has 0 entries, so the dictionary is now empty.

     Close the Python Shell window.


    Replacing the switch statement with a dictionary

    Most programming languages provide some sort of switch statement. A switch statement provides for elegant menu type selections. The user has a number of options but is allowed to choose only one of them. The program takes some course of action based on the user selection. Here is some representative code (it won’t execute) of a switch statement you might find in another language:


    switch(n)
    {
    case 0:
    print("You selected blue."); break;
    case 1:
    print("You selected yellow."); break;
    case 2:
    print("You selected green."); break;
    }

    The application normally presents a menu-type interface, obtains the number of the selection from the user, and then chooses the correct course of action from the switch statement. It’s straightforward and much neater than using a series of if statements to accomplish the same task.

    Unfortunately, Python doesn’t come with a switch statement. The best you can hope to do is use an if...elif statement for the task. However, by using a dictionary, you can simulate the use of a switch statement. The following steps help you create an example that will demonstrate the required technique.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    def PrintBlue():
    print("You chose blue!\r\n")

    def PrintRed():
    print("You chose red!\r\n")

    def PrintOrange():
    print("You chose orange!\r\n")

    def PrintYellow():
    print("You chose yellow!\r\n")

    Before the code can do anything for you, you must define the tasks. Each of these functions defines a task associated with selecting a color option onscreen. Only one of them gets called at any given time.

     Type the following code into the window — pressing Enter after each line:

    ColorSelect = {
     PrintBlue,
     PrintRed,
     PrintOrange,
     PrintYellow
    }

    This code is the dictionary. Each key is like the case part of the switch statement. The values specify what to do. In other words, this is the switch structure. The functions that you created earlier are the action part of the switch — the part that goes between the case statement and the break clause.


     Type the following code into the window — pressing Enter after each line:

    Selection = 0

    while (Selection != 4): print("0. Blue") print("1. Red") print("2. Orange") print("3. Yellow") print("4. Quit")

    Selection = int(input("Select a color option: "))

    if (Selection >= 0) and (Selection < 4): ColorSelect[Selection]()

    Finally, you see the user interface part of the example. The code begins by creating an input variable, Selection. It then goes into a loop until the user enters a value of 4.

    During each loop, the application displays a list of options and then waits for user input. When the user does provide input, the application performs a range check on it. Any value between 0 and 3 selects one of the functions defined earlier using the dictionary as the switching mechanism.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application displays a menu like the one.



     Type 0 and press Enter.

    The application tells you that you selected blue and then displays the menu again, as.


     Type 4 and press Enter.

    The application ends.


    Creating Stacks Using Lists


    A stack is a handy programming structure because you can use it to save an application execution environment (the state of variables and other attributes of the application environment at any given time) or as a means of determining an order of execution. Unfortunately, Python doesn’t provide

    a stack as a collection. However, it does provide lists, and you can use a list as a perfectly acceptable stack. The following steps help you create an example of using a list as a stack.

     Open a Python File window.

    You see an editor in which you can type the example code.

     Type the following code into the window — pressing Enter after each line:

    MyStack = []
    StackSize = 3

    def DisplayStack():

    print("Stack currently contains:") for Item in MyStack:
    print(Item)

    def Push(Value):

    if len(MyStack) < StackSize: MyStack.append(Value)
    else:
    print("Stack is full!")

    def Pop():

    if len(MyStack) > 0: MyStack.pop()
    else:
    print("Stack is empty.")

    Push(1)
    Push(2)
    Push(3)
    DisplayStack()
    input("Press any key when ready...")

    Push(4)
    DisplayStack()
    input("Press any key when ready...")

    Pop()
    DisplayStack()
    input("Press any key when ready...")

    Pop()
    Pop()
    Pop()
    DisplayStack()


    In this example, the application creates a list and a variable to determine the maximum stack size. Stacks normally have a specific size range. This is admittedly a really small stack, but it serves well for the example’s needs.

    Stacks work by pushing a value onto the top of the stack and popping values back off the top of the stack. The Push() and Pop() functions perform these two tasks. The code adds DisplayStack() to make it easier to see the stack content as needed.

    The remaining code exercises the stack (demonstrates its functionality) by pushing values onto it and then removing them. There are four main exercise sections that test stack functionality.

     Choose Run➪Run Module.

    You see a Python Shell window open. The application fills the stack with information and then displays it onscreen. In this case, 3 is at the top of the stack because it’s the last value added.


     Press Enter.

    The application attempts to push another value onto the stack. However, the stack is full, so the task fails.

     Press Enter.

    The application pops a value from the top of the stack. Remember that 3 is the top of the stack, so that’s the value that is missing.


     Press Enter.

    The application tries to pop more values from the stack than it contains, resulting in an error. Any stack implementation that you create must be able to detect both overflows (too many entries) and underflows (too few entries).



  • Understanding Data Sorting and Types in Python - Part 2

    Working with Tuples


    As previously mentioned, a tuple is a collection used to create complex lists, in which you can embed one tuple within another. This embedding lets you create hierarchies with tuples. A hierarchy could be something as simple as the directory listing of your hard drive or an organizational chart for your company. The idea is that you can create complex data structures using a tuple.

    Tuples are immutable, which means you can’t change them. You can create a new tuple with the same name and modify it in some way, but you can’t modify an existing tuple. Lists are mutable, which means that you can change them. So, a tuple can seem at first to be at a disadvantage, but immutability has all sorts of advantages, such as being more secure as well as faster. In addition, immutable objects are easier to use with multiple processors.

    The two biggest differences between a tuple and a list are that a tuple is immutable and allows you to embed one tuple inside another. The following steps demonstrate how you can interact with a tuple in Python.

     Open a Python Shell window.

    You see the familiar Python prompt.

     Type MyTuple=(“Red”, “Blue”, “Green”) and press Enter. Python creates a tuple containing three strings.
     Type MyTuple and press Enter.

    You see the content of MyTuple, which is three strings. Notice that the entries use single quotes, even though you used double quotes to create the tuple. In addition, notice that a tuple uses parentheses rather than square brackets, as lists do.


    Type dir(MyTuple) and press Enter.

    Python presents a list of functions that you can use with tuples. Notice that the list of functions appears significantly smaller than the list of functions provided with lists in previous post. The count() and index() functions are present.


    However, appearances can be deceiving. For example, you can add new items using the __add__() function. When working with Python objects, look at all the entries before you make a decision as to functionality.

    5. Type MyTuple=MyTuple.__add__((“Purple”,)) and press Enter.

    This code adds a new tuple to MyTuple and places the result in a new copy of MyTuple. The old copy of MyTuple is destroyed after the call.

    The __add__() function accepts only tuples as input. This means that you must enclose the addition in parentheses. In addition, when creating a tuple with a single entry, you must add a comma after the entry, as shown in the example. This is an odd Python rule that you need to keep in mind or you’ll see an error message similar to this one:

    TypeError: can only concatenate tuple (not "str") to tuple

     Type MyTuple and press Enter.

    The addition to MyTuple appears at the end of the list. Notice that it appears at the same level as the other entries.


     Type MyTuple=MyTuple.__add__((“Yellow”, (“Orange”, “Black”))) and press Enter.

    This step adds three entries: Yellow, Orange, and Black. However, Orange and Black are added as a tuple within the main tuple, which creates a hierarchy. These two entries are actually treated as a single entry within the main tuple.

    You can replace the __add__() function with the concatenation operator. For example, if you want to add Magenta to the front of the tuple list, you type MyTuple=("Magenta",) + MyTuple.

     Type MyTuple[4] and press Enter.

    Python displays a single member of MyTuple, Orange. Tuples use indexes to access individual members, just as lists do. You can also specify a range when needed. Anything you can do with a list index you can also do with a tuple index.

     Type MyTuple[5] and press Enter.

    You see a tuple that contains Orange and Black. Of course, you might not want to use both members in tuple form.

    Tuples do contain hierarchies on a regular basis. You can detect when an index has returned another tuple, rather than a value, by testing for type. For example, in this case, you could detect that the sixth item (index 5) contains a tuple by typing type(MyTuple[5]) == tuple. The output would be True in this case.


     Type MyTuple[5][0] and press Enter.

    At this point, you see Orange as output. The indexes always appear in order of their level in the hierarchy.


    Using a combination of indexes and the __add__() function (or the concatenation operator, +), you can create flexible applications that rely on tuples. For example, you can remove an element from a tuple by making it equal to a range of values. If you wanted to remove the tuple containing Orange and Black, you type MyTuple=MyTuple[0:5].

     

    Working with Dictionaries



    A Python dictionary works just the same as its real-world counterpart — you create a key and value pair. It’s just like the word and definition in a dictionary. As with lists, dictionaries are mutable, which means that you can change

    them as needed. The main reason to use a dictionary is to make information lookup faster. The key is always short and unique so that the computer doesn’t spend a lot of time looking for the information you need.

    The following sections demonstrate how to create and use a dictionary. When you know how to work with dictionaries, you use that knowledge to make up for deficiencies in the Python language. Most languages include the concept of a switch statement, which is essentially a menu of choices from which one choice is selected. Python doesn’t include this option, so you must normally rely on if...elif statements to perform the task. (Such statements work, but they aren’t as clear as they could be.)


  • Powered by Blogger.

    Tags

    Popular Posts