Python II

Today's topics

  • Review
  • Scripting
  • Functions
  • Loops
  • Reading/Writing files & formatting output
  • Libraries

Review

  • Numeric and string input:
    <variable> = input <prompt>
  • Lists, mutable, mixed-type:
    [<item1>, <item2>, ...]
  • Tuples, immutable list:
    (<item1>, <item2>, ...)

Review

  • Dictionaries, mutable key-value pairs:
    {<key1>: <value1>, <key2>: <value2> ... }
  • Indexing:
    <variable>[i]
  • Slicing:
    <variable>[begin:end]
  • If statement:
    if <condition>

Writing scripts

Scripts

To run your Python script:

  • Add the ".py" extension
  • Needs #!/usr/bin/env python at top of script
  • To run the script:
    
                                    python scriptname.py
                                    

Scripts

From last time


                        
                        In [1]: spam = input("2 letter words for (and rhymes with) you and me: ")

                        In [3]: guido = [spam, 'eggs']

                        In [4]: if (guido[1] == 'eggs'):
                           ...:     guido[1] = 'are the'
                           ...:

                        In [5]: x = guido

                        In [6]: sausage = input("Like a time of day, but begins with 'k': ")

                        In [7]: y = sausage + 's'

                        In [8]: bacon = input("Fill in the blank in this children's game: Simon ___: ")

                        In [9]: z = ['who', bacon[0:-1]]

                        In [10]: print(x, y, z, "Ni!")
                        

Scripts

Now you can put everything together


                        In [1]: def main():
                           ...:     spam = input("2 letter words for (and rhymes with) you and me: ")
                           ...:     guido = [spam, 'eggs']
                           ...:     if (guido[1] == 'eggs'):
                           ...:         guido[1] = 'are the'
                           ...:     x = guido
                           ...:     sausage = input("Like a time of day, but begins with 'k': ")
                           ...:     y = sausage + 's'
                           ...:     bacon = input("Fill in the blank in this children's game: Simon ___: ")
                           ...:     z = ['who', bacon[0:-1]]
                           ...:     print(x, y, z, "Ni!")
                           ...:

                        In [2]: main()
                        

You can now save this in a file with the .py extension!

Functions

Functions

  • Define a function with def <function>():
  • Call a function with <function>()
    
                                    In [1]: def example_function():
                                       ...:     print("This is a normal function")
                                       ...:
    
                                    In [2]: example_function()
                                    This is a normal function
                                    

Functions

  • You can pass arguments between functions
  • def <function>(<arg1>, <arg2>):
  • 
                                In [1]: def greet(person):
                                   ...:     print('Hello ', person)
                                   ...:
    
                                In [2]: def main():
                                   ...:     name = input("What is your name?: ")
                                   ...:     greet(name)
                                   ...:
    
                                In [3]: main()
                                What is your name?: Victor
                                Hello  Victor
                                

Functions

  • They can also return values!
  • 
                                In [1]: def square(x):
                                   ...:     z = float(x)**2
                                   ...:     return z
                                   ...:
    
                                In [2]: def main():
                                   ...:     number = input("Pick a number, any number: ")
                                   ...:     y = square(number)
                                   ...:     print("The square of your number is: ", y)
                                   ...:
    
                                In [3]: main()
                                Pick a number, any number: 16
                                The square of your number is:  256.0
                                

See how I had to change the input. It was a string, so I changed it to a float!

Functions

  • Functions should have docstrings!
  • This is the documentation of the function
  • 
                                In [1]: def square(x):
                                   ...:     """
                                   ...:     Returns the square of a number `x`
                                   ...:
                                   ...:     Parameters
                                   ...:     -----------
                                   ...:     x : `float`, `str`, `int`
                                   ...:         Input number.
                                   ...:
                                   ...:     Returns
                                   ...:     ----------
                                   ...:     z : `float`
                                   ...:         Square value of `x`
                                   ...:     """
                                   ...:     z = float(x)**2
                                   ...:     return z
                                

Functions

  • You can call the docstring in iPythonwith the ? symbol
  • 
                                In [3]: square?
                                Signature: square(x)
                                Docstring:
                                Returns the square of a number `x`
    
                                Parameters
                                -----------
                                x : `float`, `str`, `int`
                                    Input number.
    
                                Returns
                                ----------
                                z : `float`
                                    Square value of `x`
                                File:      ~/<ipython-input-2-56d47fb12480>
                                Type:      function
                                

Functions

  • The docstring of a function is very important!
  • You should always document your functions and code!
  • You'll be making yourself and others a favor
  • And you might use it in the future!!

For more info on how to properly write docstrings, see:
https://docs.python-guide.org/writing/documentation/#docstrings-and-magic

Loops
How to write them

Loops - for loops

The main format of the for loop is:


                        for <variable> in <sequence>:
                            do something
                        

Examples


                        In [1]: word = 'spam'
                        In [2]: for letter in word:
                           ...:     print(letter)
                           ...:

                        In [3]: for i in [1, 3, 5, 7, 9]:
                           ...:     print(i * i)

                        In [4]: for i in range(10):
                           ...:     x = 3.9 * i * (1 - i)
                           ...:     print(x)
                        

Loops - while loops

The main format of the while loop is:


                        while <condition>:
                            <body>
                        

Examples


                        In [2]: while(i < 10):
                           ...:     print(i)
                           ...:     i = i + 1
                           ...:
                        0
                        1
                        2
                        3
                        4
                        5
                        6
                        7
                        8
                        9
                        

Note that you can also write:


                        i += 1
                        

instead of i = i + 1

Reading files

Reading files

  • <filevar>.read()
    • Returns the entire contents of the file as a single string
  • <filevar>.readline()
    • Returns the next line of the file, up to and including the next newline character \n
  • <filevar>.readlines()
    • Returns a list of the remaining lines in the f
    • Each item in the list if a line including the newline character.

Reading files


                        # How to open a file. The 'r' stands for 'read'.
                        infile = open('filename.dat', 'r')
                        
                        # Saves the entire content of the file as a single string
                        data = infile.read()
                        
                        # Print out data
                        print(data)
                        
                        # Closes the file. Always remember to close your files!
                        infile.close()
                        

Reading files

Now you can print out the first 6 lines of sample.dat


                        # Opens the file in 'read' mode
                        infile = open('sample.dat', 'r')
                        
                        # Loops over the first 6 lines
                        for i in range(6):
                            # Saves output to 'line'
                            line = infile.readline()
                            print( line[:-1] )
                        
                        # Closes the file.
                        infile.close()
                        

You can open files with the r option.

Writing files

Writing files

  • <filevar>.write(<string>)

                        # Writes to file 'out.dat' and saves it as the object 'outfile'
                        outfile = open('out.dat', 'w')
                        
                        # You write strings to 'outfile'.
                        # See the newline character and how it is being added
                        # to the string.
                        outfile.write( "Spam and eggs\n")
                        outfile.write( "Spam, bacon, eggs, and spam\n")
                        
                        # Close the file
                        outfile.close()
                        

Watch out ... 'w' will overwrite the file each time it is reopened.

You can use 'a' instead to append to the file

Formatting

Formatting

  • You can format strings by specifying the type of data
  • <format specifier> % (<values>)
  • Format specifier: %<width>.<precision>.<datatype>

You can specify the type of data types as well!

Formatting

  • Possible data types: decimal, float, and string

As part of the string, you can specify:

  • width
      How manyplaces to use in display. If not enough, Python will expand to fit the value. Width of 0 means "use as much space as needed.
  • precision
      with floats, precision indicates the number of digits after the decimal

width and precision are optional

Formatting

Some examples are


                        In [1]: a = 165.2

                        In [2]: print( '%.2d' %(a))
                        165

                        In [3]: b = 1024.65748

                        In [4]: print( '%.3f' %b)
                        1024.657

                        In [5]: print( '%s and another %s' %('spam', 'ham'))
                        spam and another ham
                        

A better way of formatting

There is a better and easier way of formatting strings.

'some_string_{0}'.format(something)

A better way of formatting


                        In [1]: a = 123.45
                        In [2]: b = 45
                        In [3]: c = 'some string'

                        In [4]: 'a is equal to {0}, but b is equal to {1}'.format(a, b)
                        Out[4]: 'a is equal to 123.45, but b is equal to 45'

                        In [5]: 'you can also print out strings: {0}'.format(c)
                        Out[5]: 'you can also print out strings: some string'

                        In [6]: 'And combine numbers (a = {0:.1f} and strings (c = {1})'.format(a, c)
                        Out[6]: 'And combine numbers (a = 123.5 and strings (c = some string)'
                        
  • format is really easy to use
  • You don't have to convert into strings
  • And you can use with along with arrays

A better way of formatting


                        In [7]: array1 = [1, 'pancake', 2.0, 'testing']

                        In [8]: str1 = 'First is "{0}", then "{1}". Third element is "{2}", and finally "{3}"'

                        In [9]: str1.format(*array1)
                        Out[9]: 'First is "1", then "pancake". Third element is "2.0", and finally "testing"'
                        
  • format is really easy to use
  • You don't have to convert into strings
  • And you can use with along with arrays

Libraries

Libraries

Whenever you write a script or interact with Python, you want to include some packages:

  • Math - 'advanced' math functions
  • Strings - String manipulation functions
  • os - Operating system interface
  • etc.

Libraries

Ways of using a package

  • import <library>

                        ## Import the complete package
                        import math

                        # Access a function
                        math.sqrt(x)
                        

Libraries

Ways of using a package

  • from <library> import <function>

                        ## Importing only a module of the package
                        from numpy import arange

                        # Access a function
                        arange(10)
                        

Libraries

Ways of using a package

  • from <library> import *

                        ## Importing only a module of the package
                        from numpy import *

                        # Access a function
                        arange(10)
                        

Libraries

Out of the three methods of importing a package,
the best one is the:

import <library>

because you're not overwriting namespace

More info: here

Useful resources

Back to main website:

https://tinyurl.com/bcb18