OPS445 Lab 2: Difference between revisions

From Littlesvr Wiki
Jump to navigation Jump to search
 
(2 intermediate revisions by the same user not shown)
Line 109: Line 109:
name = sys.argv[0]
name = sys.argv[0]


print('Print out ALL script arguments: ', arguments)
print('Print out ALL program arguments: ', arguments)
print('Print out the script name: ' + name)
print('Print out the program name: ' + name)
print('Print out the number of arguments: ', len(sys.argv))
print('Print out the number of arguments: ', len(sys.argv))
</syntaxhighlight>
</syntaxhighlight>
Line 399: Line 399:


* Make a copy of '''lab2f.py''' and call it '''lab2g.py'''.
* Make a copy of '''lab2f.py''' and call it '''lab2g.py'''.
* Modify '''lab2g.py''', add an IF statement to the program which will check whether an argument was entered. If a argument was entered use that number for the timer, if no argument was entered, then by default, the timer should equal 3.  
* Modify '''lab2g.py''', and rename the '''count''' variable to '''timer'''.
* Add an IF statement to the program which will check whether an argument was entered. If a argument was entered use that number for the timer, if no argument was entered, then by default, the timer should equal 3.


* Your program sould also:
* Your program sould also:
Line 446: Line 447:
Run the following command in a terminal:<syntaxhighlight lang="bash">
Run the following command in a terminal:<syntaxhighlight lang="bash">
cd ~/ops435/lab2
cd ~/ops435/lab2
python3 ./CheckLab2.py -f -v
python3 ./CheckLab2.py -f
</syntaxhighlight>
</syntaxhighlight>



Latest revision as of 10:17, 19 January 2025

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 program. This program 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 program and study the output:
    ./lab2a.py
    

This Python program 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 program:
    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 http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2b
    
  • Make certain that you identify any and all errors in lab2b.py. When the check program 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 program, but this time, this argument will be passed when we execute your Python program 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 program 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 program arguments: ', arguments)
    print('Print out the program name: ' + name)
    print('Print out the number of arguments: ', len(sys.argv))
    
  • Examine the output by running the Python program 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 program 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 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 a part 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 program 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 program 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 program name as a argument.

Now it's time to create a new program. You will be modifying the previous Python program to provide a message if the user did NOT provide any argument when running the program, and abort the program 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 to make sure that lab2d.py has received '2' additional arguments. This check should be done before you attempt to use any of those 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 the program
  5. Use a variable called name
  6. Use a variable called age
  7. Use the value of sys.argv[1] (first argument)
  8. Use the value of sys.argv[2] (second argument)
  9. Store the values in the correct variables
  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 http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2d
    

if/elif/else

There are many ways to use IF statements in more advanced configurations. This section will provide a few more examples and provide an explanation of how they work.

For the following examples, try changing the numbers in the objects to get different results.

  • Create one or more new files for testing the following steps (you won't need to submit them).
  • Let's use an IF statement testing a condition of two object values. In this case, if object 'a' is greater than object 'b', then print a message, if False, do nothing:
    a = 10
    b = 15
    if a > b:
        print('a is greater than b')
    
  • Try the following code instead:
    a = 10
    b = 15
    if a > b:
        print('a is greater than b')
    else:
        print('b is greater than a')
    
    Change the values of a and b so you can get either printout. But what if 'a' is equal to 'b'? In order to account for that we could add another condition using the == operator, but that extra condition is unnecessary. The 'elif' statement allows us to string together multiple if statement. This new statement 'elif' means: IF the first expression is False, it will check the second expression under 'elif'. HOWEVER, if the first expression is True, it will run the code indented under the first expression and SKIP the 'elif' statement. Finally, we include the ELSE statement - in this case, if 'a' is equal to 'b' (i.e. fails first test since 'a' is not greater than 'b' and fails second test since 'a' is not less than 'b', so they must be equal to check other).
  • Modify your program to look like this:
    a = 10
    b = 10
    if a > b:
        print('a is greater than b')
    elif a < b:
        print('b is greater than a')
    else:
        print('a is not greater than b')
        print('a is not less than b')
        print('Therefore, a is equal to b')
    

while Loops

Loops are another universal programming technique. There are different types of loops, we will look at one of the simplest and most commond types: the while loop.

while loops use a the same type of conditions found in if statements. While the condition is True, the code indented under the while loop will be repeated. When the condition becomes False the loop will stop repeating.

  • Create a temporary python file for practicing with the following examples:
  • The while loop is not the most common type of loop in Python but it's the simplest. Below is a while loop which will run five times. Each time the loop is run, it will add one to the count variable, increasing the variables number:
    count = 0
    while count != 5:
        print(count)
        count = count + 1
    print('loop has ended')
    

Sometimes you know in advance how many times a loop will execute but often you don't. For example loops are extremely useful for error-checking in order to prevent incorrect data being accepted and causing the program not to perform correctly.

  • Here is an example of a loop used for error-checking. Run this code and type several incorrect passwords then the correct one to see what happens:
    password = ''
    while password != 'P@ssw0rd':
        password = input("Type in a password: ")
    print('Congratulations you guessed the correct password!')
    
  • Now it's time to create a new program. You will be creating an entirely new Python program to use a WHILE loop as a determinant loop. This while loop will count down from 10, print each value as it counts down. When it gets to the end it will output 'blast off!' Refer to Sample Runs displayed below for exact prompt and output requirements.
  • Make a new file called lab2e.py, this program will contain a while loop. Your program should:
  1. Have a Shebang line
  2. Use a variable named timer with a value of 10
  3. Have a while loop that repeats until timer equals 0
  4. Print the exact output as shown

Sample run:

./lab2e.py
10
9
8
7
6
5
4
3
2
1
blast off!
  • Download the check script and check your work. Enter the following commands from the bash shell.
    cd ~/ops435/lab2/
    pwd # confirm that you are in the right directory
    ls CheckLab2.py || wget http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2e
    
  • Make certain that you identify any and all errors in lab2e.py. When the check script tells you everything is OK, you may proceed to the next step.

Using while loops with program arguments

  • Make a copy of lab2e.py and call it lab2f.py.
  • Modify lab2f.py to change the initial value of the variable count to the value of the first argument when running your program.
Idea.png
Program arguments are strings
When using arguments as numbers/integers or performing math on arguments you must convert them to numbers using the int() function.
  • Your program should also:
  1. Have a Shebang line
  2. import sys
  3. Use a variable named timer with the value of int(sys.argv[1])
  4. Have a while loop that repeats until timer equals 0
  5. Print the exact output as shown

Sample run 1:

./lab2f.py 10
10
9
8
7
6
5
4
3
2
1
blast off!

Sample run 2:

./lab2f.py 3
3
2
1
blast off!
  • Download the check script and check your work. Enter the following commands from the bash shell.
    cd ~/ops435/lab2/
    pwd # confirm that you are in the right directory
    ls CheckLab2.py || wget http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2f
    
  • Make certain that you identify any and all errors in lab2f.py. When the check script tells you everything is OK, you may proceed to the next step.

Combining WHILE loops with IF statements

Let's improve upon your previous program to further prevent errors from incorrect input. You can combine logic flow-control statements with other LOGIC flow-control statements for more complex programming. For example, if you ran the previous Python program without an argument (i.e. empty string), you would encounter an error since it could not convert an empty string to an integer.

  • Make a copy of lab2f.py and call it lab2g.py.
  • Modify lab2g.py, and rename the count variable to timer.
  • Add an IF statement to the program which will check whether an argument was entered. If a argument was entered use that number for the timer, if no argument was entered, then by default, the timer should equal 3.
  • Your program sould also:
  1. Have a Shebang line
  2. import sys
  3. Use a variable named timer with the value of 3 if no arguments are entered
  4. Use a variable named timer with the value of int(sys.argv[1]) if arguments are entered
  5. Have a WHILE loop that repeats until (and not including when) timer equals 0
  6. Print the exact output as shown
Sample run 1:
./lab2g.py 5
5
4
3
2
1
blast off!
Sample run 2:
./lab2g.py 2
2
1
blast off!
Sample run 3:
./lab2g.py
3
2
1
blast off!
  • Download the check script and check your work. Enter the following commands from the bash shell.
    cd ~/ops435/lab2/
    pwd #confirm that you are in the right directory
    ls CheckLab2.py || wget http://ops345.ca/ops445/CheckLab2.py
    python3 ./CheckLab2.py -f -v lab2g
    
  • Make certain that you identify any and all errors in lab2g.py. When the check script tells you everything is OK, you may proceed to the next step.

Submit evidence of your work

Run the following command in a terminal:

cd ~/ops435/lab2
python3 ./CheckLab2.py -f
  • The output of the lab check command must say OK.
  • To show that you completed the lab, submit a screenshot of the terminal with that output.