Python Programming: Lecture 2 Data Types
|
|
- Jeffry Gregory
- 5 years ago
- Views:
Transcription
1 Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania
2 Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float) is bool 4. The type of print hello() is None 5. hi and 0 evaluates to 0 6. Even integers from 0 up to and including 10: range(0, 11, 2)
3 Ternary Expressions How do we replicate a bool? a : b expression? i.e. if bool is true, then return a, else return b >>> b = True >>> x = 5 if b else 10 >>> x 5 >>> x = 5 if not b else 10 >>> x 10
4 Lists Mutable / resizable arrays Can contain multiple datatypes Written using square brackets [] # empty list [5, "Hi!", [1, 2, 3], False]
5 Lists: Indexing >>> a = ['a', 'b', 'c', 'd'] >>> a[0] 'a' >>> a[-1] 'd'
6 Lists: Indexing >>> a = ['a', 'b', 'c', 'd'] >>> range(1,3) # recall... [1, 2] >>> a[1:3] ['b', 'c'] >>> a[1:] ['b', 'c', 'd'] >>> a[:-2] ['a', 'b']
7 Lists: Indexing >>> a = ['a', 'b', 'c', 'd'] >>> range(1,10,2) # recall... [1, 3, 5, 7, 9] >>> a[0:3:2] ['a', 'c'] >>> a[::2] ['a', 'c']
8 Lists: Indexing >>> a = [5, "Hi!", [1, 2, 3], False] >>> a[2][1] 2
9 Lists: Builtins >>> b = [5, 10, 15, 20] >>> b.index(10) 1 >>> len(b) 4 >>> sum(b) 50 >>> 5 in b True >>> 6 not in b True
10 Lists: Iteration >>> a = ["apple", "orange", "banana"] >>> range(len(a)) [0, 1, 2] >>> for i in range(len(a)): # Bad!... print a[i]... apple orange banana >>> for i in a: # Good!... print i... apple orange banana
11 Lists: Insertion >>> a = ["apple", "orange", "banana"] >>> a[1] = "pear" >>> a ['apple', 'pear', 'banana'] >>> a.insert(2, "kiwi") >>> a ['apple', 'orange', 'kiwi', 'banana']
12 Lists: Concatenation >>> a = [1, 2, 3] >>> b = [4, 5, 6] >>> a + b [1, 2, 3, 4, 5, 6] >>> a.extend(b) >>> a [1, 2, 3, 4, 5, 6] >>> a.append(7) >>> a [1, 2, 3, 4, 5, 6, 7]
13 Lists: Removal >>> a = ['a', 'b', 'c'] >>> del a[0] >>> a ['b', 'c'] >>> a.remove('c') >>> a ['b'] del removes a specific index, whereas remove removes the first matching value.
14 Lists: Removal >>> b = [1, 2, 3, 4] >>> b[1:3] = [] >>> b [1, 4]
15 References All data in Python is represented by objects Then variables must all be references to objects The memory a variable takes up is merely a pointer to some other part of memory that actually has the object We usually think of the thing being pointed to as the value of the variable, not the pointer itself
16 References
17 References
18 References
19 References == checks whether variables point to objects of the same value is checks whether variables point to the same object >>> a = [1,2,3] >>> b = a >>> a == b True >>> a is b True >>> a.append(4) >>> a [1, 2, 3, 4] >>> b [1, 2, 3, 4]
20 References b was an shallow copy Use list or [:] to get deep copies >>> a = [1,2,3] >>> b = list(a) # or b = a[:] >>> a == b True >>> a is b False >>> a.append(5) >>> a [1, 2, 3, 4, 5] >>> b [1, 2, 3, 4]
21 References What happens here? >>> a = [1,2,3] >>> b = [1,2,3]
22 References What happens here? >>> a = [1,2,3] >>> b = [1,2,3] >>> a == b True >>> a is b False
23 Lists: Multiplication >>> [0] * 5 [0, 0, 0, 0, 0] >>> [1, 2] * 3 [1, 2, 1, 2, 1, 2] >>> [[1, 2]] * 3 [[1, 2], [1, 2], [1, 2]]
24 Lists: Multiplication But be careful! >>> l = [[]] * 3 >>> l [[], [], []] >>> l[1].append(0) >>> l [[0], [0], [0]] # expected [[], [0], []] When you use the [x]*n syntax, what you get is a list of n many x objects, but they re all references to the same object.
25 Lists: Multiplication [[]]*n is the same as:: l = [] x = [] for i in range(n): l.append(x) Instead, do: l = [] for i in range(n): l.append([]) We ll see a one-liner that accomplishes this shortly...
26 Lists: Comprehensions Produce new lists from existing lists Basic form: [expr(x) for x in xs if cond(x)]
27 Lists: Comprehensions >>> a = [1, 2, 3, 4, 5] # map >>> [x * 2 for x in a] [2, 4, 6, 8, 10] >>> [x for x in a if x > 3] # filter [4, 5] >>> [x * 3 for x in a if x % 2 == 0] # both [6, 12]
28 Lists: Comprehensions To achieve our desired list-of-lists initialization: >>> x = [[] for _ in range(3)]
29 Lists: Comprehensions Nested for loop: >>> matrix = [[1, 2], [3, 4]] >>> [element for row in matrix for element in row] [1, 2, 3, 4] Read this left-to-right, as: for row in matrix: for element in row: element
30 Lists: Comprehensions Nested list comprehension: >>> matrix = [[1, 2], [3, 4]] >>> [[row[i] for row in matrix] for i in range(len(matrix))] [[1, 3], [2, 4]] Read this right-to-left, as: for i in range(len(matrix)): for row in matrix: row[i]
31 Lists: Comprehensions Find the sum of the integers from 1 to 100 that are even, and not perfect squares.
32 Strings Immutable sequences of characters Use single or double quotes for one-line strings Use triple quotes for multi-line strings We can use many of the same operations as before as long as they didn t mutate the list
33 Strings >>> s = "hello" >>> s[0] 'h' >>> for i in s:... print i... h e l l o >>> s[0] = 'a' TypeError
34 Strings: Split >>> s = "Pretend this sentence makes sense." >>> s.split(" this ") ['Pretend', 'sentence makes sense.'] >>> words = s.split(" ") >>> words ['Pretend', 'this', 'sentence', 'makes', 'sense.']
35 Strings: Join >>> " ".join(words) 'Pretend this sentence makes sense.' >>> "_".join(words) 'Pretend_this_sentence_makes_sense.' Note that we are calling the join method of the object.
36 Strings: Join join only works on lists of strings, but... >>> a = [1, 2, 3] >>> " ".join([str(x) for x in a]) '1 2 3'
37 Strings: Find and Replace >>> s = "I wish I were home right now." >>> s.find('home') 14 >>> s.find('dinosaur') -1 >>> s = "I'm taking CIS 192." >>> s.replace('cis', 'Computer Science') "I'm taking Computer Science 192."
38 Strings: Case >>> s = 'dog' >>> s.capitalize() 'Dog' >>> s.upper() 'DOG' >>> s.lower() 'dog'
39 Strings: Stripping >>> s = ' hi --' >>> s.strip(' -') 'hi' >>> s.lstrip(' ') 'hi --'
40 Strings: Alphas and Digits >>> s = 'abc' >>> s.isalpha() True >>> s = '123' >>> s.isdigit() True >>> int(s) 123
41 Strings: Escape Characters >>> s = "a\nb" >>> s 'a\nb' >>> print s a b
42 Tuples Immutable lists Written using parentheses, not square brackets A way of packaging multiple values together Functions can return tuples, take tuples as arguments Immutability makes them more efficient
43 Tuples >>> a = [1,2] >>> b = (a, 3) >>> b ([1, 2], 3) >>> b[0] = 0 TypeError >>> a[0] = 0 >>> b ([0, 2], 3)
44 Tuples: Enumerate >>> a = ["apple", "orange", "banana"] >>> for (index, fruit) in enumerate(a):... print str(index) + ": " + fruit... 0: apple 1: orange 2: banana
45 Tuples: Enumerate Write a function tuple indices(l, position, value) that has the following behavior: >>> l = [("pineapple", 5), ("cherry", 7), ("kumquat", 3), ("plum", 7)] >>> tuple_indices(l, 1, 7) [1, 3] >>> tuple_indices(l, 0, "kumquat") [2]
46 Tuples: Zip >>> a = [1, 2, 3] >>> b = ['a', 'b', 'c'] >>> c = [4, 5, 6] >>> zip(a, b, c) [(1, 'a', 4), (2, 'b', 5), (3, 'c', 6)] Here zip has three arguments, but it can actually take a variable number.
47 Tuples: Singletons >>> a = ("Hi") >>> type(a) <type 'str'> >>> a = ("Hi",) >>> type(a) <type 'tuple'>
48 Tuples: String Formatting >>> "Hello, %s!" % "Annie" 'Hello, Annie!' >>> "A number: %s" % 5 'A number: 5' >>> "A list: %s" % [1, 2, 3] 'A list: [1, 2, 3]' Non-string objects are converted using str.
49 Tuples: String Formatting Use a tuple for multiple arguments: >>> "a = %s and b = %s" % ("apple", "banana") 'a = apple and b = banana' Can also perform type conversions explicitly: >>> "a = %d and b = %d" % (0, 1) 'a = 0 and b = 1' >>> "a = %d and b = %f" % (0, 1.5) 'a = 0 and b = ' >>> "a = %d and b = %.1f" % (0, 1.5) 'a = 0 and b = 1.5'
50 Tuples: String Formatting What if we wanted to print a tuple? >>> x = ("a", "b", "c") >>> "A tuple: %s" % x TypeError Instead: >>> "A tuple: %s" % (x,) "A tuple: ('a', 'b', 'c')"
51 Sidenote on String Formatting Another option, introduced in Python 2.6: >>> template = "{0} is {1} years old. {0} is a girl." >>> template.format("annie", 20) 'Annie is 20 years old. Annie is a girl.'
52 Tuples: Assigning Multiple Values at Once >>> v = ('a', 'b', 'c') >>> (x, y, z) = v >>> x 'a' >>> y 'b' >>> z 'c'
53 Tuples: Assignming Multiple Values at Once >>> def foo(x, y):... return (x,y)... >>> (a, b) = foo('a', 'b')
54 Dictionaries Key : Value pairs Implemented using hash tables So keys can be any hashable type strings numbers tuples ** not lists ** if they contain hashable types only!
55 Dictionaries >>> d = {'a': 1, 'b': 2, 'c': 3} >>> d['b'] 2 >>> d['b'] = 3 >>> d['b'] 3 >>> 'a' in d True >>> d.keys() ['a', 'c', 'b'] >>> d.values() [1, 3, 3]
56 Dictionaries >>> d = {'a': 1, 'b': 2, 'c': 3} >>> d['e'] KeyError: 'e' >>> d.get('e', 0) 0
57 Dictionaries: Iteration >>> d.items() [('a', 1), ('c', 3), ('b', 3)] >>> for (key, value) in d.items():... print "%s: %s" % (key, value)... a: 1 c: 3 b: 3
58 Dictionaries: Construction Dictionaries can also be constructed from lists of tuples. >>> e = dict([('first', 'a'), ('second', 'b')]) >>> e {'second': 'b', 'first': 'a'} >>> keys = ['a', 'b', 'c'] >>> values = [0, 0, 0] >>> e = dict(zip(keys, values)) >>> e {'a': 0, 'c': 0, 'b': 0}
59 Dictionaries: Construction >>> import string >>> alphabet = string.lowercase >>> alphabet 'abcdefghijklmnopqrstuvwxyz' >>> d = dict(zip(list(alphabet), [0]*len(alphabet))) >>> d {'a': 0, 'c': 0, 'b': 0, 'e': 0,...
60 Dictionaries: DefaultDict Counting character occurrences: d = {} # we see an 'a'! # don't know if it's the first one... if 'a' in d: d['a'] += 1 else: d['a'] = 1
61 Dictionaries: DefaultDict from collections import defaultdict >>> d = defaultdict(int) >>> d['a'] 0 >>> d['a'] += 1 >>> d = defaultdict(list) >>> d['a'] [] >>> d['a'].append(0)
62 Dictionaries vs. If/Elif Consider writing a function position(char) that takes a character as input and returns its position in the alphabet Don t do: if char == 'a': return 1 elif char == 'b'... Instead: alphabet = string.lowercase d = dict(zip(list(alphabet), range(1,27))) return d['c']
63 Shallow/Deep Copies >>> d1 = {'a': 1, 'b': 2} >>> d2 = d1 >>> d1['a'] = 5 >>> d2['a'] 5
64 Shallow/Deep Copies >>> d1 = {'a': 1, 'b': 2} >>> d2 = dict(d1) >>> d1['a'] = 5 >>> d2['a'] 1
65 Sets Lists, but without order or duplicates. Two common uses: 1. De-duplication of lists: >>> l = [1, 1, 2, 2, 3] >>> set(l) set([1, 2, 3])
66 Sets 2. Do you just need to know whether or not you ve already got a particular value? (And you don t need to know how many times?) >>> seen = set() >>> for i in ['abcabcdabcde']: seen.add(i) >>> seen set(['a', 'c', 'b', 'e', 'd'])
67 Sets But be careful can only use sets on hashable types! >>> s = set() >>> s.add([1]) TypeError: unhashable type: 'list'
Python Programming: Lecture 3 Functions
Python Programming: Lecture 3 Functions Lili Dworkin University of Pennsylvania Last Week s Quiz In one line, write code that will turn the list [9, 9, 9] into the string 90909. Last Week s Quiz In one
More informationCIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani
CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34
More informationA Brief Introduction to Python for those who know Java. (Last extensive revision: Daniel Moroz, fall 2015)
A Brief Introduction to Python for those who know Java (Last extensive revision: Daniel Moroz, fall 2015) Plan Day 1 Baby steps History, Python environments, Docs Absolute Fundamentals Objects, Types Math
More informationCIS192 Python Programming
CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types
More informationA Brief Introduction to Python for those who know Java Last extensive revision: Jie Gao, Fall 2018 Previous revisions: Daniel Moroz, Fall 2015
A Brief Introduction to Python for those who know Java Last extensive revision: Jie Gao, Fall 2018 Previous revisions: Daniel Moroz, Fall 2015 Meet the Mighty Python Plan Day 1 Baby steps History, Python
More informationCompound Data Types 1
Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:
More informationCS2304: 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 informationPython 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 informationLECTURE 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 informationCS 11 python track: lecture 3. n Today: Useful coding idioms
CS 11 python track: lecture 3 Today: Useful coding idioms Useful coding idioms "Idiom" Standard ways of accomplishing a common task Using standard idioms won't make your code more correct, but more concise
More informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu/program/philippines-summer-2012/ Philippines Summer 2012 Lecture 1 Introduction to Python June 19, 2012 Agenda About the Course What is
More informationBasic Scripting, Syntax, and Data Types in Python. Mteor 227 Fall 2017
Basic Scripting, Syntax, and Data Types in Python Mteor 227 Fall 2017 Basic Shell Scripting/Programming with Python Shell: a user interface for access to an operating system s services. The outer layer
More informationChapter 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 informationAccelerating Information Technology Innovation
Accelerating Information Technology Innovation http://aiti.mit.edu Cali, Colombia Summer 2012 Lesson 1 Introduction to Python Agenda What is Python? and Why Python? Basic Syntax Strings User Input Useful
More informationCSC148 Fall 2017 Ramp Up Session Reference
Short Python function/method descriptions: builtins : input([prompt]) -> str Read a string from standard input. The trailing newline is stripped. The prompt string, if given, is printed without a trailing
More information6. 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 informationStudent Number: Comments are not required except where indicated, although they may help us mark your answers.
CSC 108H5 F 2018 Midterm Test Duration 90 minutes Aids allowed: none Student Number: utorid: Last Name: First Name: Do not turn this page until you have received the signal to start. (Please fill out the
More informationCSC326 Python Sequences i. CSC326 Python Sequences
i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples
More informationPython 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 informationOverview 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[Software Development] Python (Part A) Davide Balzarotti. Eurecom Sophia Antipolis, France
[Software Development] Python (Part A) Davide Balzarotti Eurecom Sophia Antipolis, France 1 Homework Status 83 registered students 41% completed at least one challenge 5 command line ninjas 0 python masters
More informationSequences 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 informationGIS 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 informationPython 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 informationMUTABLE LISTS AND DICTIONARIES 4
MUTABLE LISTS AND DICTIONARIES 4 COMPUTER SCIENCE 61A Sept. 24, 2012 1 Lists Lists are similar to tuples: the order of the data matters, their indices start at 0. The big difference is that lists are mutable
More informationQuestion 1. Part (a) Part (b) December 2013 Final Examination Marking Scheme CSC 108 H1F. [13 marks] [4 marks] Consider this program:
Question 1. Part (a) [4 marks] Consider this program: [13 marks] def square(x): (number) -> number Write what this program prints, one line per box. There are more boxes than you need; leave unused ones
More informationThere 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 informationPython Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. PythonBasics
Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. http://ai.berkeley.edu/tutorial.html# PythonBasics Operators >>> 1 + 1 2 >>> 2 * 3 6 Boolean operators >>> 1==0 False >>> not (1==0) True >>> (2==2) and (2==3)
More informationPLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science
PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science DECEMBER 2013 EXAMINATIONS CSC 108 H1F Instructors: Craig and Gries Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number:
More informationData type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.
NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike
More informationQuiz 2 problems. 1. short answers
Quiz 2 problems 1. short answers >>> a = [2] >>> b = [a, a] >>> a.append(3) >>> b 2. sorting -- translate between 3 ways of sorting and compare them 3. number of interleavings -- memoization 4. weird quicksort
More informationUNIVERSITY OF TORONTO SCARBOROUGH. Wnter 2016 EXAMINATIONS. CSC A20H Duration 2 hours 45 mins. No Aids Allowed
Student Number: Last Name: First Name: UNIVERSITY OF TORONTO SCARBOROUGH Wnter 2016 EXAMINATIONS CSC A20H Duration 2 hours 45 mins No Aids Allowed Do not turn this page until you have received the signal
More informationPLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science
PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science SUMMER 2012 EXAMINATIONS CSC 108 H1Y Instructors: Janicki Duration NA PLEASE HAND IN Examination Aids: None Student Number: Family Name(s):
More informationScripting Languages. Python basics
Scripting Languages Python basics Interpreter Session: python Direct conversation with python (>>>) Python 3.5.2 (default, Nov 23 2017, 16:37:01) [GCC 5.4.0 20160609] on linux Type "help", "copyright",
More information(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.
Basics of Python - 2 by Kaustubh Vaghmare (IUCAA, Pune) E-mail: kaustubh[at]iucaa[dot]ernet[dot]in 1 of 54 Sunday 16 February 2014 05:30 PM Our First Program - Rewritten! Let us introduce the following
More informationMEIN 50010: Python Data Structures
: Python Data Structures Fabian Sievers Higgins Lab, Conway Institute University College Dublin Wednesday, 2017-10-18 Data Structures Stacks, Queues & Deques Structures Data structures are a way of storing
More informationThe Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 4 Working with Strings 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sequence of Characters We
More informationLists, 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'...' "..." escaping \u hhhh hhhh '''...''' """...""" raw string Example: r"abc\txyz\n" in code;
Strings Writing strings Strings can be written in single quotes, '...', or double quotes, "..." These strings cannot contain an actual newline Certain special characters can be written in these strings
More informationTypes, 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 informationIntroduction to Python
Introduction to Python Efstratios RAPPOS efstratios.rappos@heig-vd.ch Slide 1 2016 HEIG-VD SNU Summer School Background Easy and popular programming language Interpreted: must have python installed to
More informationPLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science
PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science APRIL 2012 EXAMINATIONS CSC 108 H1S Instructors: Campbell Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Family
More informationDSC 201: Data Analysis & Visualization
DSC 201: Data Analysis & Visualization Classes Dr. David Koop Tuple, List, Dictionary, or Set? [1,2,"abc"] 2 Tuple, List, Dictionary, or Set? {"a", 1, 2} 3 Tuple, List, Dictionary, or Set? {} 4 Tuple,
More informationSome material adapted from Upenn cmpe391 slides and other sources
Some material adapted from Upenn cmpe391 slides and other sources History Installing & Running Python Names & Assignment Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics
More informationMITOCW watch?v=rvrkt-jxvko
MITOCW watch?v=rvrkt-jxvko The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high quality educational resources for free. To
More informationProgramming 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 informationModule 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists
Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',
More informationList 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 informationCSCA20 Worksheet Strings
1 Introduction to strings CSCA20 Worksheet Strings A string is just a sequence of characters. Why do you think it is called string? List some real life applications that use strings: 2 Basics We define
More informationPython language: Basics
Python language: Basics The FOSSEE Group Department of Aerospace Engineering IIT Bombay Mumbai, India FOSSEE Team (FOSSEE IITB) Basic Python 1 / 45 Outline 1 Data types Numbers Booleans Strings 2 Operators
More informationPython BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.
Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Identikit First appeared in 1991 Designed by Guido van Rossum General purpose High level
More informationPROGRAMMING IN HASKELL. Chapter 5 - List Comprehensions
PROGRAMMING IN HASKELL Chapter 5 - List Comprehensions 0 Set Comprehensions In mathematics, the comprehension notation can be used to construct new sets from old sets. {x 2 x {1...5}} The set {1,4,9,16,25}
More informationCollections. 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 informationChapter 2: Lists, Arrays and Dictionaries
Chapter 2: Lists, Arrays and Dictionaries 1. Higher order organization of data In the previous chapter, we have seen the concept of scalar variables that define memory space in which we store a scalar,
More informationInteractive 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(CC)A-NC 2.5 by Randall Munroe Python
http://xkcd.com/353/ (CC)A-NC 2.5 by Randall Munroe Python Python: Operative Keywords Very high level language Language design is focused on readability Mulit-paradigm Mix of OO, imperative, and functional
More informationGE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING
GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why
More informationCS Advanced Unix Tools & Scripting
& Scripting Spring 2011 Hussam Abu-Libdeh slides by David Slater March 4, 2011 Hussam Abu-Libdeh slides by David Slater & Scripting Python An open source programming language conceived in the late 1980s.
More informationThe current topic: Python. Announcements. Python. Python
The current topic: Python Announcements! Introduction! reasons for studying languages! language classifications! simple syntax specification Object-oriented programming: Python Types and values Syntax
More informationPython: Short Overview and Recap
Python: Short Overview and Recap Benjamin Roth CIS LMU Benjamin Roth (CIS LMU) Python: Short Overview and Recap 1 / 39 Data Types Object type Example creation Numbers (int, float) 123, 3.14 Strings this
More informationAlgorithms for Bioinformatics
These slides are based on previous years slides of Alexandru Tomescu, Leena Salmela and Veli Mäkinen 582670 Algorithms for Bioinformatics Lecture 1: Primer to algorithms and molecular biology 2.9.2014
More information\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 informationScript language: Python Data structures
Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what
More informationOOP and Scripting in Python Advanced Features
OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary
More informationCSCE 110 Programming I
CSCE 110 Programming I Basics of Python (Part 3): Functions, Lists, For Loops, and Tuples Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani
More informationExercise: 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 informationData Structures. Dictionaries - stores a series of unsorted key/value pairs that are indexed using the keys and return the value.
Data Structures Lists - stores a series of ordered mutable items Tuples - stores a series of ordered immutable items [not commonly used] Sets - stores a series of mutable or immutable(frozen) unsorted
More informationENGR 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 informationA lot of people make repeated mistakes of not calling their functions and getting errors. Make sure you're calling your functions.
Handout 2 Functions, Lists, For Loops and Tuples [ ] Functions -- parameters/arguments, "calling" functions, return values, etc. Please make sure you understand this example: def square(x): return x *
More informationUNIVERSITY OF TORONTO SCARBOROUGH. December 2017 EXAMINATIONS. CSCA20H3 Duration 3 hours. Examination Aids: Instructor: Bretscher
PLEASE HAND IN UNIVERSITY OF TORONTO SCARBOROUGH December 2017 EXAMINATIONS CSCA20H3 Duration 3 hours PLEASE HAND IN Examination Aids: None Student Number: Last (Family) Name(s): First (Given) Name(s):
More informationInteractive 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 informationCMSC201 Computer Science I for Majors
CMSC201 Computer Science I for Majors Lecture 12 Tuples All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Modularity Meaning Benefits Program design Last Class We Covered Top
More informationPython 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 informationChapter 8 Dictionaries. Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values.
Chapter 8 Dictionaries Dictionaries are mutable, unordered collections with elements in the form of a key:value pairs that associate keys to values. Creating a Dictionary To create a dictionary, you need
More informationHello, World. Java. #include <stdio.h> int main(int argc, char ** argv) {! printf( Hello, World!\n ); }
Why Python? Because it s easy and great fun! only 15 years old, yet very popular now a wide-range of applications, esp. in AI and Web extremely easy to learn many schools have shifted their intro-courses
More informationList comprehensions (and other shortcuts) UW CSE 160 Spring 2015
List comprehensions (and other shortcuts) UW CSE 160 Spring 2015 Three Ways to Define a List Explicitly write out the whole thing: squares = [0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100] Write a loop to create
More informationPython for ArcGIS. Lab 1.
Python for ArcGIS. Lab 1. Python is relatively new language of programming, which first implementation arrived around early nineties of the last century. It is best described as a high level and general
More informationMidterm 1 Review. Important control structures. Important things to review. Functions Loops Conditionals
Midterm 1 Review Important control structures Functions Loops Conditionals Important things to review Binary numbers Boolean operators (and, or, not) String operations: len, ord, +, *, slice, index List
More informationAbout the Final. Saturday, 7-10pm in Science Center 101. Closed book, closed notes. Not on the final: graphics, file I/O, vim, unix
CS 21 Final Review About the Final Saturday, 7-10pm in Science Center 101 Closed book, closed notes Not on the final: graphics, file I/O, vim, unix Expect Questions That Ask You To: Evaluate Python expressions
More informationProgramming in Python
3. Sequences: Strings, Tuples, Lists 15.10.2009 Comments and hello.py hello.py # Our code examples are starting to get larger. # I will display "real" programs like this, not as a # dialog with the Python
More informationExercise: 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 informationLists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10
Lists in Python CS 8: Introduction to Computer Science, Winter 2018 Lecture #10 Ziad Matni Dept. of Computer Science, UCSB Administrative Homework #5 is due today Homework #6 is out and DUE on MONDAY (3/5)
More informationSets and Dictionaries
Copyright Software Carpentry 2010 This work is licensed under the Creative Commons Attribution License See http://software-carpentry.org/license.html for more information. Let's try an experiment Let's
More informationCIS192 Python Programming. Robert Rand. August 27, 2015
CIS192 Python Programming Introduction Robert Rand University of Pennsylvania August 27, 2015 Robert Rand (University of Pennsylvania) CIS 192 August 27, 2015 1 / 30 Outline 1 Logistics Grading Office
More informationThe Pyth Language. Administrivia
Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.
More informationCSE 130, Winter 2011: Final Examination
Name: ID : CSE 130, Winter 2011: Final Examination March 15, 2011 Do not start the exam until you are told to. This is a open-book, open-notes exam, but with no computational devices allowed (such as calculators/cellphones/laptops).
More informationDictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections
Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for
More informationPython Basics. 1 of 7 9/5/2018, 8:51 AM. txt1 = "ada lovelace, english mathematician and writer" print(txt1)
1 of 7 9/5/2018, 8:51 AM Python Basics In [1]: txt1 = "ada lovelace, english mathematician and writer" print(txt1) ada lovelace, english mathematician and writer Here txt1 is a variable and "ada lovelace,
More informationCOMP519 Web Programming Lecture 17: Python (Part 1) Handouts
COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents
More informationThe 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 informationStrings are actually 'objects' Strings
Strings are actually 'objects' Strings What is an object?! An object is a concept that we can encapsulate data along with the functions that might need to access or manipulate that data. What is an object?!
More informationKey Differences Between Python and Java
Python Python supports many (but not all) aspects of object-oriented programming; but it is possible to write a Python program without making any use of OO concepts. Python is designed to be used interpretively.
More informationHaske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell
Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program
More informationPython Programming Language
Python Programming Language Data Structure Sachin PVPPCOE December 22, 2015 Data types Basic objects: numbers(float, int, complex), strings, Tuples, lists, sets, & dictionaries Other data types: Modules,
More informationIntro. Scheme Basics. scm> 5 5. scm>
Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if
More informationCSC324- TUTORIAL 5. Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides
CSC324- TUTORIAL 5 ML Shems Saleh* *Some slides inspired by/based on Afsaneh Fazly s slides Assignment 1 2 More questions were added Questions regarding the assignment? Starting ML Who am I? Shems Saleh
More informationPart 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 informationUnit 2. Srinidhi H Asst Professor
Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence
More informationSequence 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 informationCMPT 120 Lists and Strings. Summer 2012 Instructor: Hassan Khosravi
CMPT 120 Lists and Strings Summer 2012 Instructor: Hassan Khosravi All of the variables that we have used have held a single item One integer, floating point value, or string often you find that you want
More information