Skip to content

Commit 695296d

Browse files
committed
origin master
1 parent 1a8dc8f commit 695296d

23 files changed

+728
-0
lines changed

labs/coding-103-python-json/1.md

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
# Coding 103: Coding with Python and Parsing JSON
2+
3+
In this Learning Lab you will learn the basics of how to write Python code and parse JSON.
4+
5+
6+
## Objective ##
7+
8+
Completion Time: 45 minutes
9+
10+
* Understand and apply the fundamentals of coding in Python
11+
* Learn how to parse simple to slightly complex JSON using Python
12+
13+
14+
## Prerequisites
15+
16+
**Background**
17+
* We recommend that you complete the [Coding 101 Rest Basics Learning Lab](/#/lab/coding-101-rest-basics-ga/step/1) before you start this lab.
18+
19+
**Access to an APIC-EM Controller**
20+
* To run these code samples, you will need access to an APIC-EM controller.
21+
* **If you are not using your own APIC-EM Controller**, use the [DevNet Sandbox](https://developer.cisco.com/site/devnet/sandbox/) Always-On APIC-EM Lab: https[]()://devnetapi.cisco.com/sandbox/apic_em .
22+
23+
**Python**
24+
* To run the code samples, you need to have Python 3 installed on your machine.
25+
* **If you are working on a DevNet Learning Lab PC at a DevNet event**, Python 3.x + is already installed.
26+
* See **How to Set up Your Own Computer** section above for how to install Python on your own machine.
27+
28+
**Python Requests Library**
29+
* Some of the code samples use the Python Requests Library to simplify making REST API calls.
30+
* **If you are working on a DevNet Learning Lab PC at a DevNet event**, the Requests Library is already installed.
31+
* See **How to Set up Your Own Computer** section above for how to install the Requests Library on your own machine.
32+
33+
34+
**Clone Git Repo**
35+
* **If you are working on a DevNet Learning Lab PC at a DevNet event**,
36+
* Open the Git Command window by clicking on the *Git CMD* icon on the Task Bar or click on the Start button, then in the Run bar type: **git cmd** and press the **Enter** key.
37+
* **If you are working from your own workstation**, on your desktop open a command terminal.
38+
* Go to the root directory by typing: `cd \`
39+
* Create a directory called 'C:\DevNetCode\yourname' by typing: `mkdir DevNetCode\<your-name>`
40+
* For example: `mkdir DevNetCode\brTiller`
41+
* Go to the new directory by typing: `cd \DevNetCode\<your-name>`
42+
* For example: `cd \DevNetCode\brTiller`
43+
* Clone the coding skills sample code from GitHub. Enter the command below.
44+
```
45+
git clone https://github.com/CiscoDevNet/coding-skills-sample-code
46+
```
47+
![](/posts/files/coding-103-python-json/assets/images/github-clone.png)<br/><br/>
48+
Inside the directory you created you should now see directory 'coding-skills-sample-code'.<br/><br/>
49+
![](/posts/files/coding-103-python-json/assets/images/github-clone-listing.png)<br/><br/>
50+
51+
## Step 1. Python Version, Scripts and Interpretor
52+
53+
### Checking Your Python Version
54+
55+
It's quite easy to check the version of Python installed on your system. Simply access a terminal window, then at the command prompt type: **python -V** and press the return key. If you have multiple versions of python installed on your system or python 3 you may need to type either **py -3 -V** or **python3 -V** depending upon your operating system. See the graphic below for details.
56+
![](/posts/files/coding-103-python-json/assets/images/python-version-os.png)<br/><br/>
57+
Here's an example of how to get the Python version.<br/><br/>
58+
![](/posts/files/coding-103-python-json/assets/images/python-version.png)<br/><br/>
59+
60+
61+
### Running Your Python Script
62+
To run a Python script is quite simple. At the terminal window command prompt enter **python** then enter the full name of the python script and press the return key. If you are not at the directory where the python script resides you will have to specify the full directory location of the script as well.
63+
![](/posts/files/coding-103-python-json/assets/images/python-script-os.png)<br/><br/>
64+
Here's an example of running a Python Script.<br/><br/>
65+
![](/posts/files/coding-103-python-json/assets/images/python-script.png)<br/><br/>
66+
67+
### Using the Python Interpretor
68+
At the command prompt you can enter the Python Interpretor by simply typing **python** and pressing the return key. Inside the Interpretor you can write and run very basic Python code. To exit type Cntrl-Z or quit().
69+
![](/posts/files/coding-103-python-json/assets/images/python-interpretor-os.png)<br/><br/>
70+
Here's an example of using the Python interpretor<br/><br/>
71+
![](/posts/files/coding-103-python-json/assets/images/python-interpretor.png)<br/><br/>
72+
73+
74+
75+
## Give it a try!
76+
77+
### Get the Python Version. Use the interpretor
78+
1. Open a terminal
79+
2. Enter the appropriate python command for your operating system to get the version. For example, in Windows you would type **python -V** then press the return key.
80+
3. Enter the appropriate python command to start the interpretor. For example, in Windows you would type **python** then press the return key.
81+
4. Enter **print("Hello World! How are you?")** and press the return key.
82+
5. To exit press the **Ctrl** key then **z** or enter **quit()**
83+
84+
### Run a Python Script
85+
1. Open a terminal and go to the directory you created earlier named: ** DevNetCode\&lt;your-name&gt;**
86+
* In the **Prerequisites section** you had cloned the source code files from the git repository into this directory. Inside the directory you created you should see subdirectory **coding-skills-sample-code**. If that subdirectory does not exist, go back to the prerequisites section and follow the steps to create the directory and clone the git repository.
87+
2. Go to directory **coding103-python-json**. In the terminal type:
88+
**cd \DevNetCode\&lt;your-name&gt;\coding-skills-sample-code\coding103-python-json**
89+
3. To run the script type the python command and then the filename at the command prompt, and press the return key.
90+
* *On Windows type*: **py -3 hello.py**. Or type: **python hello.py**
91+
* *On Mac OS or Linux type*: **python3 hello.py**
92+
4. The program should execute or display an error message.
93+
94+
**Next Step:** Learn about Python Data Types

labs/coding-103-python-json/2.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
## Step 2. Python - Scope, Variables, Operators and Simple Conditional Statements
2+
3+
In this step we'll cover the very basics of scope, variables and conditional statements.
4+
5+
### Python Basics
6+
7+
If you've written code in other languages you've noticed that statement blocks define scope (the range that a statement affects or variable exists) which is set by curly braces. These braces are used to define the start and end of the statement, and therefore, its scope. Python doesn't use curly braces to define scope. Instead it uses indentation. The indentation can be in the form of spaces or tabs, but must be consistent or the Python interpretor will complain.
8+
9+
Consider the Python code below.
10+
11+
``` python
12+
print ("Hello World!")
13+
num = 1
14+
if num < 1:
15+
print ("I'm less than 1!")
16+
print ("Goodbye Cruel World!")
17+
```
18+
1. On the first line we print to the screen the text Hello World! which is commonly what developers do when they write their first application.
19+
2. On the second line we create a variable which we call 'num' and assign it the value of 1. By the way we could have called that variable 'brett', 'a' and many other things. You can read more about [naming variables](http://www.thehelloworldprogram.com/python/python-variable-assignment-statements-rules-conventions-naming/).
20+
3. On the next line we check the value of the variable we called 'num' asking if it is less than 1? The less than symbol **'<'** is an operator. Python has many operator types with the most of commonly used being [Comparison, Assignment and Arithmetic](http://www.tutorialspoint.com/python/python_basic_operators.htm). This ['if' statement](http://www.openbookproject.net/books/bpp4awd/ch04.html) is called a *conditional statement* because we are checking a condition. If the condition is true, then whatever is inside the scope of the conditional statement gets executed; otherwise it all gets skipped.
21+
4. Notice that the next two statements are indented. That indentation signifies that they are inside the scope of the conditional statement.
22+
23+
### Quiz. Scroll Down for Answers
24+
1. If the python code above were run, what would be printed to the screen?
25+
2. If you unindented the line print("Goodbye Cruel World!") what would be printed to the screen?
26+
3. If you only changed the value of num to 0, what would be printed to the screen?
27+
<br/>
28+
<br/>
29+
<br/>
30+
<br/>
31+
32+
### Answers
33+
<ol>
34+
<li>Hello World!
35+
<li>Hello World! Goodbye Cruel World!
36+
<li>Hello World! I'm less than 1! Goodbye Cruel World!
37+
</ol>
38+
39+
40+
## Give it a try!
41+
42+
1. Open a terminal and go to the directory created back in Step 1 named: ** DevNetCode\&lt;your-name&gt;**
43+
* In the **Prerequisites section** of Step 1 you had cloned the source code files from the git repository into this directory. Inside the directory you created you should see subdirectory **coding-skills-sample-code**. If that subdirectory does not exist, go back to the Step 1 prerequisites section and follow the steps to create the directory and clone the git repository.
44+
2. Go to directory **coding103-python-json**. In the terminal type:
45+
**cd \DevNetCode\&lt;your-name&gt;\coding-skills-sample-code\coding103-python-json**
46+
3. To run the script type the python command and then the filename at the command prompt, and press the return key.
47+
* *On Windows type*: **py -3 helloworld.py**. Or type: **python helloworld.py**
48+
* *On Mac OS or Linux type*: **python3 helloworld.py**
49+
4. The program should execute or display an error message.
50+
51+
#### Make these changes and run the helloworld.py script.
52+
1. Open the file **helloworld.py**. For example, in Windows type: **notepad helloworld.py**
53+
2. Make the change specified in the instructions in question 2 of the Quiz.
54+
3. Save the file. If encoding type is an option select **UTF-8**.
55+
4. Run the script.
56+
5. Repeat steps 1 - 4, but make the change specified in the instructions in question 3 of the Quiz.
57+
58+
#### Write your first program
59+
1. Create a file called myworld.py .
60+
2. Write python code that does the following:<br/>
61+
a. Assigns a value to a variable<br/>
62+
b. Checks the value in the variable “Remember if (variable < value):”<br/>
63+
c. Prints statements within the *if conditional block* when the condition is true. Statements under the if conditional statement must be indented!<br/>
64+
65+
66+
67+
**Next Step:** Learn about Python Data Types

labs/coding-103-python-json/3.md

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# Step 3. Python Data Types
2+
3+
In this step we'll explore Python data types. There are many data types listed in the figure below. There are simple numeric ones like **integers** and **floats**. For our purposes the differences between a **float** and an **integer** is that a **float** has a decimal in it. For example 52.856 is a **float** while 52 is an **integer**. **Boolean** data types can only be either True or False. **Text** is a data type with a non-numeric value. **Text** is more commonly called **string**. For example: "brett" is a **string**, so is 'brett123', but 123 is an **integer**.
4+
5+
![](/posts/files/coding-103-python-json/assets/images/python-datatypes.png)
6+
7+
There are also more complex data types such as list, tuples and dictionaries. Let's delve into these types.
8+
9+
A [**list**](http://www.tutorialspoint.com/python/python_lists.htm) contains any number of sequential elements and is defined by square brackets []. Here's a list *['Martha','Betty',5]* . Assigning a list to a variable is as simple as *var=['Martha','Betty',5]*. Lists are mutable which means that they can be changed. You can add data to a list, modify and delete it or even sort it. Notice that lists can have different data types inside them.
10+
11+
A [**tuple**](http://www.tutorialspoint.com/python/python_tuples.htm) contains any number of sequential elements and is defined by parenthesis (). Here's a tuple *('Brett',9,'Cisco')*. Assigning a tuple to a variable is simple: *var1=('Brett',9,'Cisco')*. Tuples are similar to lists, but they are immutable which means they cannot be changed. You might use a tuple to group similar data. For example, referring to the tuple defined above the similarity is that my name is Brett and I've worked at Cisco for 9 years. Because tuples are immutable they are more efficient meaning that their data can be accessed more quickly than lists.
12+
13+
While lists and tuples are defined a little differently, they both have their data accessed the same manner which is by square brackets []. The first data element always starts at position zero. In the example in the list that was defined earlier if I entered the python statement **print(var[0])**, it would display *Martha*. If I entered the python statement **print(var[1])**, it would display *Betty* and so on. The same syntax applies to tuples. For the tuple defined above if I entered the python statement **print(var1[0])**, it would display *Brett*. If I entered the python statement **print(var1[1])**, it would display *9* and so on
14+
15+
A [**dictionary**](http://www.tutorialspoint.com/python/python_dictionary.htm) is a different than lists and tuples. Each element in a dictionary must contain a key followed by a value. This key value association is typically referred to as *name value pairs*. Dictionaries are defined by curly braces {}. Here's a dictionary *{"car":"corvette","age":7, "food":"pizza"}* . Assigning a dictionary to a variable is simple: *myvar={"car":"corvette","age":7, "food":"pizza"}* . The value in a dictionary is accessed by its key. For example if I entered the python statement **print(myvar["car"])**, it would display *corvette*. If I entered the python statement **print(myvar["food"])**, it would display *pizza* and so on. Dictionaries are sometimes also called *maps* or *associative arrays* .
16+
17+
18+
Examples of how to define each Python data type is shown in the table below.
19+
![](/posts/files/coding-103-python-json/assets/images/python-datatypes2.png)
20+
21+
22+
## Give it a try!
23+
1. In Step 2 you created and ran python script myworld.py . Now let's add to this script.<br/>
24+
a. Add a list with two elements and assign it to a variable.<br/>
25+
b. Add a tuple with three elements and assign it to a variable..<br/>
26+
c. Add a dictionary with two name value pairs and assign it to a variable..<br/>
27+
d. Print one value from each data type you created.<br/>
28+
29+
2. Now open file data-types-values.py . Which values should be displayed for each data type? Run the script to check your answers.
30+
31+
3. Modify the file data-type-values.py to create errors. For example, change the line *print(my_dict["green"])* to *print(my_dict["mean"])* . What error is displayed?
32+
33+
**Next Step:** Learn about JSON and How to Parse it Using Python

labs/coding-103-python-json/4.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Step 4. Parsing JSON With Python
2+
3+
We are going to build on your new knowledge of Python data types, and learn about JSON and how to parse it with Python. [JSON](http://www.json.org/) which stands for **Java Script Object Notation** consists of text-based name-value pairs making it simple for applications to store and exchange data. It's designed to be lightweight and readable as well as minimal so there's not excessive text which is sometimes been the complaint of [XML](http://www.w3schools.com/xml/xml_whatis.asp) which is another text-based option for exchanging and storing data.
4+
5+
The structure and parsing of JSON is very similar to Python dictionaries and lists.
6+
<ol>
7+
<li> In JSON data is set up in name value pairs just like a Python dictionary. However, in JSON dictionaries are called objects. For example, **{"car":"volvo", "fruit":"apple"}** is a JSON object. The object is assigned to a variable in the same manner as well: **var={"car":"volvo", "fruit":"apple"}**. In addition, data is accessed the same way as when accessing data in a dictionary. For example, to get the value for **fruit** we would enter **var["fruit"]** which would return **apple**. To display this value we enter **print(var["fruit"])** .</li><br/>
8+
9+
<li> As with Python JSON also uses **lists** which it calls **arrays**. In JSON an array is typically nested in an object. For example, **{"donut":["chocolate","glazed","sprinkled"]}** . Let's assign this object to a variable: **var1={"donut":["chocolate","glazed","sprinkled"]}**. If I wanted to get the chocolate donut, (you're getting hungry aren't you?), I would access it by entering **var1["donut"] [0]** which would return **chocolate** because it is the first element in the array. I could display the text by entering **print(var1["donut"] [0])**.</li><br/>
10+
11+
<li> JSON can also nest objects in objects with arrays inside. For example: **{"donut":{"flavors":["chocolate","glazed","sprinkled"]}}**. In this case to get the chocolate donut we need to dig a little deeper. First we assign it to a variable **myvar={"donut":{"flavors":["chocolate","glazed","sprinkled"]}}** . We access *chocolate* by entering **myvar["donut"]["flavors"][0]** . We can display it by entering **print(myvar["donut"]["flavors"][0])** . For viewing purposes JSON is typically formatted to separate data types from each other to make it easier to read. So the example above would typically look like the picture below, but is still parsed the same way.</li><br/>
12+
13+
![](/posts/files/coding-103-python-json/assets/images/json.png)<br/><br/>
14+
15+
<li> JSON will also include objects inside a list. For example: **{"type":"donut","flavors":{"flavor":[{"type":"chocolate","id":"1001"}, {"type":"glazed","id":"1002"},{"type":"sprinkled","id":"1003"}]}}**. So we need to dig a little deeper still to get our chocolate donut. First we assign it to a variable **myvar1={"type":"donut","flavors":{"flavor":[{"type":"chocolate","id":"1001"}, {"type":"glazed","id":"1002"},{"type":"sprinkled","id":"1003"}]}}** . We access *chocolate* by entering **myvar1["flavors"]["flavor"][0]["type"]** . We can display it by entering **print(myvar1["flavors"]["flavor"][0]["type"])**. As mentioned earlier for viewing purposes JSON is typically formatted. The example above would typically look like the picture below, but is still parsed the same way.</li>
16+
</ol>
17+
18+
![](/posts/files/coding-103-python-json/assets/images/json2.png)
19+
20+
### Quiz. Scroll Down for Answers
21+
22+
fruit={"cherry":"red", "lemon":"yellow", "lime":"greeen"}
23+
24+
food={“vegetables”:[“carrots”,“kale”,“cucumber”,”tomato”]}
25+
26+
cars={“sports”:{“porsche”:“Volkswagon”,“Viper”:“Dodge”,“Corvette”:“Chevy”}}
27+
28+
donut={"type":"donut","flavors":{"flavor":[{"type":"chocolate","id":"1001"}, {"type":"glazed","id":"1002"},{"type":"sprinkled","id":"1003"}]}}
29+
30+
Write the code to access and then display the requested items below
31+
1. Access the value for "lemon" from the fruit variable.
32+
2. Access "tomato" from the food variable.
33+
3. Access the value for "Viper" from the cars variable.
34+
4. Access the glazed value from the donut variable.
35+
<br/>
36+
<br/>
37+
<br/>
38+
39+
### Answers
40+
<ol>
41+
<li>fruit["lemon"] print(fruit["lemon"])
42+
<li>food["vegetables"][3] print(food["vegetables"][3])
43+
<li>cars["sports"]["Viper"] print(cars["sports"]["Viper"])
44+
<li>donut["flavors"]["flavor"][1]["type"] print(donut["flavors"]["flavor"][1]["type"])
45+
</ol>
46+
47+
48+
## Give it Try!
49+
1. Go to directory \DevNetCode\&lt;your-name&gt;\coding-skills-sample-code\coding103-python-json
50+
2. Open file **json_parse-1.py**
51+
3. Write Python code to print out one value for each of the json objects. Run the code.
52+
53+
54+
**Next Step:** Learn how to write loops in Python.

0 commit comments

Comments
 (0)