OPS445 Lab 2

From Littlesvr Wiki
Revision as of 20:27, 10 January 2025 by Andrew (talk | contribs) (→‎if)
Jump to navigation Jump to search

!!! THIS LAB IS NOT READY YET !!!

User Input

In this lab we will look at two ways to get data from the user into your program.

Prompting for input

Asing the program user for input on the command-line is a rather unusual thing to do these days, but it will help you get used to several basic concepts.

  • To begin, let's start out with a very basic script. This script will use objects that will display specific values to your terminal. Create the file lab2a.py in the ~/ops435/lab2 directory, containing the following content:
    #!/usr/bin/env python3
    
    name = 'John'
    age = 20
    print('Hi ' + name + ', you are ' + str(age) + ' years old.')
    
  • Try running this script and study the output:
    ./lab2a.py
    

This Python script is not very useful: it always displays the same output.

You can use the input() function to obtain information from the user and store it into a variable. The argument you pass to the input() function will be the prompt the user will see.

  • Replace the print() call in your lab2a.py with the following (you can just comment-out the print() call using a # at the beginning of the line):
    colour = input("Type in a colour and press enter: ")
    
  • When prompted, type the text: red and press ENTER. Did anything display? Why not?
  • Add another line to your script:
    print(colour)
    

Thr print() function will display the contents of the colour variable (it's a variable and not the string "colour" because it's in quotes). The contents of the colour variable are set to whatever the input() function returned, which is whatever the user typed in before pressing Enter.

  • Now replace that line with this:
    print("The colour I typed in is: " + colour)
    

This appears trivial, but again: take the time to understand what's happening here:

  1. Your program calls the Python input() function, passing it a string.
  2. The input function prints the string it received on the terminal, and waits for the user to type something in and press Enter.
  3. After the user does that: the input function returns the string which the user typed in back to your program.
  4. Your program takes the return from the input function and stores it in the colour variable.
  5. Your program then concatenates the two strings "The colour I typed in is: " and the value in the colour variable.
  6. Your program calls the print() function, and passes to it that concatenated string as a parameter.

When you start understanding software in this manner: you're starting to think as a programmer.

  • Make a copy of lab2a.py and call it lab2b.py
  • Modify lab2b.py so that it prompts the user for both the user's name and age. Your program should:
  1. Have a Shebang line
  2. Use a variable called name
  3. Use a variable called age
  4. Prompt the user for "Name: "
  5. Prompt the user for "Age: "
  6. Store the values in the correctly spelled variables (case sensitivity counts)
  7. Print the exact output as shown. Think through what type of variable age is.

Sample run 1:

./lab2b.py
Name: Jon
Age: 20
Hi Jon, you are 20 years old.

Sample run 2:

./lab2b.py
Name: Jen
Age: 25
Hi Jen, you are 25 years old.
  • Download the checking script and check your work. Run the following commands from the bash shell.
    cd ~/ops435/lab2/
    pwd # confirm that you are in the right directory
    ls CheckLab2.py || wget wget http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2b
    
  • Before proceeding, make certain that you identify any and all errors in lab2b.py. When the check script tells you everything is OK, you may procede to the next step.

Using command-line arguments

An argument is a data item that is passed to a program or passed to a function that can be used for processing within that program or function. In the previous section, you passed an argument to the input() function. In this section, you will learn how to pass an argument to your Python script, but this time, this argument will be passed when we execute your Python script from the bash shell.

  • Create a temporary file to use for testing your work for this section.

In order to read arguments in Python, we will need to import some functionality from a standard 'library' of code provided by the developers of Python. import sys will load into your program code written by another person.

  • Start with the following line:
    import sys
    
  • Add these function calls one at a time, and note what they do:
    print(sys.version) # tells us the version of the python currently in use
    print(sys.platform) # tells us our operating system platform
    print(sys.argv) # tells us our arguments or shell version if issued from shell
    print(len(sys.argv)) # tells us the number of command line arguments the program received
    sys.exit() # will immediately end the running Python program, ignoring the remaining lines in the program
    

Instead of using the input() function to prompt the user for data, we can get the arguments the user provided. They are available in sys.argv, which is an object (a variable which is an instance of a class) of type list:

  1. sys.argv - stores all argument items
  2. sys.argv[0] - stores the name of the program
  3. sys.argv[1] - stores the first argument
  4. sys.argv[2] - stores the second argument
  5. etc...
  6. len(sys.argv) - gives the number of arguments
  • Create a new script called ~/ops435/lab2/showargs.py and add the following content:
    #!/usr/bin/env python3
    
    import sys
    
    arguments = sys.argv
    name = sys.argv[0]
    
    print('Print out ALL script arguments: ', arguments)
    print('Print out the script name: ' + name)
    print('Print out the number of arguments: ', len(sys.argv))
    
  • Run the script and examine the output by running the Python script without and with arguments:
    ./showargs.py
    ./showargs.py testing different arguments
    ./showargs.py argument1 argument2 argument3 argument4
    
  • Make a copy of lab2b.py and call it lab2c.py.
  • Modify lab2c.py to use the sys.argv[1] and sys.argv[2] functions instead of the input() function (used in your previous lab2b.py program). Your program should:
  1. Have a Shebang line
  2. Contain import sys
  3. Use a variable called name
  4. Use a variable called age
  5. Use sys.argv[1] (first argument)
  6. Use sys.argv[2] (second argument)
  7. Store the values in the correct variables
  8. Print the exact as shown

Sample run 1:

./lab2c.py Jon 20
Hi Jon, you are 20 years old.

Sample run 2:

./lab2c.py Jen 25
Hi Jen, you are 25 years old.

Note that in the following sample run 3 shows an ugly an error message. This error happens if you run the script without any arguments. It is important to note that an error such as this can occur, so you can avoid it when you write your code.

Sample run 3:

./lab2c.py
Traceback (most recent call last):
  File "/home/andrew/ops435/lab2/./lab2c.py", line 5, in <module>
    name = sys.argv[1]
           ~~~~~~~~^^^
IndexError: list index out of range
  • Download the checking script and check your work. Run the following commands from the bash shell:
    cd ~/ops435/lab2/
    pwd # confirm that you are in the right directory
    ls CheckLab2.py || wget wget http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2c
    

Conditional execution

The programs we've written so far probably barely feel like software at all. They would just just execute one line at a time, from beginning to end. Boring.

What makes software useful, or very useful, or actually intelligent is conditional execution.

All programming languages have some means to do this. The syntax will be different, but the fundamental principles are universal.

if

An if statement is a control flow statement that executes or does not execute a block code depending on whether a condition is True or False.

The syntax of the if statement is the same no matter how impressive the results. if, followed by condition, followed by action For example, both of these are decisions a human being can make:

  1. If the chair looks comfortable: I will sit in it.
  2. If I work really hard to get good grades in courses in my program which my parents paid for: that will keep me busy for a few years so I don't have to make any difficult decisions about my life.

Let's look at how this works in Python.

  • Create a temporary python file for testing things in this section.
  • Try the following 2 lines, indenting the second line:
    if True:
        print('This print is apart of the if statement')
    

When you run this code:

  1. The condition following the keyword if will be evaluated. It needs to evaluate to True or False. Usually it's obvious what's true and what's false, and other times you'll have to do some research to figure it out.
  2. When the condition evaluates to True, the code indented underneath the if statement will run. In this case, we use the boolean value True to make this happen.
  3. When the condition evaluates to False, then the code indented underneath the if statement will not run. Any code not indented under the if statement will run normally as the main program and is NOT associated with control flow statement.
  4. Indentation means to start a line with spaces or tabs before your text. Using indentation will direct the script what code will run as part of the IF statement and which code will run regardless. Also, using indentation makes it easier for a programmer to identify Control Flow statements. From this point on, be VERY careful and consistent with indentation because it will affect how your code works.
Important.png
4 spaces
While python allows some flexibility with your indentation - please don't be creative with it. Always use 4 spaces for each new block. There will be exceptions later on, but start with this now. You may find it helpful to configure your editor to insert four spaces instead of a tab character when you press the tab key.
  • Try the following 3 lines, indenting the second and third lines, but NOT the fourth line:
    if False:
        print('This first print statement will never run')
        print('This second print statement will also not run')
    print('This print statement will run')
    

So far, you have been using only the Boolean values True or False for your IF statements. This is really only useful for testing purposes. Normally for a condition you use an expression that will be evaluated to a True or False Boolean value.

  • Create an IF statement with a different condition and run that code:
    password = input('Please enter a secret password: ')
    if password == "P@ssw0rd":
        print('You have succesfully used the right password')
    

Here's what happened:

  1. The value of the password variable is set (using the assignment operator) to the return of the input() function.
  2. The condition in the if statement checks whether the value of the password variable is the same as the string '"@ssword".
  3. That check is done using the == operator, which is nothing like the = operator. == is used for checking whether the left side is equal to the right side. = is used to assign the value from the right side to the variable on the left side.
  4. The == operator returns a value, the same way as a function returns a value. This operator always returns either True or False.

If statements can also be used to compare numbers. We can do this by using comparison operators (such as: ==, !=, >, >=, <, <=), but we can also use functions. The function len() can be used to return the number of characters in a word (plus other features). length of words and other objects. We can also use the len() function to give us the number of argumuents provided to our script by using 'len(sys.argv)' and it should return a number. Below we are also using != which stands for not eqal to.

  • Try the following program:
    import sys
    
    print(len(sys.argv))
    
    if len(sys.argv) != 10:
        print('you do not have 10 arguments')
        sys.exit()
    
Important.png
Number of Arguments with len(sys.argv)
If you are calling the len() function with the sys.argv argument, the number of arguments returned will be always be at least '1'. This number will always be one higher than the actual number of arguments entered, since it also counts the script name as a argument.

Now it's time to create a new script. You will be modifying the previous Python script to provide a message if the user did NOT provide any argument when running the script, and abort the script if two additional arguments are not provided. Refer to Sample Runs displayed below for exact prompt and output requirements.

  • Make a copy of lab2c.py and call it lab2d.py
  • Modify lab2d.py by adding an if statement immediately BEFORE your print statements. This if statement should make sure that lab2d.py has received '2' additional arguments.
  • The program should also:
  1. Have a Shebang line
  2. import sys
  3. Print a usage message if zero arguments present, or if not exactly 2 arguments are provided when running the program (NOTE: Use sys.argv[0] value in this message in case you rename the program at a later date!)
  4. Exit without attempting to do any more work if exactly 2 arguments are not provided when running script
  5. Use an object called name
  6. Use an object called age
  7. Use sys.argv[1] (first argument)
  8. Use sys.argv[2] (second argument)
  9. Store the values in the correct objects
  10. Print the exact output as shown

Sample run 1:

./lab2d.py Jon 20
Hi Jon, you are 20 years old.

Sample run 2:

./lab2d.py Jen 25
Hi Jen, you are 25 years old.

Sample run 3:

./lab2d.py 
Usage: ./lab2d.py name age

Sample run 4:

./lab2d.py Jon is 20
Usage: ./lab2d.py name age
  • Download the checking script and check your work. Run the following commands from the bash shell:
    cd ~/ops435/lab2/
    pwd # confirm that you are in the right directory
    ls CheckLab2.py || wget wget http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2d