Python Tutorial. CSE 3461: Computer Networking

Similar documents
CS2304: Python for Java Programmers. CS2304: Sequences and Collections

Part III Appendices 165

Python. Jae-Gil Lee Based on the slides by K. Naik, M. Raju, and S. Bhatkar. December 28, Outline

Beyond Blocks: Python Session #1

Table of Contents EVALUATION COPY

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Introduction to Scientific Python, CME 193 Jan. 9, web.stanford.edu/~ermartin/teaching/cme193-winter15

18.1. CS 102 Unit 18. Python. Mark Redekopp

Topic 7: Lists, Dictionaries and Strings

Crash Dive into Python

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

CIS192 Python Programming. Robert Rand. August 27, 2015

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Python I. Some material adapted from Upenn cmpe391 slides and other sources

CS 2316 Exam 1 Spring 2014

Programming refresher and intro to C programming

Midterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals

Introduction to Python

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

Babu Madhav Institute of Information Technology, UTU 2015

Senthil Kumaran S

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Introduction to Python for Plone developers

Python Basics. Lecture and Lab 5 Day Course. Python Basics

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

Key Differences Between Python and Java

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

CS61A Lecture 16. Amir Kamil UC Berkeley February 27, 2013

STEAM Clown & Productions Copyright 2017 STEAM Clown. Page 1

Introduction to Python

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python

CS Summer 2013

Python: Short Overview and Recap

ENGR 102 Engineering Lab I - Computation

Collections. Lists, Tuples, Sets, Dictionaries

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital

Programming in Python

Pace University. Fundamental Concepts of CS121 1

Programming to Python

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

Introduction to Python

SECOND EDITION SAMPLE CHAPTER. First edition by Daryl K. Harms Kenneth M. McDonald. Naomi R. Ceder MANNING

Python Programming, bridging course 2011

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like

Getting started with Java

Advanced Python. Executive Summary, Session 1

Data Structures. Lists, Tuples, Sets, Dictionaries

Statements 2. a operator= b a = a operator b

Visualize ComplexCities

Variable and Data Type I

Script language: Python Data structures

CS 2316 Learning Objectives

Variable and Data Type I

Language Reference Manual

Comp Exam 1 Overview.

Introduction to Python

The Practice of Computing Using PYTHON

Index. object lifetimes, and ownership, use after change by an alias errors, use after drop errors, BTreeMap, 309

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python. Executive Summary

MEIN 50010: Python Introduction

Python for ArcGIS. Lab 1.

AI Programming CS S-02 Python

Python a modern scripting PL. Python

Introduction to Python, Cplex and Gurobi

Python: common syntax

Python for Non-programmers

Hardware: Logical View

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems

SAMPLE CHAPTER. Naomi Ceder MANNING. Foreword by Nicholas Tollervey

Programming. We will be introducing various new elements of Python and using them to solve increasingly interesting and complex problems.

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Introduction to Programming in Python (1)

Selection statements. CSE 1310 Introduction to Computers and Programming Alexandra Stefan University of Texas at Arlington

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7

COMP-520 GoLite Tutorial

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Introduction to Python

And Parallelism. Parallelism in Prolog. OR Parallelism

Episode 3 Lists and Strings

pybdg Documentation Release 1.0.dev2 Outernet Inc

CIS192: Python Programming

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

Selection Statement ( if )

University of Texas at Arlington, TX, USA

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France

Artificial Intelligence A Primer for the Labs

Introduction to Python

Coral Programming Language Reference Manual

Computing with Numbers

Course Introduction and Python Basics

Play with Python: An intro to Data Science

Sequence Types FEB

The second statement selects character number 1 from and assigns it to.

PROGRAMMING FUNDAMENTALS

ECE 364 Software Engineering Tools Laboratory. Lecture 4 Python: Collections I

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

Transcription:

Python Tutorial CSE 3461: Computer Networking 1

Outline Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 2

Intro to Python Dynamically typed, object-oriented, interpreted scripting language Not statically typed like Java Objects and exceptions similar to Java Concise style (in contrast to C!) Interpreted via interpreter vs. compilation, linking, and execution Python 3.x breaks backward compatibility with 2.x Not all libraries with 2.x work with 3.x (e.g., twister) But 3.x offers features not found in 2.x Many Python references online, including: Python tutorial: http://docs.python.org/3/tutorial/index.html N.R. Ceder, The Quick Python Book, 2nd ed., Manning, 2010, http://proquest.safaribooksonline.com/book/programming/pytho n/9781935182207 3

Running Python Programs Interpreters: Interactive mode (type python at command line) IDLE CSE Environment (type idle at command line) Scripts Create a file beginning with: #!/usr/bin/env python Then add your code helloworld.py #!/usr/bin/env python print Hello world $ python helloworld.py Hello world Running Hello World in IDLE (above) and as a script (below). 4

Basic Data Types (1) Numbers: Integers (-3, 0, 5) Floats (3.0, -6.0, 2.5e12, -2.5e-12) Complex numbers (3+2j, -3-2j) Booleans (True, False) Strings: immutable sequences of characters, indices start at 0 If a = Python, then a[0] returns P, a[5] returns n Positive and negative indices: +---+---+---+---+---+---+ P y t h o n +---+---+---+---+---+---+ 0 1 2 3 4 5 6-6 -5-4 -3-2 -1 Slicing: a[i:j] returns substring of a containing characters i, i+1, j-1 (e.g., a[2:4] returns th ) str() converts an object to a string, e.g., str(5) returns 5 5

Basic Data Types (2) Lists: mutable sequences of objects Example: [1,2,3] and [1, two,3] List elements can be changed: if a = [1,5,9], a[1] = 4 yields a = [1,4,9] Operators: len(), max(), min(), append(), count(), extend(), index(), insert(), pop(), remove(), reverse(), sort(), in, +, * len() also returns length of string list() constructs a list from its input Tuples: immutable vectors of objects (keys in dictionaries) Example: (1,), (1,2), and (1, two, 3) Operators in, +, *, len(), max(), min() apply tuple() and list() convert lists to tuples and vice versa 6

Basic Data Types (3) Dictionaries: maps between immutable keys and mutable values Ex: x={ one :1, two :2} and [ three ]=3 yield x={ one :1, two :2, three :3} Operators: len(), del(), clear(), copy(), get(), has_key(), items(), keys(), update(), values() File objects: file I/O is very simple Ex: f = open( file.txt, r ) line = f.readline() print(line) 7

Control Structures (1) Boolean connectives are mostly the same as other languages (>,, <,, ==,!=) Specialties: and, or, not, is, is not, in, not in If-then-else: the else if is elif: x = 5 if x < 5: x = x + 1 elif x > 5: x = x 1 else: print(x) What happens? Notice indentation determines control structure level ; no braces! Usually four spaces (no tabs) 8

Control Structures (2) while loop: executes as long as stmt. is true Example: x = 5 while (x > 0): x = x 1 print(x) for loop: iterates over iterable objects Example: alist = list([1, 2, 3, 4]) for item in alist: print(item) 9

Function Definition Python lets us define our own functions Ex: def find_mean(iterable): the_sum = 0 for x in iterable: the_sum = the_sum + x the_sum = float(the_sum / len(iterable)) return the_sum a = list([1,2,3,4]) mu_a = find_mean(a) print(mu_a) 10

Class Definition Python enables object-oriented programming: Ex. (Listing 3.3 in The Quick Python Book): 11

Outline Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 12

CSE Environment (1) Both Python 2.x or 3.x are available on stdlinux The default version of Python on stdlinux is 2.7.10 To use Python 3.5.0, please use subscribe command On stdlinux, type subscribe and select PYTHON-3 Then, log out from and log in again to stdlinux Please make sure that python3.x is installed with which python3 The execution commands are python for 2.7.10 python3 for 3.5.0 13

CSE Environment (2) How to find the IP address that you are logging in /sbin/ifconfig eth0 grep inet Submission command submit c3461ax lab1 [code1] [code2] Where x could be a, b, and so on Note that the last submission overwrites the previous submission 14

Tips for Python Primitive Types Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 15

Encoding Integer to Bytes (Python 2.x) For version 2.x, you can use "struct" class Note that "<" means little endian, and "I" means unsigned integer An integer variable is always 4 bytes, and thus the pack() function returns a byte object with size 4 >> import struct >> var = 1000 # an integer variable >> byte_int = struct.pack('<i', var) # a byte object 16

Encoding Integer to Bytes (Python 3.x) For version 3.x, there s a simple way. Note that (int).to_bytes(int, byteorder) was introduced in 3.1; not available for 2.6.6. The first argument is the number of bytes, and the second argument is little, big, etc. # var is encoded into a byte object, byte_int, with size 4 # with little endian. >> var = 1000 # an integer variable >> byte_int = var.to_bytes(4, byteorder='little ) 17

Decoding Byte to Integer (Python 2.x) Use "struct.unpack struct.unpack('<i', bytes_var) returns a tuple; first element is an integer value < indicates the little endian, and I indicates unsigned integer type # byte_int is a byte object with size 4. >> import struct >> var = struct.unpack('<i', byte_int)[0] 18

Decoding Byte to Integer (Python 3.x) Use "int.from_bytes(bytes_var, byteorder) This is a static function, thus in form of int.function(...) # byte_int is a byte object >> var = int.from_bytes(byte_int, byteorder='little') 19

Encoding String to Bytes String type has encode() and decode() functions ASCII is default encoding scheme >> str_var = "Hello. >> byte_var = str_var.encode() # encoding with ASCII >> str_var2 = byte_var.decode() # decoding with ASCII 20

Formatting String (Constant Length) Use (str_var).rjust(int), where the argument is the length after formatting Spaces are added in keeping with the original string at the right (the end of the string) Similar functions are available, such as "ljust(int)", and so on # e.g., "Hello" (5-byte) is formatted to " Hello" (10-byte) >> str_var = "Hello >> formatted_str_var = str_var.rjust(10) 21

Removing Spaces from String Use (str_var).lstrip() that removes spaces from the left (the beginning of the string), where str_var is a string object # e.g., The spaces in " Hello" are removed from the left # (the beginning of the string), # and lstrip() reutrns "Hello". >> formatted_str_var = " Hello >> str_var = formatted_str_var.lstrip() 22

Outline Introduction to Python CSE Environment Tips for Python Primitive Types Tips for Encoding/Decoding an IP Address 23

Encoding Integer to Byte (Python 2.x) Note that Python 3.x is recommended For Python 2.x, you can encode an IP address as follows: for each integer value, [127, 0, 0, 1], pack integer as a binary with the 'B' option. Reverse operation for decoding. # Note that "var" must be between 0-255. >> import struct >> var = 3 >> byte_var = struct.pack('b', var) >> \x03 # unpacking, where byte_var is \x03 >> unpacked_var = struct.unpack('b', byte_var) >> 3 24

Encoding Integer to Byte (Python 3.x) Encode an IP address into bytes with size 4 as follows: Split the string object "127.0.0.1" to a list with four elements, i.e., ["127,"0,"0,"1"], where "." is token Cast every element to an integer value, i.e., [127,0,0,1] Use "to_bytes" function for each integer value Concatenate bytes with +. # byte_var is a 1-byte byte object. # The first argument of "to_byte" is the size of a byte object. >> var = 10 >> byte_var = var.to_bytes(1, byteorder='little') # byte_var3 is "\x9b\x00" >> byte_var1 = \x9b >> byte_var2 = \x00 >> byte_var3 = byte_var1 + byte_var2 25

Acknowledgment This material is partially based on http://www.seas.upenn.edu/~cis521/lectures/pythontutorial.pdf N.R. Ceder, The Quick Python Book, 2nd ed., Manning Publications, 2010. Python Tutorial, http://docs.python.org/3/tutorial/introduction.html 26