CSCE 110 Programming I

Size: px
Start display at page:

Download "CSCE 110 Programming I"

Transcription

1 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 L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

2 Defining a Function A function is a named block of statements that performs an operation. To define a function, we use the following syntax: def func(param_list): block When executed, this compound statement creates a new function object and assigns it to the name func. func is a valid Python name (think of valid variable names), param_list represents zero or more comma-separated parameters, and block is an indented block of statements. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

3 Function Examples (1) Listing 1: function-example.py 1 # A simple example of how to use functions 2 3 def print_msg (): 4 print "I love Python!" 5 6 def iseven ( num ): 7 print num % 2 == print_msg () 10 iseven (10) 11 iseven (7) Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

4 Function Examples (2) Listing 2: temperature-converter.py 1 # Converts the temperature to Celsius or Fahrenheit 2 3 def to_fahrenheit (c): # Convert celsius to fahrenheit 4 return (c * 9.0/5.0) def to_celsius (f): # Convert fahrenheit to celsius 7 return (f - 32) * 5.0/ type = raw_input (" Convert temperature to Celsius or Fahrenheit (c or f)? ") 10 if type == c : 11 temperature = int ( raw_input (" Enter Fahrenheit temperature : ")) 12 celsius = to_celsius ( temperature ) 13 print "%d Fahrenheit is %d Celsius." % ( temperature, celsius ) 14 else : 15 temperature = int ( raw_input (" Enter Celsius temperature : ")) 16 fahrenheit = to_fahrenheit ( temperature ) 17 print "%d Celsius is %d Fahrenheit." % ( temperature, fahrenheit ) Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

5 Function Examples (3) Listing 3: temperature-converter2.py 1 # Converts the temperature to Celsius or Fahrenheit. Uses a main function 2 # to drive the program. 3 4 def to_fahrenheit (c): # Convert celsius to fahrenheit 5 return (c * 9.0/5.0) def to_celsius (f): # Convert fahrenheit to celsius 8 return (f - 32) * 5.0/ def main (): 11 type = raw_input (" Convert temperature to Celsius or Fahrenheit (c or f)? ") 12 if type == c : 13 temperature = int ( raw_input (" Enter Fahrenheit temperature : ")) 14 celsius = to_celsius ( temperature ) 15 print "%d Fahrenheit is %d Celsius." % ( temperature, celsius ) 16 else : 17 temperature = int ( raw_input (" Enter Celsius temperature : ")) 18 fahrenheit = to_fahrenheit ( temperature ) 19 print "%d Celsius is %d Fahrenheit." % ( temperature, fahrenheit ) # Execution of the program begins here 22 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

6 Built-in Functions abs() divmod() input() open() staticmethod() all() enumerate() int() ord() str() any() eval() isinstance() pow() sum() basestring() execfile() issubclass() print() super() bin() file() iter() property() tuple() bool() filter() len() range() type() bytearray() float() list() raw_input() unichr() callable() format() locals() reduce() unicode() chr() frozenset() long() reload() vars() classmethod() getattr() map() repr() xrange() cmp() globals() max() reversed() zip() compile() hasattr() memoryview() round() import () complex() hash() min() set() apply() delattr() help() next() setattr() buffer() dict() hex() object() slice() coerce() dir() id() oct() sorted() intern() Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

7 Local and Global Variables (1) Listing 4: local-global-variables.py 1 # An example showing the difference between local and global variables. 2 v = 15 # v is a global variable 3 4 def f1 (): 5 v = 17 # v is a local variable 6 print v(f1 ):, v 7 v = v print v(f1 ):, v 9 10 def f2 (): 11 print v(f2 ):, v # since v is not local, global version is used f1 () 14 f2 () 15 print v:, v # references global version of v Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

8 Local and Global Variables (2) Listing 5: local-global-variables2.py 1 # This program has an error. Find it and explain why it is in fact an error. 2 3 v = def f1 (): 6 v = 17 7 print v(f1 ):, v 8 9 def f2 (): 10 v = v print v(f2 ):, v f1 () 14 f2 () 15 print v:, v Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

9 Lists Ordered collection of data. Example: some_data = [ dog, 78, 87.0, gorilla ] Elements can be of different types (heterogeneous) Can have a mixture of strings, ints, floats, lists, etc. Composed of elements that can be accessed by indexing Can create sublists by specifying an index range This is accomplished with the slicing operator [:] or [::] You can change individual elements directly ( mutable ) Unlike strings, each element in a list can be modified List creation operator [ ], elements of the list are separated by commas Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

10 List Examples (Python Shell) 1 >>> alist = [1, 2, 3, 4] # list creation 2 >>> alist 3 [1, 2, 3, 4] 4 5 >>> alist [0] # indexing individual elements >>> alist [2:] # creating sublist 9 [3, 4] >>> alist [:3] # creating sublist 12 [1, 2, 3] >>> alist [1] = 5 # mutable 15 >>> alist 16 [1, 5, 3, 4] Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

11 List Examples (Python Shell) 1 >>> alist = [1, 2, 3, 4] # list creation 2 >>> alist 3 [1, 2, 3, 4] 4 5 >>> alist [0] # indexing individual elements >>> alist [2:] # creating sublist 9 [3, 4] >>> alist [:3] # creating sublist 12 [1, 2, 3] >>> alist [1] = 5 # mutable 15 >>> alist 16 [1, 5, 3, 4] Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

12 for Loop for iter_var in iterable: suite_to_repeat Objects that are iterable include strings, lists, and tuples. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

13 for Loop Examples Listing 6: for-example.py 1 for eachletter in " Names ": 2 print " current letter :", eachletter Listing 7: for-example2.py 1 name_list = [ Walter, " Nicole ", Steven ] # iterating over a list 2 for each_name in name_list : 3 print each_name, " Smith " Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

14 while vs for loops Listing 8: while-vs-for.py 1 # Shows the difference between while and for loops by 2 # printing the numbers from 1 to print " while loop : Printing the numbers from 1 to 5." 5 i = 1 6 while i < 6: # could also write while i <= 5: 7 print i 8 i += print "\ nfor loop : Printing the numbers from 1 to 5." 11 for i in range (1,6): # range (1,6) creates the list [1, 2, 3, 4, 5] 12 print i Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

15 Integer to English Conversion Given an integer value, return a string with the equivalent English text of each digit. For example, an input of 89 results in eight-nine being returned. For an extra challenge, return English text with proper usage, i.e., eighty-nine. For this problem, restrict values to be between 0 and 1,000. Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

16 Integer to English (Version 1) I Listing 9: integer-to-english1.py 1 # A program that converts an integer between 0 and 1,000 to its English equivalent. 2 3 # Returns the English equivalent of the numbers 0 to 9. 4 def convert ( digit ): 5 6 if digit == 0 : 7 name = zero 8 elif digit == 1 : 9 name = one 10 elif digit == 2 : 11 name = two 12 elif digit == 3 : 13 name = three 14 elif digit == 4 : 15 name = four 16 elif digit == 5 : 17 name = five 18 elif digit == 6 : 19 name = six 20 elif digit == 7 : 21 name = seven 22 elif digit == 8 : 23 name = eight 24 else : 25 name = nine return name Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

17 Integer to English (Version 1) II # Obtains the user s input and farms the work. 31 def main (): result = 34 number = raw_input ( Please enter an integer between 0 and 1000: ) for digit in number : 37 result += convert ( digit ) print %s is %s. % (number, result [: len ( result ) -1]) # Execution begins here. 43 main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

18 Integer to English (Version 2) Listing 10: integer-to-english1a.py 1 # A program that converts an integer between 0 and 1,000 to its English equivalent. 2 # Easy version. 3 4 # Returns the English equivalent of the numbers 0 to 9. 5 def convert ( digit ): 6 name = [ zero, one, two, three, four, five, 7 six, seven, eight, nine ] 8 return name [int ( digit )] # Obtains the user s input and farms the work. 12 def main (): result = [] 15 number = raw_input ( Please enter an integer between 0 and 1000: ) for digit in number : 18 result += [ convert ( digit )] result = -.join ( result ) print %s is %s. % ( number, result ) main () Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

19 Tuples Tuples are similar to lists except for one important difference. Unlike lists, tuples are immutable. Example: some_data = ( dog, 78, 87.1, gorilla ) An element in a tuple cannot be changed. In that sense, both strings and tuples share the immutability criterion. Reason for immutability: you don t want variable s contents to be accidentally overwritten. Tuple creation operator ( ), elements of the list are separated by commas Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

20 Tuple Examples (Python Shell) 1 >>> atuple = ( robots, 77, 93, try ) # tuple creation 2 >>> atuple 3 ( robots, 77, 93, try ) 4 5 >>> atuple [:3] # creating subtuples 6 ( robots, 77, 93) 7 8 >>> atuple [1] = 5 # immutable 9 10 Traceback ( most recent call last ): 11 File "<string >", line 1, in <fragment > 12 TypeError : tuple object does not support item assignment Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

21 Concatenating Lists or Tuples Examples (Python Shell) 1 >>> alist = [1, 2, 3] # list creation 2 >>> alist + [4, 5] # list concatenation 3 [1, 2, 3, 4, 5] 4 5 >>> atuple = ( four, five ) # tuple creation 6 >>> atuple + ( six ) # immutable 7 Traceback ( most recent call last ): 8 File "<string >", line 1, in <fragment > 9 TypeError : can only concatenate tuple ( not " str ") to tuple >>> alist # print alist 12 [1, 2, 3] 13 >>> atuple # print atuple 14 ( four, five ) 15 >>> alist + [ atuple ] # concatenate list and tuple as a list 16 [1, 2, 3, ( four, five )] >>> alist + atuple # immutable Traceback ( most recent call last ): 21 File "<string >", line 1, in <fragment > 22 TypeError : can only concatenate list (not " tuple ") to list Tiffani L. Williams (Texas A&M) CSCE 110: Basics of Python (Part 3) Spring / 21

CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions

CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions CSCE 110 Programming I Basics of Python: Lists, Tuples, and Functions Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Fall 2011 Lists Ordered collection of data.

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

Python Reference (The Right Way) Documentation

Python Reference (The Right Way) Documentation Python Reference (The Right Way) Documentation Release 0.1 Jakub Przywóski Sep 30, 2017 Contents 1 Contents 1 1.1 Introduction............................................... 1 1.2 Definitions................................................

More information

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : }

contacts= { bill : , rich : , jane : } print contacts { jane : , bill : , rich : } Chapter 8 More Data Structures We have seen the list data structure and its uses. We will now examine two, more advanced data structures: the set and the dictionary. In particular, the dictionary is an

More information

Modules and scoping rules

Modules and scoping rules C H A P T E R 1 1 Modules and scoping rules 11.1 What is a module? 106 11.2 A first module 107 11.3 The import statement 109 11.4 The module search path 110 11.5 Private names in modules 112 11.6 Library

More information

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output

CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output CSCE 110 Programming I Basics of Python: Variables, Expressions, Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2011 Python Python was developed

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

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

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Basics of Python (Part 1): Variables, Expressions, and Input/Output Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2013 Tiffani

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 3000 and You. Guido van Rossum PyCon March 14, 2008

Python 3000 and You. Guido van Rossum PyCon March 14, 2008 Python 3000 and You Guido van Rossum PyCon March 14, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print

More information

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points)

Part 1 (80 points) Multiple Choice Questions (20 questions * 4 points per question = 80 points) EECS 183 Fall 2013 Exam 1 Part 1 (80 points) Closed Book Closed Notes Closed Electronic Devices Closed Neighbor Turn off Your Cell Phones We will confiscate all electronic devices that we see including

More information

CNRS ANF PYTHON Objects everywhere

CNRS ANF PYTHON Objects everywhere CNRS ANF PYTHON Objects everywhere Marc Poinot Numerical Simulation Dept. Outline Python Object oriented features Basic OO concepts syntax More on Python classes multiple inheritance reuse introspection

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

Python: common syntax

Python: common syntax Lab 09 Python! Python Intro Main Differences from C++: True and False are capitals Python floors (always down) with int division (matters with negatives): -3 / 2 = -2 No variable data types or variable

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

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

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

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

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

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

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

VALLIAMMAI ENGINEERING COLLEGE

VALLIAMMAI ENGINEERING COLLEGE VALLIAMMAI ENGINEERING COLLEGE SRM Nagar, Kattankulathur 60 20 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING QUESTION BANK B.E I SEMESTER GE85- Problem Solving and Python Programming Regulation 207 Academic

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

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

MUTABLE LISTS AND DICTIONARIES 4

MUTABLE 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 information

(IUCAA, Pune) kaustubh[at]iucaa[dot]ernet[dot]in.

(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 information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

The Pyth Language. Administrivia

The 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 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

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

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

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008

Python 3000 and You. Guido van Rossum EuroPython July 7, 2008 Python 3000 and You Guido van Rossum EuroPython July 7, 2008 Why Py3k Open source needs to move or die Matz (creator of Ruby) To fix early, sticky design mistakes e.g. classic classes, int division, print

More information

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont.

ECS15, Lecture 14. Reminder: how to learn Python. Today is the final day to request a regrade of the midterm. Topic 4: Programming in Python, cont. ECS15, Lecture 14 Today is the final day to request a regrade of the midterm Topic 4: Programming in Python, cont. Turn in a short cover letter explaining the issue. Reminder: how to learn Python Type

More information

Lists How lists are like strings

Lists How lists are like strings Lists How lists are like strings A Python list is a new type. Lists allow many of the same operations as strings. (See the table in Section 4.6 of the Python Standard Library Reference for operations supported

More information

Python for ArcGIS. Lab 1.

Python 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 information

Script language: Python Data structures

Script 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 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

CSCE 110 Programming I

CSCE 110 Programming I CSCE 110 Programming I Simulations and Plotting Data Dr. Tiffani L. Williams Department of Computer Science and Engineering Texas A&M University Spring 2014 Tiffani L. Williams (Texas A&M) CSCE 110) Spring

More information

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

Exam 1 Format, Concepts, What you should be able to do, and Sample Problems CSSE 120 Introduction to Software Development Exam 1 Format, Concepts, What you should be able to do, and Sample Problems Page 1 of 6 Format: The exam will have two sections: Part 1: Paper-and-Pencil o

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

Fundamentals of Programming (Python) Getting Started with Programming

Fundamentals of Programming (Python) Getting Started with Programming Fundamentals of Programming (Python) Getting Started with Programming Ali Taheri Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

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

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

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

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

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania 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)

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

CS Summer 2013

CS Summer 2013 CS 1110 - Summer 2013 intro to programming -- how to think like a robot :) we use the Python* language (www.python.org) programming environments (many choices): Eclipse (free from www.eclipse.org), or

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

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015

CS 115 Exam 1, Fall 2015 Thu. 09/24/2015 CS 115 Exam 1, Fall 2015 Thu. 09/24/2015 Name: Section: Rules and Hints You may use one handwritten 8.5 11 cheat sheet (front and back). This is the only additional resource you may consult during this

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ TUPLES 2 Tuples as Immutable Sequences tuple =

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

CIS192 Python Programming. Robert Rand. August 27, 2015

CIS192 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 information

cs1114 REVIEW of details test closed laptop period

cs1114 REVIEW of details test closed laptop period python details DOES NOT COVER FUNCTIONS!!! This is a sample of some of the things that you are responsible for do not believe that if you know only the things on this test that they will get an A on any

More information

Getting Started with Python

Getting Started with Python Fundamentals of Programming (Python) Getting Started with Python Sina Sajadmanesh Sharif University of Technology Some slides have been adapted from Python Programming: An Introduction to Computer Science

More information

Introduction to Python

Introduction to Python Introduction to Python Reading assignment: Perkovic text, Ch. 1 and 2.1-2.5 Python Python is an interactive language. Java or C++: compile, run Also, a main function or method Python: type expressions

More information

Chapter 2 Writing Simple Programs

Chapter 2 Writing Simple Programs Chapter 2 Writing Simple Programs Charles Severance Textbook: Python Programming: An Introduction to Computer Science, John Zelle (www.si182.com) Software Development Process Figure out the problem - for

More information

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi

CMPT 120 Basics of Python. Summer 2012 Instructor: Hassan Khosravi CMPT 120 Basics of Python Summer 2012 Instructor: Hassan Khosravi Python A simple programming language to implement your ideas Design philosophy emphasizes code readability Implementation of Python was

More information

Advanced Algorithms and Computational Models (module A)

Advanced Algorithms and Computational Models (module A) Advanced Algorithms and Computational Models (module A) Giacomo Fiumara giacomo.fiumara@unime.it 2014-2015 1 / 34 Python's built-in classes A class is immutable if each object of that class has a xed value

More information

Webgurukul Programming Language Course

Webgurukul Programming Language Course Webgurukul Programming Language Course Take One step towards IT profession with us Python Syllabus Python Training Overview > What are the Python Course Pre-requisites > Objectives of the Course > Who

More information

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming

Lecture Writing Programs. Richard E Sarkis CSC 161: The Art of Programming Lecture Writing Programs Richard E Sarkis CSC 161: The Art of Programming Class Administrivia Agenda To be able to understand and write Python statements to output information to the screen To assign values

More information

The Big Python Guide

The Big Python Guide The Big Python Guide Big Python Guide - Page 1 Contents Input, Output and Variables........ 3 Selection (if...then)......... 4 Iteration (for loops)......... 5 Iteration (while loops)........ 6 String

More information

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han

Lesson 4: Type Conversion, Mutability, Sequence Indexing. Fundamentals of Text Processing for Linguists Na-Rae Han Lesson 4: Type Conversion, Mutability, Sequence Indexing Fundamentals of Text Processing for Linguists Na-Rae Han Objectives Python data types Mutable vs. immutable object types How variable assignment

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data 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 information

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

PYTHON FOR MEDICAL PHYSICISTS. Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital PYTHON FOR MEDICAL PHYSICISTS Radiation Oncology Medical Physics Cancer Care Services, Royal Brisbane & Women s Hospital TUTORIAL 1: INTRODUCTION Thursday 1 st October, 2015 AGENDA 1. Reference list 2.

More information

Python - Variable Types. John R. Woodward

Python - Variable Types. John R. Woodward Python - Variable Types John R. Woodward Variables 1. Variables are nothing but named reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.

More information

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

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

CS Advanced Unix Tools & Scripting

CS 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 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

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012

Computing with Strings. Learning Outcomes. Python s String Type 9/23/2012 Computing with Strings CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01 Discussion Sections 02-08, 16, 17 1 Learning Outcomes To understand the string data type and how strings are represented

More information

Comp Exam 1 Overview.

Comp Exam 1 Overview. Comp 170-400 Exam 1 Overview. Resources During the Exam The exam will be closed book, no calculators or computers, except as a word processor. In particular no Python interpreter running in a browser or

More information

CS 1301 Final Exam Review Guide

CS 1301 Final Exam Review Guide CS 1301 Final Exam Review Guide A. Programming and Algorithm 1. Binary, Octal-decimal, Decimal, and Hexadecimal conversion Definition Binary (base 2): 10011 = 1*2 4 + 0*2 3 + 0*2 2 + 1*2 1 + 1*2 0 Octal-decimal

More information

1 RPN (Danny Yoo / Donovan Preston)

1 RPN (Danny Yoo / Donovan Preston) 1 RPN (Danny Yoo / Donovan Preston) This code implements a reverse polish notation calculator. It s deliberately written in a slightly weird way to avoid being taken used as a homework answer. 1 """ RPN

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

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

Swift. Introducing swift. Thomas Woodfin

Swift. Introducing swift. Thomas Woodfin Swift Introducing swift Thomas Woodfin Content Swift benefits Programming language Development Guidelines Swift benefits What is Swift Benefits What is Swift New programming language for ios and OS X Development

More information

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd.

Python Training. Complete Practical & Real-time Trainings. A Unit of SequelGate Innovative Technologies Pvt. Ltd. Python Training Complete Practical & Real-time Trainings A Unit of. ISO Certified Training Institute Microsoft Certified Partner Training Highlights : Complete Practical and Real-time Scenarios Session

More information

Python. Department of Computer Science And Engineering. European University Cyprus

Python. Department of Computer Science And Engineering. European University Cyprus 1 Python VICKY PAPADOPOULOU LESTA, Assistant Professor, Member at AHPC group MICHALIS KYPRIANOU, member of the AHPC group(internship project) Department of Computer Science And Engineering European University

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

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 1 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

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

The current topic: Python. Announcements. Python. Python

The 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 information

More Loop Examples Functions and Parameters

More Loop Examples Functions and Parameters More Loop Eamples Functions and Parameters Eample: min difference Given two of numbers, compute the minimum difference among any pair of numbers, one from each. E.g., 1 = [1, 2, 3, 4], 2 = [-2, 10, 5,

More information

Introduction to Python

Introduction to Python Introduction to Python Michael Krisper Thomas Wurmitzer March 22, 2014 Michael Krisper, Thomas Wurmitzer Introduction to Python March 22, 2014 1 / 27 Schedule Tutorium Dates & Deadlines Submission System

More information

Course Title: Python + Django for Web Application

Course Title: Python + Django for Web Application Course Title: Python + Django for Web Application Duration: 6 days Introduction This course offer Python + Django framework ( MTV ) training with hands on session using Eclipse+Pydev Environment. Python

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

Part III Appendices 165

Part III Appendices 165 Part III Appendices 165 Appendix A Technical Instructions Learning Outcomes This material will help you learn how to use the software you need to do your work in this course. You won t be tested on it.

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

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

Introduction to Python (All the Basic Stuff)

Introduction to Python (All the Basic Stuff) Introduction to Python (All the Basic Stuff) 1 Learning Objectives Python program development Command line, IDEs, file editing Language fundamentals Types & variables Expressions I/O Control flow Functions

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

Data Structures. Lists, Tuples, Sets, Dictionaries

Data Structures. Lists, Tuples, Sets, Dictionaries Data Structures Lists, Tuples, Sets, Dictionaries Collections Programs work with simple values: integers, floats, booleans, strings Often, however, we need to work with collections of values (customers,

More information

Downloaded from Chapter 2. Functions

Downloaded from   Chapter 2. Functions Chapter 2 Functions After studying this lesson, students will be able to: Understand and apply the concept of module programming Write functions Identify and invoke appropriate predefined functions Create

More information

CITS 4406 Problem Solving & Programming

CITS 4406 Problem Solving & Programming CITS 4406 Problem Solving & Programming Tim French Lecture 02 The Software Development Process (These slides are based on John Zelle s powerpoint slides for lectures accompanied with the text book) Objectives

More information

Programming in Python

Programming 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 information