Python. Executive Summary

Size: px
Start display at page:

Download "Python. Executive Summary"

Transcription

1 Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic" data: integer, float, string, boolean, None "container" data: list, tuple, set, dict "code" objects: functions, methods, classes "custom" objects: defined by Python module authors (including you) VARIABLE: an object bound (assigned to) a name. var = 10 myxx = "hello!" def myfunc(): print('ok!') # int object # str object # function object Initialization of a variable means that the object is being stored in memory for later use during the run of the program. Re-initialization means that the name has been bound to a new object, and is now unbound from the prior object. All initializations create a new binding between a name and an object. STATEMENTS simple statements: assignment (with =): var = 10 augmented assignment (+=, -=, etc.): var += 5 del (unbind a variable or remove a dict key/value): del var break (drop out of a loop): break continue (jump to next iteration of a loop): continue import (import a Python module): import random ternary: an if/else in a simple statement var = 0 if xx < 0 else xx conditional assignment: if/else assignment var = xx or 100 compound statements: if, elif, else: if var > 5: and, or (for compound tests): if var > 5 and var < 10: not (testing negative condition): if not var > 5: while loop: while var < 100:

2 for: iterate through an iterable (container or file): for item in mylist: try: test code for a raised exception: try: except: lines to execute if exception occurs except IndexError: def: declare a function: def myfunc(arg1, arg2): class: declare a class class MyClass(object): OPERATORS An operator usually has two operands upon which it operates; it returns the result. math operators (+, -, *, /, **, %): var = 5 * 10 concatenation operator (+): var = 'hello' + ', world!' string repetition operator (*) var = 'hello' * 3 binary assignment operators (+=, -=, *=, /=, **=): var += 1 comparison operators (<, >, ==, <=, >=,!=): if var < 20: print var membership operators (in, not in): if 'David' not in names_list: identity operators (is, is not): if var is None: boolean compound operators (and, or): if var > 10 and var < 20: ternary expression (x if C else y): var = 0 if var < 0 else var FUNCTIONS all(): given a container, True if all are True if all([5, 10, 0.9, True]): any(): given a container, True if any are True if any([5, 0, 0, 0.0, None]): bool(): return True or False based on passed object enumerate(): return a list of (count, item) for count, item in enumerate(mylst): exit(): exit the program exit() int(), float(), str(), bool(): object constructors myf = float(5) len(): length of a string or container mylen = len('hello') min(), max(): min or max val from an iterable this = min([5, 9, 3, 0.9, 2]) print(): echo text to the screen print('hello');print('hello', end='\n') range(): return a list of integers in a range myrange = range(5, 10) input(): take keyboard input x = raw_input('enter num: ') repr(): display an object in more 'literal' form print repr(mystr) round(): round a float myr = round(5.539, 2) sorted(): return a list of sorted objects x = sorted([5, 9, 3, 0.9, 2]) type(): get type of any object print type(myr)

3 INTEGER and FLOAT var = 5 my_xx = 5.0 # initialize an int object # initialize a float object STRING mystr = 'hello' yourzzy = "hello" this_one = """this is a multi-line string.""" # initialize a single-quoted string object # initialize a double-quoted string (same as above) # initialize a multi-line string object count(): return int occurrences of substr within a string mynum = mystr.count('e') find(): return int index position of substr within a string indexx = mystr.index('e') format(): return a new string with {} tokens replaced fmstr = mystr.format(55, 23.0) isdigit(): return True if string is all digit characters if mystr.isdigit(): join(): return a string of element values joined on a str ','.join(['val1', 'val2', 'val3']) replace(): return a new string with substr replaced rstr = mystr.replace('e', 'a') rstrip(): return a str with whitespace / other chars removed mystr = mystr.rstrip() split(): return a list of strs from string split on delimeters slist = mystr.split() splitlines(): return a list of strs comprising lines from file slines = text.splitlines() startswith(): return True if string begins with substr if mystr.startswith('hel'): string slicing: return a portion of string slicstr = mystr[3:5] upper(), lower(): return an upper- or lowercased str newstr = mystr.upper() LIST and TUPLE mylist = ['a', 'b', 'c', 'hello', 5.3, 9] mytup = ('a', 'b', 'c', 'hello', 5.3, 9) # initialize a list # initialize a tuple slicing: return a list or tuple withs elected items newlist = mylist[3:5] subscripting: return one item from a list myitem = mylist[3] list append(): add an item to the end of a list mylist.append(100)

4 SET myset = { 'a', 'b', 'c', 'd' } =or= myset = set(['a', 'b', 'c', 'd']) add(): add an item to a set myset.add('newitem') difference(): return items in this set not in an iterable newset = myset.difference(this_list) intersection(): return items in this set also in an iterable newset = myset.intersection(a_tuple) union(): return items in both this set and an iterable newset = myset.union(some_set) DICTIONARY mydict = { 'a': 1, 'b': 2, 'c': 3 } add a key/value pair mydict['d'] = 4 read a value based on a key var = mydict['d'] loop through a dict's keys for key in mydict: loop through a dict's items for key, val in mydict.items() check for key membership for key in mydict: return length of a dict thislen = len(mydict).get(): return a value (or default) given a key value = mydict.get('a', None).items(): return a list of 2-element tuples items = mydict.items().keys(): return a list of the dict's keys keys = mydict.keys().values(): return a list of the dict's values values = mydict.values() FILE fh = open('thisfile.txt') # initialize a file object function: open() a file for writing fh = open('thisfile.txt', 'w') function: open() a file for appending fh = open('thisfile.txt', 'a') method: write(): write string data to the file fh.write('a line of text\n') 'for' looping: assign each line in file to a 'control variable' for line in fh: read(): return a string containing the text of the file text = fh.read() readlines(): return a list of strings, each line from file lines = fh.readlines()

5 MULTIDIMENSIONAL CONTAINERS list of lists x = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] o access a single element item = x[1][2] # 6 list of dicts o loop through for innerlist in x: for item in innerlist: print item x = [ { 'this': 5, 'that': 10 }, { 'this': 20, 'that': 7 } ] o access a single element value = x[1]['that'] # 7 dict of lists o loop through for innerdict in x: for key in innerdict: print innerdict[key] x = { 'a': [ 1, 2, 3, 4 ], 'b': [1, 3, 2, 4] } o access a single element item = x['b'][1] # 3 o loop through for key in x: for item in x[key]: print item dict of dicts x = { 'a': { 'this': 5, 'that': 10 }, 'b': { 'this': 20, 'that': 25 } } o access a single element o loop through value = x['a']['that'] # 10 for key in x: print key + ':' for ikey in x[key]: print ' ' + ikey + ', ' + str(x[key][ikey])

6 CONTAINER OPERATIONS (applies to list, tuple, set, string, others) len(): get int length of (# of items in) container length = len(mylist) in: test for membership in a container if 'hello' in mylist: for: loop through each item in a container for item in myset: sum(): sum values in a container (numbers) total = sum(prices) max(): get max value in a container highest = max(prices) min(): get min value in a container minim = min(prices) sorted(): return list of items, sorted slist = sorted(mylist) subscript: return item at index pos (list, tuple) first = mylist[0] slice: return new container with selected items newlist = mylist[3:5] LIST COMPREHENSIONS wanted_lines = [line.split()[1] for line in lines if line.startswith('1972')] LAMBDAS slist = sorted(mylist, key=lambda x: x.split()[0]) CUSTOM SORT FUNCTIONS def by_first_item(line): items = line.split() first_item = items[0] return first_item slist = sorted(mylist, key=by_first_item) TRAPPING EXCEPTIONS try: x = int(input('enter a number, please: ') except ValueError: print('oops, that did not convert to an int!')

7 USER-DEFINED FUNCTIONS def addthese(arg1, arg2): mysum = arg1 + arg2 return mysum argument and return value def myfunc(this_arg): new_val = this_arg + 1 return new_val positional arguments def myfunc(arg1, arg2): keyword arguments def myfunc(this=none, that=0): arbitrary arguments: *args def myfunc(*args): arbitrary keyword arguments: **kwargs def myfunc(**kwargs): MODULES time: import time time.sleep(10) date and datetime: from datetime import datetime dt = datetime.now() timedelta: from datetime import timedelta td = timedelta(hours=3) USING MODULES import modname: import a module's variables through its name import mymod print mymod.var import modname as convenientname: rename module in our code import mymod as tt print tt.var from modname import varname: import a variable from module from mymod import var from modname import *: don't ever do this! ;) NO sys.path: module search path sys.path.append(newdir) PYTHONPATH: environment variable informing the sys.path if name == ' main ': module / script "identity gate" if name == ' main ': main() pip module install program

8 CLASSES class declaration class MyClass(object): pass set object's attributes ( dict ) x = MyClass() x.var = 5 get attribute value print x.var self implicit argument to method def dothis(self): init constructor def init (self): EXCEPTIONS (also see Exceptions Reference) SyntaxError: when the code has a syntax mistake (missing paren or quote, etc.) NameError: when a variable name is used that doesn't exist (often a misspelling) TypeError: when the type of object used in a function or method is incorrect AttributeError: when attempting to acces an attribute (e.g. method) that is incorrect for the object IndexError: when attempting to access an item in a list where the index doesn't exist UnboundLocalError: reading a local variable before def dothis(): assigning x = x + 1 # is x a global? IndentationError: when an indent occurs before for item in mylist: a block, or doesn't occur inside a block print item raise: cause an exception to occur raise ValueError

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

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

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

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

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

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

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

LECTURE 3 Python Basics Part 2

LECTURE 3 Python Basics Part 2 LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.

More information

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

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

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

18.1. CS 102 Unit 18. Python. Mark Redekopp

18.1. CS 102 Unit 18. Python. Mark Redekopp 18.1 CS 102 Unit 18 Python Mark Redekopp 18.2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 18.3 Python in Context Two

More information

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

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

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

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

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

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

Introduction to Python for Plone developers

Introduction to Python for Plone developers Plone Conference, October 15, 2003 Introduction to Python for Plone developers Jim Roepcke Tyrell Software Corporation What we will learn Python language basics Where you can use Python in Plone Examples

More information

Python. Karin Lagesen.

Python. Karin Lagesen. Python Karin Lagesen karin.lagesen@bio.uio.no Plan for the day Basic data types data manipulation Flow control and file handling Functions Biopython package What is programming? Programming: ordered set

More information

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

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell In the python interactive shell you don t need print Creating variables

More information

Introduction to Python

Introduction to Python Introduction to Python Michael Krisper Thomas Wurmitzer October 21, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python October 21, 2014 1 / 26 Schedule Tutorium I Dates & Deadlines Submission

More information

Exceptions and File I/O

Exceptions and File I/O Lab 6 Exceptions and File I/O Lab Objective: In Python, an exception is an error detected during execution. Exceptions are important for regulating program usage and for correctly reporting problems to

More information

Python Evaluation Rules

Python Evaluation Rules Python Evaluation Rules UW CSE 160 https://courses.cs.washington.edu/courses/cse160/15sp/ Michael Ernst and Isaac Reynolds mernst@cs.washington.edu April 1, 2015 Contents 1 Introduction 2 1.1 The Structure

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

Control Structures 1 / 17

Control Structures 1 / 17 Control Structures 1 / 17 Structured Programming Any algorithm can be expressed by: Sequence - one statement after another Selection - conditional execution (not conditional jumping) Repetition - loops

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

DaMPL. Language Reference Manual. Henrique Grando

DaMPL. Language Reference Manual. Henrique Grando DaMPL Language Reference Manual Bernardo Abreu Felipe Rocha Henrique Grando Hugo Sousa bd2440 flt2107 hp2409 ha2398 Contents 1. Getting Started... 4 2. Syntax Notations... 4 3. Lexical Conventions... 4

More information

Here n is a variable name. The value of that variable is 176.

Here n is a variable name. The value of that variable is 176. UNIT II DATA, EXPRESSIONS, STATEMENTS 9 Python interpreter and interactive mode; values and types: int, float, boolean, string, and list; variables, expressions, statements, tuple assignment, precedence

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

TEXT MINING INTRO TO PYTHON

TEXT MINING INTRO TO PYTHON TEXT MINING INTRO TO PYTHON Johan Falkenjack (based on slides by Mattias Villani) NLPLAB Dept. of Computer and Information Science Linköping University JOHAN FALKENJACK (NLPLAB, LIU) TEXT MINING 1 / 23

More information

EE 355 Unit 17. Python. Mark Redekopp

EE 355 Unit 17. Python. Mark Redekopp 1 EE 355 Unit 17 Python Mark Redekopp 2 Credits Many of the examples below are taken from the online Python tutorial at: http://docs.python.org/tutorial/introduction.html 3 Python in Context Interpreted,

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Jarek Szlichta

Jarek Szlichta Jarek Szlichta http://data.science.uoit.ca/ Python is a straightforward language very simple syntax It encourages programmers to program without boilerplate (prepared) code 2 Python is completely object

More information

Coral Programming Language Reference Manual

Coral Programming Language Reference Manual Coral Programming Language Reference Manual Rebecca Cawkwell, Sanford Miller, Jacob Austin, Matthew Bowers rgc2137@barnard.edu, {ja3067, skm2159, mlb2251}@columbia.edu October 15, 2018 Contents 1 Overview

More information

Exercise: The basics - variables and types

Exercise: The basics - variables and types Exercise: The basics - variables and types Aim: Introduce python variables and types. Issues covered: Using the python interactive shell Creating variables Using print to display a variable Simple arithmetic

More information

Introduction to Python Code Quality

Introduction to Python Code Quality Introduction to Python Code Quality Clarity and readability are important (easter egg: type import this at the Python prompt), as well as extensibility, meaning code that can be easily enhanced and extended.

More information

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s

PYTHON FOR KIDS A Pl ayfu l I ntrodu ctio n to Prog r am m i ng J a s o n R. B r i g g s PYTHON FO R K I D S A P l ay f u l I n t r o d u c t i o n to P r o g r a m m i n g Jason R. Briggs Index Symbols and Numbers + (addition operator), 17 \ (backslash) to separate lines of code, 235 in strings,

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Python debugging and beautification

Python debugging and beautification Python debugging and beautification #!/usr/bin/env python # # # THIS CODE DOES NOT WORK import sys def read(a): myfile = open(a,'r'): for i in myfile: yield i myfile.close() def count_chars(a): sum = 0

More information

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

Computer Sciences 368 Scripting for CHTC Day 3: Collections Suggested reading: Learning Python Day 3: Collections Suggested reading: Learning Python (3rd Ed.) Chapter 8: Lists and Dictionaries Chapter 9: Tuples, Files, and Everything Else Chapter 13: while and for Loops 1 Turn In Homework 2 Homework

More information

egrapher Language Reference Manual

egrapher Language Reference Manual egrapher Language Reference Manual Long Long: ll3078@columbia.edu Xinli Jia: xj2191@columbia.edu Jiefu Ying: jy2799@columbia.edu Linnan Wang: lw2645@columbia.edu Darren Chen: dsc2155@columbia.edu 1. Introduction

More information

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A DEBUGGING TIPS COMPUTER SCIENCE 61A 1 Introduction Every time a function is called, Python creates what is called a stack frame for that specific function to hold local variables and other information.

More information

Lists, loops and decisions

Lists, loops and decisions Caltech/LEAD Summer 2012 Computer Science Lecture 4: July 11, 2012 Lists, loops and decisions Lists Today Looping with the for statement Making decisions with the if statement Lists A list is a sequence

More information

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

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

STSCI Python Introduction. Class URL

STSCI Python Introduction. Class URL STSCI Python Introduction Class 2 Jim Hare Class URL www.pst.stsci.edu/~hare Each Class Presentation Homework suggestions Example files to download Links to sites by each class and in general I will try

More information

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break

Strings. Upsorn Praphamontripong. Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Note: for reference when we practice loop. We ll discuss Strings in detail after Spring break Strings Upsorn Praphamontripong CS 1111 Introduction to Programming Spring 2018 Strings Sequence of characters

More information

6. Data Types and Dynamic Typing (Cont.)

6. Data Types and Dynamic Typing (Cont.) 6. Data Types and Dynamic Typing (Cont.) 6.5 Strings Strings can be delimited by a pair of single quotes ('...'), double quotes ("..."), triple single quotes ('''...'''), or triple double quotes ("""...""").

More information

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

Python Tutorial. Day 1

Python Tutorial. Day 1 Python Tutorial Day 1 1 Why Python high level language interpreted and interactive real data structures (structures, objects) object oriented all the way down rich library support 2 The First Program #!/usr/bin/env

More information

University of Texas at Arlington, TX, USA

University of Texas at Arlington, TX, USA Dept. of Computer Science and Engineering University of Texas at Arlington, TX, USA Part of the science in computer science is the design and use of data structures and algorithms. As you go on in CS,

More information

Programming in Python 3

Programming in Python 3 Programming in Python 3 Programming transforms your computer from a home appliance to a power tool Al Sweigart, The invent with Python Blog Programming Introduction Write programs that solve a problem

More information

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD PYTHON Varun Jain & Senior Software Engineer Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT CenturyLink Technologies India PVT LTD 1 About Python Python is a general-purpose interpreted, interactive,

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

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

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

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

Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Princeton University COS 333: Advanced Programming Techniques A Subset of Python 2.7 Program Structure # Print "hello world" to stdout. print 'hello, world' # Print "hello world" to stdout. def f(): print

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8 Chapter 5: Control Flow This chapter describes related to the control flow of a program. Topics include conditionals, loops,

More information

SCoLang - Language Reference Manual

SCoLang - Language Reference Manual SCoLang - Language Reference Manual Table of Contents: 1. Introduction 2. Types a. Basic Data types b. Advanced Data types 3. Lexical Convention a. Identifiers b. Keywords c. Comments d. Operators e. Punctuators

More information

Flow Control: Branches and loops

Flow Control: Branches and loops Flow Control: Branches and loops In this context flow control refers to controlling the flow of the execution of your program that is, which instructions will get carried out and in what order. In the

More information

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT

Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Duration: Six Weeks Faculty : Mr Sai Kumar, Having 10+ Yrs Experience in IT Online Classes are also available Recorded class will be given if you miss any day interview tips and quiz at end of every module

More information

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

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT

Python The way of a program. Srinidhi H Asst Professor Dept of CSE, MSRIT Python The way of a program Srinidhi H Asst Professor Dept of CSE, MSRIT 1 Problem Solving Problem solving means the ability to formulate problems, think creatively about solutions, and express a solution

More information

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

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0 6 Statements 43 6 Statements The statements of C# do not differ very much from those of other programming languages. In addition to assignments and method calls there are various sorts of selections and

More information

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala

Loops and Conditionals. HORT Lecture 11 Instructor: Kranthi Varala Loops and Conditionals HORT 59000 Lecture 11 Instructor: Kranthi Varala Relational Operators These operators compare the value of two expressions and returns a Boolean value. Beware of comparing across

More information

Course Introduction and Python Basics

Course Introduction and Python Basics Course Introduction and Python Basics Johan Falkenjack 2018-01-15 Course Introduction Python > Data Science 3 hp pass/fail 3 lectures, 3 labs (2 sessions for each lab) Python Basics Programming Paradigms

More information

ENGR 101 Engineering Design Workshop

ENGR 101 Engineering Design Workshop ENGR 101 Engineering Design Workshop Lecture 2: Variables, Statements/Expressions, if-else Edgardo Molina City College of New York Literals, Variables, Data Types, Statements and Expressions Python as

More information

IE 555 Programming for Analytics

IE 555 Programming for Analytics IE 555 Programming for Analytics Module #1 Introduction to Python This rather lengthy document is designed to give a broad overview of the Python programming language. Numerous examples are provided to

More information

VLC : Language Reference Manual

VLC : Language Reference Manual VLC : Language Reference Manual Table Of Contents 1. Introduction 2. Types and Declarations 2a. Primitives 2b. Non-primitives - Strings - Arrays 3. Lexical conventions 3a. Whitespace 3b. Comments 3c. Identifiers

More information

Python and Bioinformatics. Pierre Parutto

Python and Bioinformatics. Pierre Parutto Python and Bioinformatics Pierre Parutto October 9, 2016 Contents 1 Common Data Structures 2 1.1 Sequences............................... 2 1.1.1 Manipulating Sequences................... 2 1.1.2 String.............................

More information

Introduction to Python Part I

Introduction to Python Part I Introduction to Python Part I BaRC Hot Topics Bioinformatics and Research Computing Whitehead Institute Nov 29th 2018 http://barc.wi.mit.edu/hot_topics/ 1 About Python Object oriented language; easy to

More information

Basic Python Revision Notes With help from Nitish Mittal

Basic Python Revision Notes With help from Nitish Mittal Basic Python Revision Notes With help from Nitish Mittal HELP from Documentation dir(module) help() Important Characters and Sets of Characters tab \t new line \n backslash \\ string " " or ' ' docstring

More information

COMP 204: Sets, Commenting & Exceptions

COMP 204: Sets, Commenting & Exceptions COMP 204: Sets, Commenting & Exceptions Yue Li based on material from Mathieu Blanchette, Carlos Oliver Gonzalez and Christopher Cameron 1/29 Outline Quiz 14 review Set Commenting code Bugs 2/29 Quiz 15

More information

Python source materials

Python source materials xkcd.com/353 Python source materials Bob Dondero s Python summary from Spring 2011 http://www.cs.princeton.edu/courses/archive/spring11/cos333/ reading/pythonsummary.pdf bwk s Python help file: http://

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Introduction Harry Smith University of Pennsylvania January 18, 2017 Harry Smith (University of Pennsylvania) CIS 192 Lecture 1 January 18, 2017 1 / 34 Outline 1 Logistics Rooms

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

MEIN 50010: Python Flow Control

MEIN 50010: Python Flow Control : Python Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-11 Program Overview Program Code Block Statements Expressions Expressions & Statements An expression has

More information

String Processing CS 1111 Introduction to Programming Fall 2018

String Processing CS 1111 Introduction to Programming Fall 2018 String Processing CS 1111 Introduction to Programming Fall 2018 [The Coder s Apprentice, 10] 1 Collections Ordered, Dup allow List Range String Tuple Unordered, No Dup Dict collection[index] Access an

More information

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017

Control Structures. Lecture 4 COP 3014 Fall September 18, 2017 Control Structures Lecture 4 COP 3014 Fall 2017 September 18, 2017 Control Flow Control flow refers to the specification of the order in which the individual statements, instructions or function calls

More information

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter Variables, Expressions, and Statements Chapter 2 Unless otherwise noted, the content of this course material is licensed under a Creative Commons Attribution 3.0 License. http://creativecommons.org/licenses/by/3.0/.

More information

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018

Chapter 8: More About Strings. COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Chapter 8: More About Strings COSC 1436, Summer 2018 Dr. Zhang 7/10/2018 Creating Strings The str Class s1 = str() # Create an empty string s2 = str("welcome") # Create a string Welcome Python provides

More information

Abstract Data Types. David E. Culler CS8 Computational Structures in Data Science Lecture 7 March 7, 2016

Abstract Data Types. David E. Culler CS8 Computational Structures in Data Science   Lecture 7 March 7, 2016 Abstract Data Types David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 7 March 7, 2016 Computational Concepts Toolbox Data type: values, literals,

More information

UNIVERSITÀ DI PADOVA. < 2014 March >

UNIVERSITÀ DI PADOVA. < 2014 March > UNIVERSITÀ DI PADOVA < 2014 March > Easy-to-learn: Python has relatively few keywords, simple structure, and a clearly defined syntax. Easy-to-read: Python code is much more clearly defined and visible

More information

Collections. Lists, Tuples, Sets, Dictionaries

Collections. Lists, Tuples, Sets, Dictionaries Collections Lists, Tuples, Sets, Dictionaries Homework notes Homework 1 grades on canvas People mostly lost points for not reading the document carefully Didn t play again Didn t use Y/N for playing again

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

An Introduction to Python

An Introduction to Python An Introduction to Python Day 2 Renaud Dessalles dessalles@ucla.edu Python s Data Structures - Lists * Lists can store lots of information. * The data doesn t have to all be the same type! (unlike many

More information

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS

CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS CHAPTER 2: Introduction to Python COMPUTER PROGRAMMING SKILLS 1439-1440 1 Outline 1. Introduction 2. Why Python? 3. Compiler and Interpreter 4. The first program 5. Comments and Docstrings 6. Python Indentations

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 1: Intro! Max Dougherty Andrew Schmitt Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and

More information

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

CS S-02 Python 1. Most python references use examples involving spam, parrots (deceased), silly walks, and the like CS662-2013S-02 Python 1 02-0: Python Name python comes from Monte Python s Flying Circus Most python references use examples involving spam, parrots (deceased), silly walks, and the like Interpreted language

More information

Exception Handling. Genome 559

Exception Handling. Genome 559 Exception Handling Genome 559 Review - classes Use your own classes to: - package together related data - conceptually organize your code - force a user to conform to your expectations Class constructor:

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

CS Programming Languages: Python

CS Programming Languages: Python CS 3101-1 - Programming Languages: Python Lecture 5: Exceptions / Daniel Bauer (bauer@cs.columbia.edu) October 08 2014 Daniel Bauer CS3101-1 Python - 05 - Exceptions / 1/35 Contents Exceptions Daniel Bauer

More information

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information