Changes

Jump to: navigation, search

OPS435 Python Lab 2

804 bytes removed, 14:16, 21 January 2019
LAB REVIEW
:Write Python code in order to:
:*'''Accept information data from users''' that run a Python script, such as a username or password.
:*'''Process the inputted informationdata''' using '''Conditional Statements'''.:::This means that the program will completely change how it works behaves based on the input given, an example would be, providing the correct password or providing the wrong password.
:*'''Process the inputted informationdata''' using '''Looping Statements'''.:::Looping (iteration) is the ability for your program to repeatedly run the same code block of codes over and over. An example of this, could be found when you provide the incorrect password to a login page and it responds with, 3 attempts to login remaining.
<br><br>
== PART 1 - User Input ==
:In this section, you will learn how to prompt (ask) the user running the program python script for input or data. Although you will not be immediately be using the information data that the user provided, you will use that information data later in this lab to change how a Python script works in different situations.
'''Storing User Input In Variablesdata to Python objects'''
:'''Perform the following steps:'''
:#Launch your Centos VM, open your code editor, and a a shell terminal (as a regular user) for executing your code.
:#To begin, let's start out with a very basic script. This script will use variables objects that will display specific information values to your terminal. Create the file '''lab2a.py''' in your '''~/ops435/lab2''' directory, containing the following content:<source lang="python">
#!/usr/bin/env python3
print('Hi ' + name + ', you are ' + str(age) + ' years old.')
</source>
:#Try running this script inside ipython3 and study the output:<source>
./lab2a.py
</source>This Python script is not very useful: it displays the same output regardless of the number of times that the Python script is run.<br>The '''input()''' function is used to obtain information from the user and store it into an object (also called a variable). It is typical to place a question (or hint) as a argument in the input() function: this will aid the user in typing in the correct informationdata.<br><br>
:#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): <source lang="python">
colour = input("Type in a colour and press enter: ")
:#Add another line to your script:<source lang="python">print(colour)
</source>What was displayed?
:And #Now replace that line wiht with this:<source lang="python">print('The colour I typed in is: ' + colour)
</source>Note what was displayed.
:#Now 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 directory
ls CheckLab2.py || wget https://raw.githubusercontent.com/Seneca-CDOT/ops435/master/LabCheckScripts/CheckLab2.py
python3 ./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''' before proceeding to the next step.
''' Practice Storing User Input data '''
:Now it's time to create a new script to prompt the user to enter data and display that data on their terminal. Refer to variable object name and prompt text information when creating your Python script. Refer to Sample Runs displayed below for exact prompt and output requirements.
:'''Perform the following Instructions:'''
:::*The script should have a '''Shebang line'''
:::*The script should use a variable an object called '''name''':::*The script should use a variable an object called '''age'''
:::*The script should prompt the user for "Name: "
:::*The script should prompt the user for "Age: "
:::*The script should store the values in the correctly spelled variables objects (case sensitivity counts)
:::*The script should print the EXACT OUTPUT as shown (case sensitivity counts)
== PART 2 - Arguments ==
:An argument is a value 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.
'''Perform the following steps:'''
:#Access Use a temporary file for testing your ipython3 shellwork for this section.:<source lang="bash">ipython3</source>#In order to read arguments in Python, we will need to '''import special variablesobjects''' from the system. This is a standard 'library' of code provided by the developers of Python. By issuing '''import sys''', you have loaded code written by another person, each 'library' that gets loaded will give us extra functionality in and objects to our program. This is done by issuing the import sys function within your ipython3 shell.<br><br>:#Issue Start with the following line to access your ipython3 shell and import special variablesadditional python objects:<source>
import sys
</source>
:#To inspect this library, and look at all that it contains, we can use the '''dir()''' function. This can be used to inspect any library (in fact, inspect other items other than libraries) in order to refer to functions and values that are available. Issue the following function:<source>dir(sys)</source>You may feel overwhelmed with all of this information, but not to worry, there are additional tools and tips on how to obtain information regarding these functions contain in the library.<br><br>:#Issue Call the following functions and note what they do:<source lang="python">print(sys.version) # tells us our the version of the python versioncurrently 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 user provide issued from 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 '''sys.argv''' function <b>list object</b> to store data as a result of running the Python script with arguments. The list object '''sys.argv''' function, when used within your Python script can store the following:<ul><li>'''sys.argv''' - stores all argument dataitems</li><li>'''sys.argv[0]''' - stores the name of the script/program</li><li>'''sys.argv[1]''' - stores the first argument</li><li>'''sys.argv[2]''' - stores the second argument</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
print('Print out ALL script arguments: ', arguments)
print('Print out the script name: ' + name)
print('Print out the number of argument: ', len(sys.argv))
</source>
./showargs.py
./showargs.py testing different arguments
./showargs.py argument1 argument2 argument3argument4
</source>
= INVESTIGATION 2: USING CONDITIONAL STATEMENTS =
:In computer programming, control flow statement can be used to change the direction (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 script runs, based entirely on input data (either user via the input() function, or command argumentsvia the list object sys.argv). In this section, we will discuss several LOGIC control flow statements including: IF, and IF/ELIF/ELSE.
== PART 1 - Using IF Statements ==
:'''Perform the following steps'''
:#Open an ipython3 shell:<source lang="bash">ipython3</source>Create a temporary python file for testing things in this section.:#Let's create an if statement from the ipython3 shell.<br>Issue Try the following 2 lines, indenting the second line (you may need to press ENTER a second time for statement to execute):<source lang="python">
if True:
print('This print is apart of the if statement')
</source>What happenedwhen you ran this code? It is important to note a couple of things with the IF statement:<ul><li>When the condition 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 condition expression determined true or false.</li><li>However, if the If expression evaluates to '''False''', then it will not run the code indented underneath it. Any code not indented under the if statement will perform normally as the main program and is NOT associated with 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 run as part of the IF statement and which code will run as part of the main programregardless. Also, using indentation makes it easier for a programmer to identify Control Flow statements. From this point on, be VERY careful and consistent in the with indentation that you make with conditional statementsbecause it will affect how your code works. </li></ul><br>However, if the If condition evaluates to '''False''', then it will not run the code indented underneath it. Any code not indented under the if statement will perform normally as the main program and is NOT associated with control flow statement.
<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>
 :#Issue <ol><li value='3'>Try the following 3 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')
print('This second print statement will also not run')
print('This print statement will run')
</source>What do you notice?<br><br>So far, you have been using only the '''Boolean values True or False''' for your IF statements. Although this can be useful, it can be more practical to state a condition to test in order an expression that will be evaluated to render a '''True''' or '''False''' Boolean value to be used with control flow statements (referred to as: '''Boolean Logic''').<br><br></li>:#<li>let's create an IF statement that runs under specific conditions. Issue the following code below:<source lang="python">
password = input('Please enter a secret password')
if password == 'P@ssw0rd':
print('You have succesfully used the right password')
</source>What happened? In the above example, you are making a comparison between the value you entered via the '''input()''' function, which in turn, was saved into the '''password''' variableobject. The IF statement is using that variable object (called named password), followed by '''==''' which represents '''identical to''', followed by the string ''' 'P@ssw0rd' '''. Never use '''=''' to 'compare values since this is used to store the value into a variable an object and may not allow IF statement to properly test evaluate the conditionexpression! Also note that a '''space is used to separate arguments with the IF statement'''. The IF statement tests that condition expression to see if it is '''True or False'''. If that condition expression is '''True''', it will run the code indented below. On the other hand, if that condition expression is '''False''', it will not run the code. Try experimenting with different combinations of passwords.<br><br>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 variablesobjects. 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. <br><br></li>:#Issue <li>Try the following lines of codeprogram:<source lang="python">
import sys
sys.exit()
</source>What happened?</li></ol>
<blockquote style="margin-left:35px;">{{Admon/important|style="padding-left:25px"|Number of Arguments with len(sys.argv)|If you are running calling the '''len()''' function with the '''sys.argv)''' function in ipython3argument, 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.}}</blockquote>
''' Practice Using IF Statements'''
:::*The script should print a '''usage message''' if zero arguments present, or if not exactly 2 arguments are provided when running the script<br>(NOTE: Use '''sys.argv[0]''' value in this message in case you rename the script at a later date!)
:::*The script should exit without attempting to do any more work if exactly 2 arguments are not provided when running script
:::*The script should use a variable an object called '''name''':::*The script should use a variable an object called '''age'''
:::*The script should use '''sys.argv[1]''' (first argument)
:::*The script should use '''sys.argv[2]''' (second argument)
:::*The script should store the values in the correct variablesobjects
:::*The script should print the EXACT OUTPUT as shown
: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 variables 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 perform use an IF statement testing a condition of two variable object values. In this case, if variable object 'a' is greater than variable object 'b', then print a message, if False, do nothing.<source lang="python">
a = 10
b = 15
print('a is greater than b')
</source>What happened? Let's now use an IF/ELSE statement.<br><br>
#Issue Try the following at the ipython3 shellcode instead:<source lang="python">
a = 10
b = 15
else:
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 condition expression is False, it will check the second condition expression under 'elif'. HOWEVER, if the first condition expression is True, it will run the code indented under the first condition 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
print('Therefore, a is equal to b')
</source>
#You are NOT required to create a Python script for this section or run the checking script. Proceed to INVESTIGATION 3.
<br><br>
= INVESTIGATION 3: USING LOOP STATEMENTS =
:::'''Sample run 1:'''<source>
run ./lab2f.py 10
10
9
</source>
:::'''Sample run 2:'''<source>
run ./lab2f.py 3
3
2
</source>
:::4. Before proceeding, make certain that you identify any and all errors in '''ab2flab2f.py'''. When the check script tells you everything is '''OK''', you may proceed to the next step.
<br><br>
= LAB REVIEW =
:# Write a short Python function script to input ask the user for to provide their shoe sizeat the keyboard, and store the result in a variable an integer object called '''shoeSize'''.:# Write a Add codes to the previous Python function script to display the shoe size entered from using the value stored in the variable mentioned in the previous questionsame integer object created. (For example: '''Your size size is: 16''').:# What is the purpose of importing special variables module from your system?:# Write a function 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>
:# What is the purpose of using an '''if''' statement?
:# What is the purpose of using an '''if-else''' statement?
:# Write a short Python code to terminate script which terminates the execution of the running Python script if there are not exactly 3 arguments contained after given at the Python script upon executioncommand line.
:# What is the purpose of an '''if-elif-else''' statement?
:# Write a Python script to prompt the user for a course mark (no error checking is required... you can assume that the input will be a valid mark from 0 to 100). Use an if-elif-else statement to convert the mark to a letter grade. For simplicity, you don't have to worry about D+, C+, B+, or A+
:# Write a Python script to print the text '''I love Python''' twenty times (on a separate line).
:# Identify and list the Python 3 keywords used in this lab.
:# Identify and list the Python 3 built-in functions used in this lab. (hint: the functions provided by the __builtins__ module)
:# '''INTERESTING CHALLENGE:''' Perform a Netsearch to see how you can write Python code to perform error-checking (using a loop) to force a user to enter a number for the shoe size script (created in question #2). There are two things to consider:<ol type="a"><li>A number as opposed to a string</li><li>It has to be an acceptable range from 1 to 20</li></ol>
[[Category:OPS435-Python]]
1,760
edits

Navigation menu