OPS445 Lab 2: Difference between revisions

From Littlesvr Wiki
Jump to navigation Jump to search
Line 158: Line 158:
python3 ./CheckLab2.py -f -v lab2c
python3 ./CheckLab2.py -f -v lab2c
</syntaxhighlight>
</syntaxhighlight>
= 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 different code based on whether the condition is '''True''' or '''False'''.

Revision as of 12:30, 10 January 2025

!!! 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 different code based on whether the condition is True or False.