CS 151: Lab 3

Title image Project 3
Spring 2020

Lab Exercise 3: Loops, conditionals and command line parameters

The goal of this lab and project is to incorporate loops and conditionals into your code as well as provide more practice in encapsulating code and concepts for later re-use and manipulation.


Tasks

  1. Set up your workspace

    In your personal file space, make a folder called project3.

    Open a text editor (e.g TextWrangler). Create a new file called com.py. Put a comment at the top of the file with your name, date, and the file name. Save it in the project3 folder.

  2. Discover Command-line Arguments

    When we run a python program in the Terminal (or command-line), sometimes we want to pass information to the program to control its behavior. The following steps will show you how to get access to the command-line information.

    1. Import packages

      After the comment lines, write the command to tell python to import the sys package:

      import sys
    2. Find out what the sys package can do

      Put the following line of code in your file.

      print(sys.argv)

      Save your file, cd to your working directory, and then run your com.py file. What do you see?

      Type some additional things on the command line after python3 com.py. For example, try:

      python3 com.py hello world 1 2 3

      What do you see?

      The sys package gives you the ability to see what the user has typed on the command line. Each individual string (defined by spaces) from the command line is an entry in a list, which is a data type that we describe as a sequential container.

    3. Access individual strings

      Add the following lines to your com.py file.

      print(sys.argv[0])
      a = sys.argv[3]
      print(a * 3)
      b = int( sys.argv[3] )
      print( b * 3)

      Run the program using the following command.

      python3 com.py three times 3

      What is going on? The first of the above three lines prints out the first item in the sys.argv list. The second line accesses the fourth item in the sys.argv list, which is a string with the digit '3' in it, and assigns it to the variable a. The third line multiplies a by 3 and prints the result, which is the string repeated three times. The fourth line accesses the fourth item in the sys.argv list, converts it to an integer and assigns the result to b. Then the fifth line multiplies b by 3 and prints out the results of 3*3.

      How could you use the capability to access values from the command line in a program? What do you need to do in order to use command line arguments as numbers?

  3. Draw a Star

    Create a new file called star.py. Import the turtle and the sys packages and then copy the following code into your file.

    # draw a star with the given number of rays of the given size
    def star( rays, size ):
        print('Drawing a star with', rays, 'rays of size', size )
    
        # loop for the number of rays
        for i in range(rays):
            turtle.setheading( i * 360 / rays )
            turtle.forward( size )
            turtle.backward( size )
    
    
    # top level code, make drawing fast
    turtle.tracer(False)
    
    # assign values to variables
    numrays = 10
    raysize = 50
    
    # call the star function
    star(numrays, raysize)
    
    # update and hold open the window
    turtle.update()
    turtle.mainloop()

    Run star.py and see what it does.

  4. Control the appearance of the star using command line parameters

    Modify the star.py code so that the number of rays and the ray size are controlled by command line parameters. Start by importing the sys package. You will need to use sys.argv and a cast to assign int values to numrays and to raysize. Look at the com.py code for an example.

    Run your code several different times using different command line arguments. For example:

    python3 star.py 8 100

    What happens if you forget to put arguments on the command line?

  5. Catching Errors

    One thing you discover when you write software is that users do not always do what they should. They don't always give you enough information or the correct information. If you want to have a robust program, you have to check the information coming in to see if it is there.

    For example, are there reasonable bounds on the number of stars in the image? What if the user does not provide enough command line parameters?

    One strategy is to pick a default value (e.g. 10) and create a variable to hold the default value.

    rays = 10

    If the user gives you a new value, then use the new value. The following code executes this idea. Add it to your star.py file. This chunk of code should replace the first assignment to rays.

    # assign a default value
    rays = 10
    
    # check for user input
    if len( sys.argv ) > 1:
        # re-assign the value if the user provided one
        rays = int( sys.argv[1] )

    The idea of having default behavior that the user can override is common in computer programs. Do the same thing for the raysize variable that uses sys.argv[2]. Then show that your program will work with no command line parameters, one parameter, and two parameters.

  6. The Range Function

    Now we're going to explore the range function that is important for common loops in Python. Open up the Python interpreter in a terminal by just typing python3. The interpreter lets you try out python code directly. Type the following code into the interpreter and run it.

    for i in range(5): print(i)	

    What does the code print? What is the value of the loop variable at each iteration of the loop?

    Try giving the range function two arguments (e.g. range(5, 10)) What does it print? Try several different pairs of arguments.

    Try giving the range function three arguments (e.g. range(5, 10, 2)). What does it print? Try several different sets of arguments.

    Try getting help on the range function by typing

    help( range )

    How does it match with what you discovered? Use 'q' to get out of the help browser.

    Use control-d (control key, not the command key) to get out of the Python interpreter.

  7. Lots of stars

    Edit your top level code so it calls the star function inside a loop. Use x as your loop variable. Set up the arguments to your range function so that it starts at -200, ends at 200, and steps by 50. Also inside the loop, and before drawing the star, add a penup, a goto, and a pendown. The goto should send the turtle to location (x, 0), where x is your loop variable. How many stars should it draw, and where will they be?

  8. Code Organization

    The final lesson on code organization today is enclosing all of your top-level code in a main function and the making the execution of that function dependent upon whether the file was imported into another file or run from the command line.

    Put all of your top-level code in the body of a new function called main. After the main function definition, put the following top-level code.

    if __name__ == "__main__":
        main()

    Run your file.

    The above conditional statement will be true only when you run the python file on the command line. If you were to import this file into another python program, the conditional statement would evaluate to false and the main function would not run.

    The real benefit is that you can write test functions for a collection of functions--like your shapes.py file--without having your test function interfere with importing it into other programs.

    From now on, your files should always have that conditional in front of top-level code.


When you are done with the lab exercises, you may begin the project.