Open main menu

CDOT Wiki β

Changes

OPS435 Python3 Lab 2

2,650 bytes added, 14:27, 24 January 2020
m
LAB REVIEW
[[Category:rchan]][[Category:OPS435-Python]= Under construction - DO NOT USE - not ready yet! =]
= LAB OBJECTIVES =
:'''<u>Objectives</u>'''
:Learn the following python topics:
:*'''builtin functions:''' input(), print(), len(), str(), int()
:*'''builtin module:''' sys - special list object sys.argv
:*'''flow control statements and block:''' if, if/else, if/elif/else, while
:*'''code indentation''' - 4 spaces (avoid using tabs)
:Write Python code in order to:
 
:*'''Accept data from users ''' at the command line, such as name and age.
 
:*'''Prompt the user to provide specific data''' from the stdin (standard input channel), such as a username or password.
 
:*'''Process the inputted data''' using '''Conditional Statements'''.
:::This means that the program will change how it behaves based on the input given, an example would be, providing the correct password or providing the wrong password.
 
:*'''Process the inputted data''' using '''Looping Statements'''.
:::Looping (iteration) is the ability for your script to repeatedly run the same block of codes over and over until a given condition is met. For example, an authentication process would allow your 3 attempts to provide the correct password, and it will deny you access after 3 attempts have been tried and failed.
:#Try running this script and study the output:<source>
./lab2a.py
</source>This :#Download the checking script and check your work. Run the following commands from the bash shell.<source lang="bash">cd ~/ops435/lab2/pwd #confirm that you are in the right directoryls CheckLab2.py || wget https://ict.senecacollege.ca/~raymond.chan/ops435/labs/LabCheckScripts/CheckLab2.pypython3 ./CheckLab2.py -f -v lab2a</source>:# Before proceeding, make certain that you identify any and all errors in '''lab2a.py'''. When the check script tells you everything is '''OK''', you may procede to the next step.:#The above Python script '''lab2a.py''' is not very useful - the data are '''hard wired''' into the script: it displays the same output regardless of the number of times that the this Python script is run.<br>The built-in '''input()''' function can be used to accept data in '''string form''' from the user and assign a name to the string object (used to be called a variable). It is typical to place a question (or hint) as a an argument in the input() function: this will aid the user in typing in the correct data.<br><br>:#Replace Copy lab2a.py to lab2a1.py and replace the print() call in your lab2alab2a1.py with the following (you can just comment-out the print() call using a '''#''' at the beginning of the line): <source lang="python">
colour = input("Type in a colour and press enter: ")
</source>
print(len(sys.argv)) # tells us the number of command line arguments the user provide from a command shell
sys.exit() # will immediately end the running Python script, ignoring the remaining lines in the Python script
</source><br>Instead of using the '''input()''' function to prompt the user for data, we can use the list object '''sys.argv''' to capture the data items provided at the command line when a Python script is being executed. The list object '''sys.argv''', when used within your Python script can store the following:<ul><li>'''sys.argv''' - stores all argument items as string objects</li><li>'''sys.argv[0]''' - stores the name of the script/program</li><li>'''sys.argv[1]''' - stores the first argumentas a string object</li><li>'''sys.argv[2]''' - stores the second argumentas a string object</li><li>etc...</li><li>'''len(sys.argv)''' - gives the number of arguments</li></ul><br>
:#Create a new script called '''~/ops435/lab2/showargs.py''' and add the following content:<source lang="python">
#!/usr/bin/env python3
= INVESTIGATION 2: USING CONDITIONAL STATEMENTS =
:In computer programming, control flow statement can be used to change the direction execution path (flow) of a program. The [https://en.wikipedia.org/wiki/Flowchart diagram here] may help you visualize it. In this section, you will focus on LOGIC control flow statements that are used to change the way each statement in a script runs, being executed. The flow may be based entirely on input data (either via the input() function, or command arguments via the list object sys.argv)provided by the user. In this section, we will discuss several LOGIC control flow statements including: IF, and IF/ELIF/ELSE.
== PART 1 - Using IF Statements ==
if True:
print('This print is apart of the if statement')
</source>What happened when you ran this code? It is important to note a couple of things with the IF statement:<ul><li>When the expression in an IF statement '''evaluates to True''', it runs the code that is indented underneath it. In this case, we can use the boolean value "True" to make this happen, or test to see if a an expression determined is evaluated to true or false.</li><li>However, if the If expression in an IF statement evaluates to '''False''', then it will not run the code indented underneath it. Any code not indented under the if IF statement will perform normally as the main program and is NOT associated with the control flow statement.</li><li>Indentation means to start a line with spaces or tabs before your text. Using '''indentation''' will direct the script what code will should be run as part of the IF statement and which code will should be 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. </li></ul>
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|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 for spaces instead of a tab when you press the tab key.}}</blockquote>
<ol><li value='3'>Try the following 3 4 lines, indenting the second and third lines, but NOT the fourth line:<source lang="python">
if False:
print('This first print statement will never run')
:::*The script should use an object called '''name'''
:::*The script should use an object called '''age'''
:::*The script should use assign the string '''sys.argv[1]''' (first argument)to the object "name" :::*The script should use assign the string '''sys.argv[2]''' (second argument):::*The script should store the values in to the correct objectsobject "age"
:::*The script should print the EXACT OUTPUT as shown
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://rawict.githubusercontentsenecacollege.comca/Seneca-CDOT~raymond.chan/ops435/masterlabs/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2d
</source>
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2d.py'''. When the check script tells you everything is '''OK''', you may procede proceed to the next step.
== PART 2 - Using IF/ELIF/ELSE Statements ==
#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 wondon't need to submit them).#Let's use an expression in an IF statement testing to test a condition of two object values. In this case, if we have two integer objects 'a' and 'b'. If object 'a' is greater than object 'b', then print a message, if False, do nothing.<source lang="python">
a = 10
b = 15
print('b is greater than a')
</source>What happened?<br><br>This is neat, but what if 'a' is equal to 'b'? In order to make this work, we would need to perform another test! 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).<br><br>
#Modify your program to looks like this:<source lang="python">a = 10
b = 10
if a > b:
= INVESTIGATION 3: USING LOOP STATEMENTS =
:In the first two labsinvestigations, you have been exposed to tools builtin function and methods special list object to write powerful Python scripts. In Lab1Part 1 of the first investigation, this included includes using using variablesinteger and string objects. In Lab Part 2 you learned how to input variables get data from the user by either prompting the user for data using the input () function or get it from the command line using data that are arguments containing the sys.argv list object within a Python script that you run. You also learned about LOGIC control-flow statements in order to make the Python script behave differently based on differing inputdifferent condition.
:You will start to learn about the second major category of control flow statements by learning how to repeat repeatedly executing a command python statement or a series of commandspython statements. Although, you will be learning other scripting techniques, the ability to know how to use variablesdifferent objects, CONDITIONAL and LOOPING control-flow statements will allow you to create useful and powerful programs script to assist you when managing your computer system (including virtual machines).
== PART 1 - Understanding WHILE Loops ==
:'''WHILE loops''' may use a the same type of conditions expression found in if IF statements. While the condition expression is evaluated to True, the code indented under the while loop will be repeated. When the condition expression becomes False the loop will stop repeatingthe indented code.
:'''Perform the following steps'''
:#Create a temporary python file for practicing practising with the followin following examples.:#A '''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 integer count variableobject, increasing the variables numbervalue of the count object:<source lang="python">
count = 0
while count != 5:
count = count + 1
print('loop has ended')
</source>Sometimes you know in advance how many times a loop will execute , this is referred as a determinant loop, 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 script not to perform correctly.<br>
:#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:<source lang="python">
password = ''
:::*The script should have a Shebang line
:::*The script should have a comment line which contains the word "Author:" and your '''full name''':::*The script should have another comment line which contains the word "Author ID:" and your '''seneca_id''':::*The script should have another comment line which contains the word "Date Created:" and the actual date in "yyyy/mm/dd" format:::*The script should use a variable an integer object named timer with a value of 10
:::*The script should have a while loop that repeats until timer equals 0
:::*The script should print the EXACT OUTPUT as shown
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://rawict.githubusercontentsenecacollege.comca/Seneca-CDOT~raymond.chan/ops435/masterlabs/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2e
</source>
== PART 2 - Using WHILE loops with script arguments ==
:You will now learn to make your Python scripts more flexible by using getting numbers as arguments to be used with WHILE loopsin your script. You will learn that all command line arguments used in Python scripts captured by using the special object sys.argv are all strings (not numbers) and therefore. Even the item provided at the command line is a pure number, it cannot be used in Mathematical operations unless they are it is converted into numbers (like an integer)object. You will be learning how to use the int() builtin function in order to convert a numeric string object into an integerobject.
:'''Perform the Following Steps:'''
:#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 first command line argument when running your Python script. '''WARNING:''' When using arguments as numbers/integers or performing math on arguments you must wrap them in the int() function, for example: '''count = int(sys.argv[1])'''
:::'''Additional Input / Output / Processing Requirements'''
:::*The script should have a '''Shebang line'''
:::*The script should have a comment line which contains the word "Author:" and your '''full name'''
:::*The script should have another comment line which contains the word "Author ID:" and your '''seneca_id'''
:::*The script should have another comment line which contains the word "Date Created:" and the actual date in "yyyy/mm/dd" format
:::*The script should '''import sys'''
:::*The script should use a variable named timer with assign the value of '''int(sys.argv[1])''' to an object named timer
:::*The script should have a while loop that repeats until timer equals 0
:::*The script should print the EXACT OUTPUT as shown
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://rawict.githubusercontentsenecacollege.comca/Seneca-CDOT~raymond.chan/ops435/masterlabs/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2f
</source>
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2dlab2f.py'''. When the check script tells you everything is '''OK''', you may proceed to the next step.
== PART 3 - Combining WHILE loops with IF statements==
:Let's improve upon your previous shell python script to further prevent errors from incorrect command line input. You can combine LOGIC control-flow statements with other LOGIC control-flow statements for more complex programming. For example, if you ran the previous Python script without an argument (i.e. empty string), you would encounter an error since it could not convert an empty string to an integer.
:''' Perform the Following Steps '''
:::*The script should have a '''Shebang line'''
:::*The script should have a comment line which contains the word "Author:" and your '''full name'''
:::*The script should have another comment line which contains the word "Author ID:" and your '''seneca_id'''
:::*The script should have another comment line which contains the word "Date Created:" and the actual date in "yyyy/mm/dd" format
:::*The script should '''import sys'''
:::*The script should use a variable named assign the value of '''timer3''' with the value of to an object named '''3timer''' if when there is '''no arguments''' are entered provided. :::*The script should use a variable named timer with assign the value of '''int(sys.argv[1])''' if an object named '''argumentstimer''' when one command line argument (sys.argv[1]) are entered
:::*The script should have a WHILE loop that repeats until (and not including when) timer equals 0
:::*The script should print the EXACT OUTPUT as shown
cd ~/ops435/lab2/
pwd #confirm that you are in the right directory
ls CheckLab2.py || wget https://rawict.githubusercontentsenecacollege.comca/Seneca-CDOT~raymond.chan/ops435/masterlabs/LabCheckScripts/CheckLab2.py
python3 ./CheckLab2.py -f -v lab2g
</source>
:::4. Before proceeding, make certain that you identify any and all errors in '''lab2flab2g.py'''. When the check script tells you everything is '''OK''', you may proceed to the next step.
<br><br>
:'''Be able to answer any questions about the lab to show that you understood it!'''
 
:<span style=color:green;font-size:1.5em;">&#x2713;</span> Submit the CheckLab2.py script output and all your Python scrips for this lab via Blackboard by the due date for Lab 2.
= LAB REVIEW =
:# Write a short Python script to ask the user to provide their shoe size at the keyboard, and store the result in an integer object called '''shoeSize'''.
:# Add codes to the previous Python script to display the shoe size entered using the same integer object created. (For example: '''Your size shoe size is: 16''').
:# What is the purpose of importing special module from your system?
:# Write a short Python script to display two arguments from running your Python script.<br>For example if your Python script was called '''myscript.py''' and you issued the command:<br>'''python myscript.py happy afternoon''', you would get the following output:<br><br>The first argument is: happy<br>The second argument is afternoon<br><br>
14
edits