Python - tutorial - 13/14

PIP - try except - user input - string formatting

Revision:


Python - PIP

PIP is a package manager for Python packages, or modules if you like. If you have Python version 3.4 or later, PIP is included by default.

A package? contains all the files you need for a module. Modules are Python code libraries you can include in your project.

Check if PIP is installed: navigate your command line to the location of Python's script directory, and type the following: C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip --version

Install PIP: If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/

Download a Package: Open the command line interface and tell PIP to download the package you want. Navigate your command line to the location of Python's script directory, and type the following: C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip install camelcase

Using a Package: Once the package is installed, it is ready to use. Import the "camelcase" package into your project.

Example 1: import and use "camelc ase":

        import camelcase
        c = camelcase.CamelCase()
        txt = "hello world"
        print(c.hump(txt))
    

Find Packages: find more packages at https://pypi.org/.

Remove a Package: use the uninstall command to remove a package:

Example 2: uninstall the package named "camelcase":

        C:\Users\Your Name\AppData\Local\Programs\Python\Python36-32\Scripts>pip uninstall camelcase
    

List Packages: use the "list" command to list all the packages installed on your system:


Python - try except

The "try" block lets you test a block of code for errors. The "except" block lets you handle the error. The "finally" block lets you execute code, regardless of the result of the "try" and "except" blocks.

Exception handling: when an error occurs, or exception as we call it, Python will normally stop and generate an error message. These exceptions can be handled using the "try" statement.

Example 3: the "try" block will generate an exception, because x is not defined:

        try:
            print(x)
        except:
            print("An exception occurred")
    

Since the "try" block raises an error, the "except" block will be executed. Without the "try" block, the program will crash and raise an error.

Many exceptions: you can define as many exception blocks as you want, e.g. if you want to execute a special block of code for a special kind of error.

Example 4: print one message if the "try" block raises a NameError and another for other errors:

        try:
           print(x)
        except NameError:
            print("Variable x is not defined")
        except:
            print("Something else went wrong")
    

Else: yu can use the "else" keyword to define a block of code to be executed if no errors were raised.

Example 5: in this example, the try block does not generate any error:

        try:
            print("Hello")
        except:
            print("Something went wrong")
        else:
            print("Nothing went wrong")
    

Finally: the "finally" block, if specified, will be executed regardless if the "try" block raises an error or not. This can be useful to close objects and clean up resources.

Example 6: the "finally" block

        try:
            print(x)
        except:
            print("Something went wrong")
        finally:
            print("The 'try except' is finished")
    

Raise an exception: As a Python developer you can choose to throw an exception if a condition occurs.To throw (or raise) an exception, use the "raise" keyword. The "raise" keyword is used to raise an exception. You can define what kind of error to raise, and the text to print to the user.

Example 7: rise an error and stop the program if x is lower than 0:

        x = -1
        if x < 0:
            raise Exception("Sorry, no numbers below zero")
    

Example 8: raise a TypeError if x is not an integer:

        x = "hello"
        if not type(x) is int:
            raise TypeError("Only integers are allowed")
    


Python - user input

User unput: Python allows for user input. That means we are able to ask the user for input. The method is a bit different in Python 3.6 than Python 2.7. Python 3.6 uses the input() method. Python 2.7 uses the raw_input() method. Python stops executing when it comes to the input() function, and continues when the user has given some input.


Python - string formatting

String format() The format() method allows you to format selected parts of a string. Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input? To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method. You can add parameters inside the curly brackets to specify how to convert the value.

Example 9: add a placeholder where you want to display the price:

        price = 49
        txt = "The price is {} dollars"
        print(txt.format(price)) # The price is 49 dollars
    

Example 10: format the price to be displayed as a number with two decimals.

        txt = "The price is {:.2f} dollars"
    

Multiple values: if you want to use more values, just add more values to the format() method. And add more placeholders.

Example 11: more values

        print(txt.format(price, itemno, count))
    

Example 12: more placeholders

        quantity = 3
        itemno = 567
        price = 49
        myorder = "I want {} pieces of item number {} for {:.2f} dollars."
        print(myorder.format(quantity, itemno, price))
    

Index numbers: you can use index numbers (a number inside the curly brackets {0}) to be sure the values are placed in the correct placeholders. Also, if you want to refer to the same value more than once, use the index number.

Example 13:

        quantity = 3
        itemno = 567
        price = 49
        myorder = "I want {0} pieces of item number {1} for {2:.2f} dollars."
        print(myorder.format(quantity, itemno, price))
    

Example 14: same value more than once

        age = 36
        name = "John"
        txt = "His name is {1}. {1} is {0} years old."
        print(txt.format(age, name))
    

Named indexes: you can also use named indexes by entering a name inside the curly brackets {carname}, but then you must use names when you pass the parameter values txt.format(carname = "Ford"):

Example 15:

        myorder = "I have a {carname}, it is a {model}."
        print(myorder.format(carname = "Ford", model = "Mustang"))