Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python Jumpstart.

Similar presentations


Presentation on theme: "Python Jumpstart."— Presentation transcript:

1 Python Jumpstart

2 Why do I care about the version?
Python Commands

3 Python Syntax, Data Types, Functions, …
Indentation defines scope Python code blocks do not have explicit statement scope delimiters Indentation amount is relative Data Types Statements Import Print Conditional Functions Looping Briefly discuss each item

4 Python Data Types A list contains any number of sequential elements and is defined by square brackets []. Here's a list ['Martha','Betty',5] which contains strings and an integer. 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, delete it or even sort it. Notice that lists can have different data types inside them A tuple 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') which contains strings and an integer. 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. 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, var=['Martha','Betty',5], 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, var1=('Brett',9,'Cisco'), 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 A dictionary is a different than a list or a tuple. 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 .

5 Python Data Types - Examples

6 Python Scope and Conditions
In your IDE or terminal window type the following commands at the end of your program and then run it to see the output: # This is a comment print() print ("Helloworld!") num = 1 if num < 1: print ("I'm less than 1!") print ("Goodbye Cruel World!") ← Comments aren't printed ← Blank lines are nice for formatting ← This simply prints a blank line ← prints "Helloworld!" ← Assigns the value 1 to variable "num" ← Note the conditional ends with a : ← Note indentation (be consistent) ← Nothing happens. Why? What happens if num = 0, 1, or >1? Python uses indentation to define scope. Discuss what gets printed, conditional statements and changes such as what if: num = 0.

7 Python Scope and Conditions
Existing Code Add This Code Run the Program print ("Helloworld!") num = 1 if num < 1: print ("I'm less than 1!") print ("Goodbye Cruel World!") elif num == 1: print ("I'm equal to 1!") else: print ("I'm greater than 1! ") Note ":" after each condition. Note indentation after each ":" ← "if" Statement and condition ← Conditional block defined by indentation ← "else if" statement & condition ← Single line conditional block ← "else" statement (optional) Note: You can have as many "elif" statements as you need Introduce various operators and other conditional statements elif and else:

8 Python Conditions and String Concatenation
print ("Helloworld!") num = 1 if num < 1: print ("I'm less than 1!") print ("Goodbye Cruel World!") elif num == 1: print ("I'm equal to 1!") else: print ("I'm greater than 1! ") num = input("Input a number: ") Run the program. What happens ? Insert Here: print ("Value is: " + str(num)) print ("Value is: ", num) Replace: Introduce String concatenation.

9 Python Conditions and String Concatenation
print ("Helloworld!") num = 1 num = input("Input a number: ") if num < 1: print ("I'm less than 1!") print ("Goodbye Cruel World!") elif num == 1: print ("I'm equal to 1!") else: print ("Value is: " + str(num)) print ("Value is: ", num) num = int( input("Input a number: ") ) ERROR! "num" is assigned the string representation of your number. Need to convert it to an integer.

10 Python Conditions and String Concatenation
print ("Helloworld!") num = 1 num = int(input("Input a number: ")) if num < 1: print ("I'm less than 1!") print ("Goodbye Cruel World!") elif num == 1: print ("I'm equal to 1!") else: print ("Value is: " + str(num)) print ("Value is: ", num) ← Accepts input from the terminal & places the result in the variable "num" The output looks "almost" the same: This concatenates the "Value" string with the character representation of the ← value contained in the variable "num" ← This prints the string followed by the character representation of "num" Note the spacing in the second print stmt Concatenates Strings

11 Conditional & Logical Operators

12 Python Looping for count in range(5) Loop from 0 to 4
for count in range(len(MyList)) Loop from 2 to 4 Loop from 0 to end of the list for fruit in basket Loops through a List, Tuple or Dictionary while count < 5 Must increment count while True Infinite loop. End with break statement

13 Looping with "for" in Python
Insert the "for" statement and indent all remaining lines. These form the block of the "for" loop. Run the program num = 1 for count in range(3): num = int(input("Input a number: ")) if num < 1: print ("I'm less than 1!") print (Goodbye Cruel World!") elif num == 1: print ("I'm equal to 1!") else: print ("Value is: " + str(num)) print ("Value is: ", num)

14 Looping with "while" in Python
num = 1 #for count in range(3): while num > 0: num = int(input("Input a number: ")) if num < 1: print ("I'm less than 1!") print (Goodbye Cruel World!") elif num == 1: print ("I'm equal to 1!") else: print ("Value is: " + str(num)) print ("Value is: ", num) Comment out the "for" statement Insert the "while" statement Run the program How has the behavior changed?

15 Dictionaries in Python
A dictionary is different than a list or a tuple. 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"} .The value in a dictionary is accessed by its key. Dictionaries are sometimes called maps or associative arrays Add this to your code and run: What is the result? print("\nMy Dictionary Example:") MyExample = {"Type":"MS250","Ports":48,"Name":"Switch1","Loc":"Building 5"} print (len(MyExample), MyExample) print (MyExample["Name"]," in ",MyExample["Loc"]," is a ",MyExample["Type"]) A dictionary is a different than a list or a tuple. 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 Parsing JSON with Python

17 What is JSON? JSON stands for Java Script Object Notation
Consists of text-based name-value pairs making it simple for applications to store and exchange data Designed to be lightweight, readable, and minimal, avoiding excessive text which has sometimes been the complaint of XML (another text-based protocol for exchanging and storing data) The structure and parsing of JSON is the same as Python dictionaries and lists In JSON, data is set up in name value pairs just like a Python dictionary; however, in JSON, dictionaries are referred to as objects

18 Concept : JSON JavaScript Object Notation (JSON)
A data-interchange text format Really just Collections of name/value pairs Object {} Ordered list of values Array [] [ { "first_name": "Joe", "last_name": "Montana" }, "first_name": "Jerry", "last_name": "Rice" } ]

19 Practice with Dictionaries
Copy the following code Run the program Devices={"model1":"MR52","model2":"MR84","model3":"MR42"} for model in Devices: print("Device Model: " + Devices[model]) Sample Output: Device Model MR52 Device Model MR84 Device Model MR42

20 Sending a REST API request
Copy the following code with a valid Dashboard API key (like your home lab's) Run the program import requests import json api_key = '<insert api key between single quotes>' org_url = ' meraki_headers = {'x-cisco-meraki-api-key': api_key, 'content-type': 'application/json'} # get all of the organizations this api key has access to response = requests.get(org_url, headers=meraki_headers) json_output = json.loads(response.text) # loop through the json_output and print each row for row in json_output: print(row) print("Org ID: " + str(row['id'])) print("Org Name: " + row['name']) Sample Output: {u'id': , u'name': u'Meraki DevNet Lab'} Org ID: Org Name: Meraki DevNet Lab

21 Deeply nested JSON structures
In JSON, objects and arrays are often nested several layers in order to organize data. Looking at the following structure from the inside and moving outward you see that we've nested an array inside an object which itself is nested inside an object. With this structure starting from the outside and moving in we see that switches is the key with the object fixed being its value. But notice that fixed is also a key and its value is the array of switch types. As a result, to get the actual types we need to dig a little deeper. myvar={"switches":{"fixed":["2900","3650","3850","9300","9500"]}} print(myvar["switches"]["fixed"][0]) print("My list of access switches are:", end=" ") for f in myvar["switches"]["fixed"]: print(f, end=" ")

22 Python Functions – Defining Your Own

23 Python Functions Defined - Examples

24 Python Functions Defined - Calling
print ("I'm not a function") def my_function(): print("Hey I'm a function!") def brett(val): for i in range(val): print("I'm a function with args!") my_function() brett(5) Example of defining and calling functions. Walk through from top down.

25 Content Credit: Cisco DevNet team, Paul Marsh, Meraki API team
Thanks for Playing ☺ Content Credit: Cisco DevNet team, Paul Marsh, Meraki API team


Download ppt "Python Jumpstart."

Similar presentations


Ads by Google